BinanceAPIException: APIError(code=-1003):


I am getting the following error:
BinanceAPIException: APIError(code=-1003): Too much request weight used; current limit is 1200 request weight per 1 MINUTE. Please use the websocket for live updates to avoid polling the API.

Even though I managed to run a code for what I wanted, as below, I am quite unexperienced with python and binance api.
I understand its possible I need to change for the websocket? But i dont manage to find how to do this?


from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager
client = Client(user_key, secret_key)

# select what to pair the coins to and pull all coins paied with PAIR_WITH
# Define the size of each trade, by default in USDT
# List of pairs to exlcude
# by default we’re excluding the most popular fiat pairs
# and some margin keywords, as we’re only working on the SPOT account
# the amount of time in MINUTES to calculate the differnce from the current price
# the difference in % between the first and second checks for the price, by default set at 10 minutes apart.
# define in % when to sell a coin that’s not making a profit
# define in % when to take profit on a profitable coin

# coins that bought by the bot since its start
coins_bought = {}
# path to the saved coins_bought file
coins_bought_file_path = "coins_bought.json"

# if saved coins_bought json file exists then load it
if os.path.isfile(coins_bought_file_path):
 with open(coins_bought_file_path) as file:
  coins_bought = json.load(file)

def get_price():
 #Return the current price for all coins on binance
  initial_price = {}
  prices = client.get_all_tickers()
  for coin in prices:
# only Return USDT pairs and exlcude margin symbols like BTCDOWNUSDT
    if PAIR_WITH in coin["symbol"] and all(item not in coin["symbol"] for item in FIATS):
      initial_price[coin["symbol"]] = { "price": coin["price"], "time":}
  return initial_price

def get_price24hrs():
 #Return the current price for all coins on binance
  lowest_price = {}
  prices1 = client.get_ticker()
  for coin in prices1:
# only Return USDT pairs and exlcude margin symbols like BTCDOWNUSDT
    if PAIR_WITH in coin["symbol"] and all(item not in coin["symbol"] for item in FIATS):
      lowest_price[coin["symbol"]] = {"lowPrice": coin["lowPrice"], "time": - timedelta(minutes=1)}
  return lowest_price

from math import pi
def check_below():
  initial_price = get_price()
  lowest_price = get_price24hrs()
  volatile_coins = {}
  # calculate the difference between the first and last price reads
  for coin in initial_price:
    if float(initial_price[coin]["price"])<=float(lowest_price[coin]["lowPrice"]):
      volatile_coins[coin] = initial_price[coin]["price"]
  return volatile_coins, len(volatile_coins), initial_price

def convert_volume():
 #Converts the volume given in QUANTITY from USDT to the each coin’s volume’’’
  volatile_coins, number_of_coins, initial_price = check_below()
  lot_size = {}
  volume = {}
  for coin in volatile_coins:
# Find the correct step size for each coin
 # max accuracy for BTC for example is 6 decimal points
 # while XRP is only 1
      info = client.get_symbol_info(coin)
      step_size = info["filters"][2]["stepSize"]
      lot_size[coin] = step_size.index("1") - 1
      if lot_size[coin] < 0:
        lot_size[coin] = 0

# calculate the volume in coin from QUANTITY in USDT (default)
    volume[coin] = float(QUANTITY) / float(initial_price[coin]["price"])
# define the volume with the correct step size
    if coin not in lot_size:
      volume[coin] = float("{:.1f}".format(volume[coin]))
      volume[coin] = float("{:.{}f}".format(volume[coin], lot_size[coin]))
  return volume, initial_price

def trade():
 #Place Buy market orders for each volatile coin found’’’
  volume, last_price = convert_volume()
  orders = {}
  for coin in volume:
# only buy if the there are no active trades on the coin
    if coin not in coins_bought or coins_bought[coin] == None:
      print(f" preparing to buy {volume[coin]} {coin}")
      orders[coin] = client.get_all_orders(symbol=coin, limit=1)
      # try to create a real order if the test orders did not raise an exception
        buy_limit = client.create_order(
# error handling here in case position cannot be placed
      except Exception as e:

      print(f"Signal detected, but there is already an active trade on {coin}")
  return orders, last_price, volume

def update_porfolio(orders, last_price, volume):
 #add every coin bought to our portfolio for tracking/selling later’’’
  for coin in orders:
    coins_bought[coin] = {
  "symbol": orders[coin][0]["symbol"],
  "orderid": orders[coin][0]["orderId"],
  "timestamp": orders[coin][0]["time"],
  "bought_at": last_price[coin]["price"],
  "volume": volume[coin]
# save the coins in a json file in the same directory
    with open(coins_bought_file_path, "w") as file:
      json.dump(coins_bought, file, indent=4)

def sell_coins():
 #sell coins that have reached the STOP LOSS or TAKE PROFIT thershold’’’
  last_price = get_price()
  for coin in coins_bought:
 # define stop loss and take profit
    TP = float(coins_bought[coin]["bought_at"]) + (float(coins_bought[coin]["bought_at"]) * TAKE_PROFIT) / 100
    SL = float(coins_bought[coin]["bought_at"]) - (float(coins_bought[coin]["bought_at"]) * STOP_LOSS) / 100
# check that the price is above the take profit or below the stop loss
    if float(last_price[coin]["price"]) > TP or float(last_price[coin]["price"]) < SL:
      print("TP or SL reached selling", {coins_bought[coin]["volume"]}, {coin})
      coins_bought[coin] = None
    with open(coins_bought_file_path, "w") as file:
      json.dump(coins_bought, file, indent=4)
    print("TP or SL not yet reached, not selling, {coin}, for now...")

if __name__ == "__main__":
 print("Press Ctrl-Q to stop the script")
for i in count():
  orders, last_price, volume = trade()
  update_porfolio(orders, last_price, volume)

Please direct this question to the owner of the third-party library.

I dont understand :frowning:

The library you are using is maintained by a third-party.

If you have any questions regarding the library, please open a Github Issue on the repository.

1 Like

thanks, my friend. I understand now