diff --git a/binance/client.py b/binance/client.py index e9f5a542a..bf5e25877 100755 --- a/binance/client.py +++ b/binance/client.py @@ -1,3 +1,4 @@ +import sys from typing import Dict, Optional, List, Tuple import aiohttp @@ -9,7 +10,6 @@ from operator import itemgetter from urllib.parse import urlencode - from .helpers import interval_to_milliseconds, convert_ts_str from .exceptions import BinanceAPIException, BinanceRequestException, NotImplementedException from .enums import HistoricalKlinesType @@ -312,6 +312,22 @@ def _request(self, method, uri: str, signed: bool, force_params: bool = False, * kwargs = self._get_request_kwargs(method, signed, force_params, **kwargs) self.response = getattr(self.session, method)(uri, **kwargs) + + status_code = self.response.status_code + used_weight = int(self.response.headers.get('x-mbx-used-weight', 0)) + + if used_weight > 1150: + sys.stdout.write( + f'Request weight might exceed limit: {used_weight} out of 1200. Waiting for 1 min...\n' + ) + time.sleep(61) # blocking + + if status_code in (418, 429): + sys.stdout.write( + f'[{status_code}] Binance is overloaded or IP is banned. Waiting for 30 min...\n' + ) + time.sleep(60 * 30 + 1) # blocking + return self._handle_response(self.response) @staticmethod @@ -6507,6 +6523,20 @@ async def _handle_response(self, response: aiohttp.ClientResponse): Raises the appropriate exceptions when necessary; otherwise, returns the response. """ + used_weight = int(response.headers.get('x-mbx-used-weight', 0)) + + if used_weight > 1150: + sys.stdout.write( + f'Request weight might exceed limit: {used_weight} out of 1200. Waiting for 1 min...\n' + ) + time.sleep(61) # blocking + + if response.status in (418, 429): + sys.stdout.write( + f'[{response.status}] Binance is overloaded or IP is banned. Waiting for 30 min...\n' + ) + time.sleep(60 * 30 + 1) # blocking + if not str(response.status).startswith('2'): raise BinanceAPIException(response, response.status, await response.text()) try: