Binance API: ошибка 403 в скрипте Python, который не нарушает ограничения скорости. Как найти проблему?Python

Программы на Python
Ответить
Anonymous
 Binance API: ошибка 403 в скрипте Python, который не нарушает ограничения скорости. Как найти проблему?

Сообщение Anonymous »

Я разработал скрипт Python, который выполняет следующие задачи:
  • Получает список всех котируемых пар USDT во фьючерсах binance, используя конечную точку API. : /fapi/v1/exchangeInfo
    Я использую для этого функцию:

Код: Выделить всё

def get_symbol_names():
symbols_list = []
base_url = 'https://fapi.binance.com'
endpoint = '/fapi/v1/exchangeInfo'
params = {}

try:
response = requests.get(base_url + endpoint, params=params)
response.raise_for_status()
response_data = response.json()
for symbol in response_data["symbols"]:
if (symbol["quoteAsset"] == "USDT"):
symbols_list.append(symbol["symbol"])

return symbols_list

except requests.exceptions.ConnectionError:
print("Network error: Unable to connect to the internet or the API server.")
except requests.exceptions.HTTPError as http_err:
print(f"Server error: {http_err}")
except requests.exceptions.RequestException as err:
print(f"An unexpected error occurred: {err}")

return None  # Return None if there was an error
  • Для каждой пары в списке с помощью цикла for затем были получены последние 50 строк, используя конечную точку API: /fapi /v1/klines
    Я использую для этого функцию:

Код: Выделить всё

def get_kline_data(symbol, interval='4h', limit=50):
"""
Fetches kline (candlestick) data from the Binance API.

Parameters:
symbol (str): The symbol pair to fetch data for, e.g., 'SUIUSDT'.
interval (str): The time interval between klines, e.g., '4h'.
limit (int): The maximum number of data points to retrieve.

Returns:
list: JSON response containing the kline data if successful, otherwise None.
"""
base_url = 'https://fapi.binance.com'
endpoint = '/fapi/v1/klines'
params = {
'symbol': symbol,
'interval': interval,
'limit': limit
}

try:
response = requests.get(base_url + endpoint, params=params)
response.raise_for_status()
return response.json()

except requests.exceptions.ConnectionError:
print("Network error: Unable to connect to the internet or the API server.")
except requests.exceptions.HTTPError as http_err:
print(f"Server error: {http_err}")
except requests.exceptions.RequestException as err:
print(f"An unexpected error occurred:  {err}")

return None  # Return None if there was an error
  • Выполняйте анализ полученных данных локально, не подключаясь к API binance для чего-либо еще.
    Код всего этого:

Код: Выделить всё

import time
from get_data_from_api import get_symbol_names
from get_data_from_api import get_kline_data
from create_chart import create_chart
from analyze_kline_data import identify_areas_of_interest
from db_manager import check_areas_of_interest_table_in_db
from db_manager import clear_recent_breaches_table_in_db
from db_manager import update_areas_of_interest_in_db
from db_manager import update_recent_breaches_table
from analyze_aois_in_db import analyze_old_aois_in_db
from analyze_aois_in_db import filter_recent_breaches

# Call the function to get data
clear_recent_breaches_table_in_db()
#this function clears the old data in recent breaches table
#clearing old data is important because every time new analysis is run, the old data becomes reduntant
check_areas_of_interest_table_in_db()
symbols = get_symbol_names()
time.sleep(2)
if symbols:
for symbol in symbols:
data = get_kline_data(symbol,'4h',50)
if data:
areas_of_interest = identify_areas_of_interest(data)
combined_aois = analyze_old_aois_in_db(symbol,data,areas_of_interest) # this analyzes the old aois in db to check if they are breached during down-time and adds the ones that are breached with all (both breached and open) fresh ones so that db can be updated properly
recent_breaches = filter_recent_breaches(data,combined_aois)
if recent_breaches:
update_recent_breaches_table(symbol,recent_breaches)
print(f"Recent breaches updated in DB for {symbol}")
create_chart(data, areas_of_interest,symbol)

update_areas_of_interest_in_db(symbol,areas_of_interest)
print(f"Analysis completed, chart created and DB updated for {symbol}")
time.sleep(1)

print("Operation Complete")
Согласно моим первоначальным тестам, обработка получения данных для всех пар занимает около 5 минут. Согласно весу использования, указанному в документации API, конечная точка «/fapi/v1/klines» с пределом 0–100 имеет вес 1. Это означает, что мой общий вес использования за 5 минут составляет 300–400
Однако сегодня при запуске этого скрипта я получил ошибку 403. (Я запускал/тестировал его в течение последних 3-4 дней без каких-либо проблем).
Что я делаю неправильно, из-за чего у меня возникла ошибка 403. Я пытался просмотреть документацию, чтобы найти причину, но это ни к чему не привело. При необходимости я готов поделиться полным кодом.

Подробнее здесь: https://stackoverflow.com/questions/791 ... -limits-ho
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»