From 3c0fec08015eae475a177ab1813454e769adcd81 Mon Sep 17 00:00:00 2001 From: carlosmiei <43336371+carlosmiei@users.noreply.github.com> Date: Tue, 29 Oct 2024 15:29:23 +0000 Subject: [PATCH] reformat --- binance/client.py | 4434 ++++++++++++++++--------- binance/depthcache.py | 136 +- binance/enums.py | 126 +- binance/exceptions.py | 25 +- binance/helpers.py | 4 +- binance/streams.py | 721 ++-- binance/threaded_stream.py | 29 +- examples/binace_socket_manager.py | 3 +- examples/create_order.py | 15 +- examples/create_order_async.py | 8 +- tests/conftest.py | 14 +- tests/test_api_request.py | 11 +- tests/test_client.py | 6 +- tests/test_cryptography.py | 21 +- tests/test_futures.py | 79 +- tests/test_get_order_book.py | 34 +- tests/test_historical_klines.py | 5 +- tests/test_ids.py | 230 +- tests/test_ping.py | 27 +- tests/test_socket_manager.py | 7 +- tests/test_streams.py | 4 +- tests/test_threaded_socket_manager.py | 12 +- 22 files changed, 3706 insertions(+), 2245 deletions(-) diff --git a/binance/client.py b/binance/client.py index ba06b33b..df90c7f8 100755 --- a/binance/client.py +++ b/binance/client.py @@ -16,112 +16,114 @@ from urllib.parse import urlencode from .helpers import interval_to_milliseconds, convert_ts_str, get_loop -from .exceptions import BinanceAPIException, BinanceRequestException, NotImplementedException +from .exceptions import ( + BinanceAPIException, + BinanceRequestException, + NotImplementedException, +) from .enums import HistoricalKlinesType class BaseClient: - - API_URL = 'https://api{}.binance.{}/api' - API_TESTNET_URL = 'https://testnet.binance.vision/api' - MARGIN_API_URL = 'https://api{}.binance.{}/sapi' - WEBSITE_URL = 'https://www.binance.{}' - FUTURES_URL = 'https://fapi.binance.{}/fapi' - FUTURES_TESTNET_URL = 'https://testnet.binancefuture.com/fapi' - FUTURES_DATA_URL = 'https://fapi.binance.{}/futures/data' - FUTURES_DATA_TESTNET_URL = 'https://testnet.binancefuture.com/futures/data' + API_URL = "https://api{}.binance.{}/api" + API_TESTNET_URL = "https://testnet.binance.vision/api" + MARGIN_API_URL = "https://api{}.binance.{}/sapi" + WEBSITE_URL = "https://www.binance.{}" + FUTURES_URL = "https://fapi.binance.{}/fapi" + FUTURES_TESTNET_URL = "https://testnet.binancefuture.com/fapi" + FUTURES_DATA_URL = "https://fapi.binance.{}/futures/data" + FUTURES_DATA_TESTNET_URL = "https://testnet.binancefuture.com/futures/data" FUTURES_COIN_URL = "https://dapi.binance.{}/dapi" - FUTURES_COIN_TESTNET_URL = 'https://testnet.binancefuture.com/dapi' + FUTURES_COIN_TESTNET_URL = "https://testnet.binancefuture.com/dapi" FUTURES_COIN_DATA_URL = "https://dapi.binance.{}/futures/data" - FUTURES_COIN_DATA_TESTNET_URL = 'https://testnet.binancefuture.com/futures/data' - OPTIONS_URL = 'https://eapi.binance.{}/eapi' - OPTIONS_TESTNET_URL = 'https://testnet.binanceops.{}/eapi' - PAPI_URL = 'https://papi.binance.{}/papi' - PUBLIC_API_VERSION = 'v1' - PRIVATE_API_VERSION = 'v3' - MARGIN_API_VERSION = 'v1' - MARGIN_API_VERSION2 = 'v2' - MARGIN_API_VERSION3 = 'v3' - MARGIN_API_VERSION4 = 'v4' - FUTURES_API_VERSION = 'v1' - FUTURES_API_VERSION2 = 'v2' - FUTURES_API_VERSION3 = 'v3' - OPTIONS_API_VERSION = 'v1' - PORTFOLIO_API_VERSION = 'v1' - PORTFOLIO_API_VERSION2 = 'v2' - - - BASE_ENDPOINT_DEFAULT = '' - BASE_ENDPOINT_1 = '1' - BASE_ENDPOINT_2 = '2' - BASE_ENDPOINT_3 = '3' - BASE_ENDPOINT_4 = '4' + FUTURES_COIN_DATA_TESTNET_URL = "https://testnet.binancefuture.com/futures/data" + OPTIONS_URL = "https://eapi.binance.{}/eapi" + OPTIONS_TESTNET_URL = "https://testnet.binanceops.{}/eapi" + PAPI_URL = "https://papi.binance.{}/papi" + PUBLIC_API_VERSION = "v1" + PRIVATE_API_VERSION = "v3" + MARGIN_API_VERSION = "v1" + MARGIN_API_VERSION2 = "v2" + MARGIN_API_VERSION3 = "v3" + MARGIN_API_VERSION4 = "v4" + FUTURES_API_VERSION = "v1" + FUTURES_API_VERSION2 = "v2" + FUTURES_API_VERSION3 = "v3" + OPTIONS_API_VERSION = "v1" + PORTFOLIO_API_VERSION = "v1" + PORTFOLIO_API_VERSION2 = "v2" + + BASE_ENDPOINT_DEFAULT = "" + BASE_ENDPOINT_1 = "1" + BASE_ENDPOINT_2 = "2" + BASE_ENDPOINT_3 = "3" + BASE_ENDPOINT_4 = "4" REQUEST_TIMEOUT: float = 10 - SYMBOL_TYPE_SPOT = 'SPOT' - - ORDER_STATUS_NEW = 'NEW' - ORDER_STATUS_PARTIALLY_FILLED = 'PARTIALLY_FILLED' - ORDER_STATUS_FILLED = 'FILLED' - ORDER_STATUS_CANCELED = 'CANCELED' - ORDER_STATUS_PENDING_CANCEL = 'PENDING_CANCEL' - ORDER_STATUS_REJECTED = 'REJECTED' - ORDER_STATUS_EXPIRED = 'EXPIRED' - - KLINE_INTERVAL_1SECOND = '1s' - KLINE_INTERVAL_1MINUTE = '1m' - KLINE_INTERVAL_3MINUTE = '3m' - KLINE_INTERVAL_5MINUTE = '5m' - KLINE_INTERVAL_15MINUTE = '15m' - KLINE_INTERVAL_30MINUTE = '30m' - KLINE_INTERVAL_1HOUR = '1h' - KLINE_INTERVAL_2HOUR = '2h' - KLINE_INTERVAL_4HOUR = '4h' - KLINE_INTERVAL_6HOUR = '6h' - KLINE_INTERVAL_8HOUR = '8h' - KLINE_INTERVAL_12HOUR = '12h' - KLINE_INTERVAL_1DAY = '1d' - KLINE_INTERVAL_3DAY = '3d' - KLINE_INTERVAL_1WEEK = '1w' - KLINE_INTERVAL_1MONTH = '1M' - - SIDE_BUY = 'BUY' - SIDE_SELL = 'SELL' - - ORDER_TYPE_LIMIT = 'LIMIT' - ORDER_TYPE_MARKET = 'MARKET' - ORDER_TYPE_STOP_LOSS = 'STOP_LOSS' - ORDER_TYPE_STOP_LOSS_LIMIT = 'STOP_LOSS_LIMIT' - ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT' - ORDER_TYPE_TAKE_PROFIT_LIMIT = 'TAKE_PROFIT_LIMIT' - ORDER_TYPE_LIMIT_MAKER = 'LIMIT_MAKER' - - FUTURE_ORDER_TYPE_LIMIT = 'LIMIT' - FUTURE_ORDER_TYPE_MARKET = 'MARKET' - FUTURE_ORDER_TYPE_STOP = 'STOP' - FUTURE_ORDER_TYPE_STOP_MARKET = 'STOP_MARKET' - FUTURE_ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT' - FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET = 'TAKE_PROFIT_MARKET' - FUTURE_ORDER_TYPE_LIMIT_MAKER = 'LIMIT_MAKER' - - TIME_IN_FORCE_GTC = 'GTC' # Good till cancelled - TIME_IN_FORCE_IOC = 'IOC' # Immediate or cancel - TIME_IN_FORCE_FOK = 'FOK' # Fill or kill - - ORDER_RESP_TYPE_ACK = 'ACK' - ORDER_RESP_TYPE_RESULT = 'RESULT' - ORDER_RESP_TYPE_FULL = 'FULL' + SYMBOL_TYPE_SPOT = "SPOT" + + ORDER_STATUS_NEW = "NEW" + ORDER_STATUS_PARTIALLY_FILLED = "PARTIALLY_FILLED" + ORDER_STATUS_FILLED = "FILLED" + ORDER_STATUS_CANCELED = "CANCELED" + ORDER_STATUS_PENDING_CANCEL = "PENDING_CANCEL" + ORDER_STATUS_REJECTED = "REJECTED" + ORDER_STATUS_EXPIRED = "EXPIRED" + + KLINE_INTERVAL_1SECOND = "1s" + KLINE_INTERVAL_1MINUTE = "1m" + KLINE_INTERVAL_3MINUTE = "3m" + KLINE_INTERVAL_5MINUTE = "5m" + KLINE_INTERVAL_15MINUTE = "15m" + KLINE_INTERVAL_30MINUTE = "30m" + KLINE_INTERVAL_1HOUR = "1h" + KLINE_INTERVAL_2HOUR = "2h" + KLINE_INTERVAL_4HOUR = "4h" + KLINE_INTERVAL_6HOUR = "6h" + KLINE_INTERVAL_8HOUR = "8h" + KLINE_INTERVAL_12HOUR = "12h" + KLINE_INTERVAL_1DAY = "1d" + KLINE_INTERVAL_3DAY = "3d" + KLINE_INTERVAL_1WEEK = "1w" + KLINE_INTERVAL_1MONTH = "1M" + + SIDE_BUY = "BUY" + SIDE_SELL = "SELL" + + ORDER_TYPE_LIMIT = "LIMIT" + ORDER_TYPE_MARKET = "MARKET" + ORDER_TYPE_STOP_LOSS = "STOP_LOSS" + ORDER_TYPE_STOP_LOSS_LIMIT = "STOP_LOSS_LIMIT" + ORDER_TYPE_TAKE_PROFIT = "TAKE_PROFIT" + ORDER_TYPE_TAKE_PROFIT_LIMIT = "TAKE_PROFIT_LIMIT" + ORDER_TYPE_LIMIT_MAKER = "LIMIT_MAKER" + + FUTURE_ORDER_TYPE_LIMIT = "LIMIT" + FUTURE_ORDER_TYPE_MARKET = "MARKET" + FUTURE_ORDER_TYPE_STOP = "STOP" + FUTURE_ORDER_TYPE_STOP_MARKET = "STOP_MARKET" + FUTURE_ORDER_TYPE_TAKE_PROFIT = "TAKE_PROFIT" + FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET = "TAKE_PROFIT_MARKET" + FUTURE_ORDER_TYPE_LIMIT_MAKER = "LIMIT_MAKER" + + TIME_IN_FORCE_GTC = "GTC" # Good till cancelled + TIME_IN_FORCE_IOC = "IOC" # Immediate or cancel + TIME_IN_FORCE_FOK = "FOK" # Fill or kill + + ORDER_RESP_TYPE_ACK = "ACK" + ORDER_RESP_TYPE_RESULT = "RESULT" + ORDER_RESP_TYPE_FULL = "FULL" # For accessing the data returned by Client.aggregate_trades(). - AGG_ID = 'a' - AGG_PRICE = 'p' - AGG_QUANTITY = 'q' - AGG_FIRST_TRADE_ID = 'f' - AGG_LAST_TRADE_ID = 'l' - AGG_TIME = 'T' - AGG_BUYER_MAKES = 'm' - AGG_BEST_MATCH = 'M' + AGG_ID = "a" + AGG_PRICE = "p" + AGG_QUANTITY = "q" + AGG_FIRST_TRADE_ID = "f" + AGG_LAST_TRADE_ID = "l" + AGG_TIME = "T" + AGG_BUYER_MAKES = "m" + AGG_BEST_MATCH = "M" # new asset transfer api enum SPOT_TO_FIAT = "MAIN_C2C" @@ -147,9 +149,15 @@ class BaseClient: CONTRACT_ORDER_PREFIX = "x-Cb7ytekJ" def __init__( - self, api_key: Optional[str] = None, api_secret: Optional[str] = None, - requests_params: Optional[Dict[str, Any]] = None, tld: str = 'com', base_endpoint: str = BASE_ENDPOINT_DEFAULT, - testnet: bool = False, private_key: Optional[Union[str, Path]] = None, private_key_pass: Optional[str] = None + self, + api_key: Optional[str] = None, + api_secret: Optional[str] = None, + requests_params: Optional[Dict[str, Any]] = None, + tld: str = "com", + base_endpoint: str = BASE_ENDPOINT_DEFAULT, + testnet: bool = False, + private_key: Optional[Union[str, Path]] = None, + private_key_pass: Optional[str] = None, ): """Binance API Client constructor @@ -191,18 +199,22 @@ def __init__( def _get_headers(self) -> Dict: headers = { - 'Accept': 'application/json', - 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', # noqa + "Accept": "application/json", + "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36", # noqa } if self.API_KEY: assert self.API_KEY - headers['X-MBX-APIKEY'] = self.API_KEY + headers["X-MBX-APIKEY"] = self.API_KEY return headers def _init_session(self): raise NotImplementedError - def _init_private_key(self, private_key: Optional[Union[str, Path]], private_key_pass: Optional[str] = None): + def _init_private_key( + self, + private_key: Optional[Union[str, Path]], + private_key_pass: Optional[str] = None, + ): if not private_key: return if isinstance(private_key, Path): @@ -213,12 +225,14 @@ def _init_private_key(self, private_key: Optional[Union[str, Path]], private_key return RSA.import_key(private_key, passphrase=private_key_pass) return ECC.import_key(private_key) - def _create_api_uri(self, path: str, signed: bool = True, version: str = PUBLIC_API_VERSION) -> str: + def _create_api_uri( + self, path: str, signed: bool = True, version: str = PUBLIC_API_VERSION + ) -> str: url = self.API_URL if self.testnet: url = self.API_TESTNET_URL v = self.PRIVATE_API_VERSION if signed else version - return url + '/' + v + '/' + path + return url + "/" + v + "/" + path def _create_margin_api_uri(self, path: str, version: int = 1) -> str: options = { @@ -227,36 +241,41 @@ def _create_margin_api_uri(self, path: str, version: int = 1) -> str: 3: self.MARGIN_API_VERSION3, 4: self.MARGIN_API_VERSION4, } - return self.MARGIN_API_URL + '/' + options[version] + '/' + path + return self.MARGIN_API_URL + "/" + options[version] + "/" + path def _create_papi_api_uri(self, path: str, version: int = 1) -> str: - options = { - 1: self.PORTFOLIO_API_VERSION, - 2: self.PORTFOLIO_API_VERSION2 - } - return self.PAPI_URL.format(self.tld) + '/' + options[version] + '/' + path + options = {1: self.PORTFOLIO_API_VERSION, 2: self.PORTFOLIO_API_VERSION2} + return self.PAPI_URL.format(self.tld) + "/" + options[version] + "/" + path def _create_website_uri(self, path: str) -> str: - return self.WEBSITE_URL + '/' + path + return self.WEBSITE_URL + "/" + path def _create_futures_api_uri(self, path: str, version: int = 1) -> str: url = self.FUTURES_URL if self.testnet: url = self.FUTURES_TESTNET_URL - options = {1: self.FUTURES_API_VERSION, 2: self.FUTURES_API_VERSION2, 3: self.FUTURES_API_VERSION3} - return url + '/' + options[version] + '/' + path + options = { + 1: self.FUTURES_API_VERSION, + 2: self.FUTURES_API_VERSION2, + 3: self.FUTURES_API_VERSION3, + } + return url + "/" + options[version] + "/" + path def _create_futures_data_api_uri(self, path: str) -> str: url = self.FUTURES_DATA_URL if self.testnet: url = self.FUTURES_DATA_TESTNET_URL - return url + '/' + path + return url + "/" + path def _create_futures_coin_api_url(self, path: str, version: int = 1) -> str: url = self.FUTURES_COIN_URL if self.testnet: url = self.FUTURES_COIN_TESTNET_URL - options = {1: self.FUTURES_API_VERSION, 2: self.FUTURES_API_VERSION2, 3: self.FUTURES_API_VERSION3} + options = { + 1: self.FUTURES_API_VERSION, + 2: self.FUTURES_API_VERSION2, + 3: self.FUTURES_API_VERSION3, + } return url + "/" + options[version] + "/" + path def _create_futures_coin_data_api_url(self, path: str, version: int = 1) -> str: @@ -269,21 +288,27 @@ def _create_options_api_uri(self, path: str) -> str: url = self.OPTIONS_URL if self.testnet: url = self.OPTIONS_TESTNET_URL - return url + '/' + self.OPTIONS_API_VERSION + '/' + path + return url + "/" + self.OPTIONS_API_VERSION + "/" + path def _rsa_signature(self, query_string: str): assert self.PRIVATE_KEY h = SHA256.new(query_string.encode("utf-8")) - signature = pkcs1_15.new(self.PRIVATE_KEY).sign(h) # type: ignore + signature = pkcs1_15.new(self.PRIVATE_KEY).sign(h) # type: ignore return b64encode(signature).decode() def _ed25519_signature(self, query_string: str): assert self.PRIVATE_KEY - return b64encode(eddsa.new(self.PRIVATE_KEY, "rfc8032").sign(query_string.encode())).decode() # type: ignore + return b64encode( + eddsa.new(self.PRIVATE_KEY, "rfc8032").sign(query_string.encode()) + ).decode() # type: ignore def _hmac_signature(self, query_string: str) -> str: assert self.API_SECRET, "API Secret required for private endpoints" - m = hmac.new(self.API_SECRET.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256) + m = hmac.new( + self.API_SECRET.encode("utf-8"), + query_string.encode("utf-8"), + hashlib.sha256, + ) return m.hexdigest() def _generate_signature(self, data: Dict) -> str: @@ -293,20 +318,20 @@ def _generate_signature(self, data: Dict) -> str: sig_func = self._rsa_signature else: sig_func = self._ed25519_signature - query_string = '&'.join([f"{d[0]}={d[1]}" for d in self._order_params(data)]) + query_string = "&".join([f"{d[0]}={d[1]}" for d in self._order_params(data)]) return sig_func(query_string) @staticmethod def _get_version(version: int, **kwargs) -> int: - if 'data' in kwargs and 'version' in kwargs['data']: - version_override = kwargs['data'].get('version') - del kwargs['data']['version'] + if "data" in kwargs and "version" in kwargs["data"]: + version_override = kwargs["data"].get("version") + del kwargs["data"]["version"] return version_override return version @staticmethod def uuid22(length=22): - return format(random.getrandbits(length * 4), 'x') + return format(random.getrandbits(length * 4), "x") @staticmethod def _order_params(data: Dict) -> List[Tuple[str, str]]: @@ -320,87 +345,106 @@ def _order_params(data: Dict) -> List[Tuple[str, str]]: has_signature = False params = [] for key, value in data.items(): - if key == 'signature': + if key == "signature": has_signature = True else: params.append((key, str(value))) # sort parameters by key params.sort(key=itemgetter(0)) if has_signature: - params.append(('signature', data['signature'])) + params.append(("signature", data["signature"])) return params - def _get_request_kwargs(self, method, signed: bool, force_params: bool = False, **kwargs) -> Dict: - + def _get_request_kwargs( + self, method, signed: bool, force_params: bool = False, **kwargs + ) -> Dict: # set default requests timeout - kwargs['timeout'] = self.REQUEST_TIMEOUT + kwargs["timeout"] = self.REQUEST_TIMEOUT # add our global requests params if self._requests_params: kwargs.update(self._requests_params) - data = kwargs.get('data', None) + data = kwargs.get("data", None) if data and isinstance(data, dict): - kwargs['data'] = data + kwargs["data"] = data # find any requests params passed and apply them - if 'requests_params' in kwargs['data']: + if "requests_params" in kwargs["data"]: # merge requests params into kwargs - kwargs.update(kwargs['data']['requests_params']) - del kwargs['data']['requests_params'] + kwargs.update(kwargs["data"]["requests_params"]) + del kwargs["data"]["requests_params"] if signed: # generate signature - kwargs['data']['timestamp'] = int(time.time() * 1000 + self.timestamp_offset) - kwargs['data']['signature'] = self._generate_signature(kwargs['data']) + kwargs["data"]["timestamp"] = int( + time.time() * 1000 + self.timestamp_offset + ) + kwargs["data"]["signature"] = self._generate_signature(kwargs["data"]) # sort get and post params to match signature order if data: # sort post params and remove any arguments with values of None - kwargs['data'] = self._order_params(kwargs['data']) + kwargs["data"] = self._order_params(kwargs["data"]) # Remove any arguments with values of None. - null_args = [i for i, (key, value) in enumerate(kwargs['data']) if value is None] + null_args = [ + i for i, (key, value) in enumerate(kwargs["data"]) if value is None + ] for i in reversed(null_args): - del kwargs['data'][i] + del kwargs["data"][i] # if get request assign data array to params value for requests lib - if data and (method == 'get' or force_params): - kwargs['params'] = '&'.join('%s=%s' % (data[0], data[1]) for data in kwargs['data']) - del kwargs['data'] + if data and (method == "get" or force_params): + kwargs["params"] = "&".join( + "%s=%s" % (data[0], data[1]) for data in kwargs["data"] + ) + del kwargs["data"] # Temporary fix for Signature issue while using batchOrders in AsyncClient - if 'params' in kwargs.keys() and 'batchOrders' in kwargs['params']: - kwargs['data'] = kwargs['params'] - del kwargs['params'] + if "params" in kwargs.keys() and "batchOrders" in kwargs["params"]: + kwargs["data"] = kwargs["params"] + del kwargs["params"] return kwargs class Client(BaseClient): - def __init__( - self, api_key: Optional[str] = None, api_secret: Optional[str] = None, - requests_params: Optional[Dict[str, Any]] = None, tld: str = 'com', - base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT, testnet: bool = False, - private_key: Optional[Union[str, Path]] = None, private_key_pass: Optional[str] = None, - ping: Optional[bool] = True + self, + api_key: Optional[str] = None, + api_secret: Optional[str] = None, + requests_params: Optional[Dict[str, Any]] = None, + tld: str = "com", + base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT, + testnet: bool = False, + private_key: Optional[Union[str, Path]] = None, + private_key_pass: Optional[str] = None, + ping: Optional[bool] = True, ): - - super().__init__(api_key, api_secret, requests_params, tld, base_endpoint, testnet, private_key, private_key_pass) + super().__init__( + api_key, + api_secret, + requests_params, + tld, + base_endpoint, + testnet, + private_key, + private_key_pass, + ) # init DNS and SSL cert if ping: self.ping() def _init_session(self) -> requests.Session: - headers = self._get_headers() session = requests.session() session.headers.update(headers) return session - def _request(self, method, uri: str, signed: bool, force_params: bool = False, **kwargs): - + def _request( + self, method, uri: str, signed: bool, force_params: bool = False, **kwargs + ): kwargs = self._get_request_kwargs(method, signed, force_params, **kwargs) self.response = getattr(self.session, method)(uri, **kwargs) @@ -417,15 +461,22 @@ def _handle_response(response: requests.Response): try: return response.json() except ValueError: - raise BinanceRequestException('Invalid Response: %s' % response.text) + raise BinanceRequestException("Invalid Response: %s" % response.text) def _request_api( - self, method, path: str, signed: bool = False, version=BaseClient.PUBLIC_API_VERSION, **kwargs + self, + method, + path: str, + signed: bool = False, + version=BaseClient.PUBLIC_API_VERSION, + **kwargs, ): uri = self._create_api_uri(path, signed, version) return self._request(method, uri, signed, **kwargs) - def _request_futures_api(self, method, path, signed=False, version: int = 1, **kwargs) -> Dict: + def _request_futures_api( + self, method, path, signed=False, version: int = 1, **kwargs + ) -> Dict: version = self._get_version(version, **kwargs) uri = self._create_futures_api_uri(path, version) @@ -436,13 +487,17 @@ def _request_futures_data_api(self, method, path, signed=False, **kwargs) -> Dic return self._request(method, uri, signed, True, **kwargs) - def _request_futures_coin_api(self, method, path, signed=False, version=1, **kwargs) -> Dict: + def _request_futures_coin_api( + self, method, path, signed=False, version=1, **kwargs + ) -> Dict: version = self._get_version(version, **kwargs) uri = self._create_futures_coin_api_url(path, version=version) return self._request(method, uri, signed, False, **kwargs) - def _request_futures_coin_data_api(self, method, path, signed=False, version=1, **kwargs) -> Dict: + def _request_futures_coin_data_api( + self, method, path, signed=False, version=1, **kwargs + ) -> Dict: version = self._get_version(version, **kwargs) uri = self._create_futures_coin_data_api_url(path, version=version) @@ -453,13 +508,17 @@ def _request_options_api(self, method, path, signed=False, **kwargs) -> Dict: return self._request(method, uri, signed, True, **kwargs) - def _request_margin_api(self, method, path, signed=False, version=1, **kwargs) -> Dict: + def _request_margin_api( + self, method, path, signed=False, version=1, **kwargs + ) -> Dict: version = self._get_version(version, **kwargs) uri = self._create_margin_api_uri(path, version) return self._request(method, uri, signed, **kwargs) - def _request_papi_api(self, method, path, signed=False, version=1, **kwargs) -> Dict: + def _request_papi_api( + self, method, path, signed=False, version=1, **kwargs + ) -> Dict: version = self._get_version(version, **kwargs) uri = self._create_papi_api_uri(path, version) return self._request(method, uri, signed, **kwargs) @@ -469,16 +528,22 @@ def _request_website(self, method, path, signed=False, **kwargs) -> Dict: return self._request(method, uri, signed, **kwargs) def _get(self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs): - return self._request_api('get', path, signed, version, **kwargs) + return self._request_api("get", path, signed, version, **kwargs) - def _post(self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs) -> Dict: - return self._request_api('post', path, signed, version, **kwargs) + def _post( + self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs + ) -> Dict: + return self._request_api("post", path, signed, version, **kwargs) - def _put(self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs) -> Dict: - return self._request_api('put', path, signed, version, **kwargs) + def _put( + self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs + ) -> Dict: + return self._request_api("put", path, signed, version, **kwargs) - def _delete(self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs) -> Dict: - return self._request_api('delete', path, signed, version, **kwargs) + def _delete( + self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs + ) -> Dict: + return self._request_api("delete", path, signed, version, **kwargs) # Exchange Endpoints @@ -492,7 +557,10 @@ def get_products(self) -> Dict: :raises: BinanceRequestException, BinanceAPIException """ - products = self._request_website('get', 'bapi/asset/v2/public/asset-service/product/get-products?includeEtf=true') + products = self._request_website( + "get", + "bapi/asset/v2/public/asset-service/product/get-products?includeEtf=true", + ) return products def get_exchange_info(self) -> Dict: @@ -557,7 +625,7 @@ def get_exchange_info(self) -> Dict: """ - return self._get('exchangeInfo', version=self.PRIVATE_API_VERSION) + return self._get("exchangeInfo", version=self.PRIVATE_API_VERSION) def get_symbol_info(self, symbol) -> Optional[Dict]: """Return information about a symbol @@ -602,8 +670,8 @@ def get_symbol_info(self, symbol) -> Optional[Dict]: res = self.get_exchange_info() - for item in res['symbols']: - if item['symbol'] == symbol.upper(): + for item in res["symbols"]: + if item["symbol"] == symbol.upper(): return item return None @@ -624,7 +692,7 @@ def ping(self) -> Dict: :raises: BinanceRequestException, BinanceAPIException """ - return self._get('ping', version=self.PRIVATE_API_VERSION) + return self._get("ping", version=self.PRIVATE_API_VERSION) def get_server_time(self) -> Dict: """Test connectivity to the Rest API and get the current server time. @@ -642,7 +710,7 @@ def get_server_time(self) -> Dict: :raises: BinanceRequestException, BinanceAPIException """ - return self._get('time', version=self.PRIVATE_API_VERSION) + return self._get("time", version=self.PRIVATE_API_VERSION) # Market Data Endpoints @@ -669,7 +737,7 @@ def get_all_tickers(self) -> List[Dict[str, str]]: :raises: BinanceRequestException, BinanceAPIException """ - return self._get('ticker/price', version=self.PRIVATE_API_VERSION) + return self._get("ticker/price", version=self.PRIVATE_API_VERSION) def get_orderbook_tickers(self, **params) -> Dict: """Best price/qty on the order book for all symbols. @@ -710,7 +778,9 @@ def get_orderbook_tickers(self, **params) -> Dict: data["symbol"] = params["symbol"] elif "symbols" in params: data["symbols"] = params["symbols"] - return self._get('ticker/bookTicker', data=data, version=self.PRIVATE_API_VERSION) + return self._get( + "ticker/bookTicker", data=data, version=self.PRIVATE_API_VERSION + ) def get_order_book(self, **params) -> Dict: """Get the Order Book for the market @@ -747,7 +817,7 @@ def get_order_book(self, **params) -> Dict: :raises: BinanceRequestException, BinanceAPIException """ - return self._get('depth', data=params, version=self.PRIVATE_API_VERSION) + return self._get("depth", data=params, version=self.PRIVATE_API_VERSION) def get_recent_trades(self, **params) -> Dict: """Get recent trades (up to last 500). @@ -777,7 +847,7 @@ def get_recent_trades(self, **params) -> Dict: :raises: BinanceRequestException, BinanceAPIException """ - return self._get('trades', data=params) + return self._get("trades", data=params) def get_historical_trades(self, **params) -> Dict: """Get older trades. @@ -809,7 +879,9 @@ def get_historical_trades(self, **params) -> Dict: :raises: BinanceRequestException, BinanceAPIException """ - return self._get('historicalTrades', data=params, version=self.PRIVATE_API_VERSION) + return self._get( + "historicalTrades", data=params, version=self.PRIVATE_API_VERSION + ) def get_aggregate_trades(self, **params) -> Dict: """Get compressed, aggregate trades. Trades that fill at the time, @@ -848,7 +920,7 @@ def get_aggregate_trades(self, **params) -> Dict: :raises: BinanceRequestException, BinanceAPIException """ - return self._get('aggTrades', data=params, version=self.PRIVATE_API_VERSION) + return self._get("aggTrades", data=params, version=self.PRIVATE_API_VERSION) def aggregate_trade_iter(self, symbol: str, start_str=None, last_id=None): """Iterate over aggregate trade data from (start_time or last_id) to @@ -883,7 +955,8 @@ def aggregate_trade_iter(self, symbol: str, start_str=None, last_id=None): """ if start_str is not None and last_id is not None: raise ValueError( - 'start_time and last_id may not be simultaneously specified.') + "start_time and last_id may not be simultaneously specified." + ) # If there's no last_id, get one. if last_id is None: @@ -902,9 +975,8 @@ def aggregate_trade_iter(self, symbol: str, start_str=None, last_id=None): while True: end_ts = start_ts + (60 * 60 * 1000) trades = self.get_aggregate_trades( - symbol=symbol, - startTime=start_ts, - endTime=end_ts) + symbol=symbol, startTime=start_ts, endTime=end_ts + ) if len(trades) > 0: break # If we reach present moment and find no trades then there is @@ -973,9 +1045,11 @@ def get_klines(self, **params) -> Dict: :raises: BinanceRequestException, BinanceAPIException """ - return self._get('klines', data=params, version=self.PRIVATE_API_VERSION) + return self._get("klines", data=params, version=self.PRIVATE_API_VERSION) - def _klines(self, klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, **params) -> Dict: + def _klines( + self, klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, **params + ) -> Dict: """Get klines of spot (get_klines) or futures (futures_klines) endpoints. :param klines_type: Historical klines type: SPOT or FUTURES @@ -984,8 +1058,8 @@ def _klines(self, klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, :return: klines, see get_klines """ - if 'endTime' in params and not params['endTime']: - del params['endTime'] + if "endTime" in params and not params["endTime"]: + del params["endTime"] if HistoricalKlinesType.SPOT == klines_type: return self.get_klines(**params) @@ -996,7 +1070,12 @@ def _klines(self, klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, else: raise NotImplementedException(klines_type) - def _get_earliest_valid_timestamp(self, symbol, interval, klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT): + def _get_earliest_valid_timestamp( + self, + symbol, + interval, + klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, + ): """Get the earliest valid open timestamp from Binance :param symbol: Name of symbol pair e.g. BNBBTC @@ -1015,12 +1094,19 @@ def _get_earliest_valid_timestamp(self, symbol, interval, klines_type: Historica interval=interval, limit=1, startTime=0, - endTime=int(time.time() * 1000) + endTime=int(time.time() * 1000), ) return kline[0][0] - def get_historical_klines(self, symbol, interval, start_str=None, end_str=None, limit=None, - klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT): + def get_historical_klines( + self, + symbol, + interval, + start_str=None, + end_str=None, + limit=None, + klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, + ): """Get Historical Klines from Binance :param symbol: Name of symbol pair e.g. BNBBTC @@ -1040,11 +1126,23 @@ def get_historical_klines(self, symbol, interval, start_str=None, end_str=None, """ return self._historical_klines( - symbol, interval, start_str=start_str, end_str=end_str, limit=limit, klines_type=klines_type + symbol, + interval, + start_str=start_str, + end_str=end_str, + limit=limit, + klines_type=klines_type, ) - def _historical_klines(self, symbol, interval, start_str=None, end_str=None, limit=None, - klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT): + def _historical_klines( + self, + symbol, + interval, + start_str=None, + end_str=None, + limit=None, + klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, + ): """Get Historical Klines from Binance (spot or futures) See dateparser docs for valid start and end string formats https://dateparser.readthedocs.io/en/latest/ @@ -1084,7 +1182,9 @@ def _historical_klines(self, symbol, interval, start_str=None, end_str=None, lim # establish first available start timestamp if start_ts is not None: - first_valid_ts = self._get_earliest_valid_timestamp(symbol, interval, klines_type) + first_valid_ts = self._get_earliest_valid_timestamp( + symbol, interval, klines_type + ) start_ts = max(start_ts, first_valid_ts) # if an end time was passed convert it @@ -1101,7 +1201,7 @@ def _historical_klines(self, symbol, interval, start_str=None, end_str=None, lim interval=interval, limit=limit, startTime=start_ts, - endTime=end_ts + endTime=end_ts, ) # append this loops data to our output data @@ -1133,8 +1233,15 @@ def _historical_klines(self, symbol, interval, start_str=None, end_str=None, lim return output_data - def get_historical_klines_generator(self, symbol, interval, start_str=None, end_str=None, limit=None, - klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT): + def get_historical_klines_generator( + self, + symbol, + interval, + start_str=None, + end_str=None, + limit=None, + klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, + ): """Get Historical Klines generator from Binance :param symbol: Name of symbol pair e.g. BNBBTC @@ -1154,10 +1261,19 @@ def get_historical_klines_generator(self, symbol, interval, start_str=None, end_ """ - return self._historical_klines_generator(symbol, interval, start_str, end_str, limit, klines_type=klines_type) + return self._historical_klines_generator( + symbol, interval, start_str, end_str, limit, klines_type=klines_type + ) - def _historical_klines_generator(self, symbol, interval, start_str=None, end_str=None, limit=None, - klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT): + def _historical_klines_generator( + self, + symbol, + interval, + start_str=None, + end_str=None, + limit=None, + klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, + ): """Get Historical Klines generator from Binance (spot or futures) See dateparser docs for valid start and end string formats https://dateparser.readthedocs.io/en/latest/ @@ -1192,7 +1308,9 @@ def _historical_klines_generator(self, symbol, interval, start_str=None, end_str # establish first available start timestamp if start_ts is not None: - first_valid_ts = self._get_earliest_valid_timestamp(symbol, interval, klines_type) + first_valid_ts = self._get_earliest_valid_timestamp( + symbol, interval, klines_type + ) start_ts = max(start_ts, first_valid_ts) # if an end time was passed convert it @@ -1209,7 +1327,7 @@ def _historical_klines_generator(self, symbol, interval, start_str=None, end_str interval=interval, limit=limit, startTime=start_ts, - endTime=end_ts + endTime=end_ts, ) # yield data @@ -1253,7 +1371,7 @@ def get_avg_price(self, **params): "price": "9.35751834" } """ - return self._get('avgPrice', data=params, version=self.PRIVATE_API_VERSION) + return self._get("avgPrice", data=params, version=self.PRIVATE_API_VERSION) def get_ticker(self, **params): """24 hour price change statistics. @@ -1314,7 +1432,7 @@ def get_ticker(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('ticker/24hr', data=params, version=self.PRIVATE_API_VERSION) + return self._get("ticker/24hr", data=params, version=self.PRIVATE_API_VERSION) def get_symbol_ticker(self, **params): """Latest price for a symbol or symbols. @@ -1351,8 +1469,7 @@ def get_symbol_ticker(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('ticker/price', data=params, version=self.PRIVATE_API_VERSION) - + return self._get("ticker/price", data=params, version=self.PRIVATE_API_VERSION) def get_symbol_ticker_window(self, **params): """Latest price for a symbol or symbols. @@ -1389,8 +1506,7 @@ def get_symbol_ticker_window(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('ticker', data=params, version=self.PRIVATE_API_VERSION) - + return self._get("ticker", data=params, version=self.PRIVATE_API_VERSION) def get_orderbook_ticker(self, **params): """Latest price for a symbol or symbols. @@ -1436,7 +1552,9 @@ def get_orderbook_ticker(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('ticker/bookTicker', data=params, version=self.PRIVATE_API_VERSION) + return self._get( + "ticker/bookTicker", data=params, version=self.PRIVATE_API_VERSION + ) # Account Endpoints @@ -1557,10 +1675,9 @@ def create_order(self, **params): :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.SPOT_ORDER_PREFIX + self.uuid22() - return self._post('order', True, data=params) - + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.SPOT_ORDER_PREFIX + self.uuid22() + return self._post("order", True, data=params) def order_limit(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params): """Send in a new limit order @@ -1593,10 +1710,7 @@ def order_limit(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params): :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException """ - params.update({ - 'type': self.ORDER_TYPE_LIMIT, - 'timeInForce': timeInForce - }) + params.update({"type": self.ORDER_TYPE_LIMIT, "timeInForce": timeInForce}) return self.create_order(**params) def order_limit_buy(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params): @@ -1630,9 +1744,11 @@ def order_limit_buy(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params): :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException """ - params.update({ - 'side': self.SIDE_BUY, - }) + params.update( + { + "side": self.SIDE_BUY, + } + ) return self.order_limit(timeInForce=timeInForce, **params) def order_limit_sell(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params): @@ -1664,9 +1780,7 @@ def order_limit_sell(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params): :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException """ - params.update({ - 'side': self.SIDE_SELL - }) + params.update({"side": self.SIDE_SELL}) return self.order_limit(timeInForce=timeInForce, **params) def order_market(self, **params): @@ -1695,9 +1809,7 @@ def order_market(self, **params): :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException """ - params.update({ - 'type': self.ORDER_TYPE_MARKET - }) + params.update({"type": self.ORDER_TYPE_MARKET}) return self.create_order(**params) def order_market_buy(self, **params): @@ -1723,9 +1835,7 @@ def order_market_buy(self, **params): :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException """ - params.update({ - 'side': self.SIDE_BUY - }) + params.update({"side": self.SIDE_BUY}) return self.order_market(**params) def order_market_sell(self, **params): @@ -1751,9 +1861,7 @@ def order_market_sell(self, **params): :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException """ - params.update({ - 'side': self.SIDE_SELL - }) + params.update({"side": self.SIDE_SELL}) return self.order_market(**params) def create_oco_order(self, **params): @@ -1816,7 +1924,7 @@ def create_oco_order(self, **params): :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException """ - return self._post('order/oco', True, data=params) + return self._post("order/oco", True, data=params) def order_oco_buy(self, **params): """Send in a new OCO buy order @@ -1855,9 +1963,7 @@ def order_oco_buy(self, **params): :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException """ - params.update({ - 'side': self.SIDE_BUY - }) + params.update({"side": self.SIDE_BUY}) return self.create_oco_order(**params) def order_oco_sell(self, **params): @@ -1897,9 +2003,7 @@ def order_oco_sell(self, **params): :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException """ - params.update({ - 'side': self.SIDE_SELL - }) + params.update({"side": self.SIDE_SELL}) return self.create_oco_order(**params) def create_test_order(self, **params): @@ -1938,7 +2042,7 @@ def create_test_order(self, **params): """ - return self._post('order/test', True, data=params) + return self._post("order/test", True, data=params) def get_order(self, **params): """Check an order's status. Either orderId or origClientOrderId must be sent. @@ -1977,7 +2081,7 @@ def get_order(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('order', True, data=params) + return self._get("order", True, data=params) def get_all_orders(self, **params): """Get all account orders; active, canceled, or filled. @@ -2022,7 +2126,7 @@ def get_all_orders(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('allOrders', True, data=params) + return self._get("allOrders", True, data=params) def cancel_order(self, **params): """Cancel an active order. Either orderId or origClientOrderId must be sent. @@ -2054,7 +2158,7 @@ def cancel_order(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._delete('order', True, data=params) + return self._delete("order", True, data=params) def get_open_orders(self, **params): """Get all open orders on a symbol. @@ -2091,7 +2195,7 @@ def get_open_orders(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('openOrders', True, data=params) + return self._get("openOrders", True, data=params) def get_open_oco_orders(self, **params): """Get all open orders on a symbol. @@ -2125,7 +2229,7 @@ def get_open_oco_orders(self, **params): ] :raises: BinanceRequestException, BinanceAPIException """ - return self._get('openOrderList', True, data=params) + return self._get("openOrderList", True, data=params) # User Stream Endpoints def get_account(self, **params): @@ -2165,7 +2269,7 @@ def get_account(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('account', True, data=params) + return self._get("account", True, data=params) def get_asset_balance(self, asset, **params): """Get current asset balance. @@ -2191,8 +2295,8 @@ def get_asset_balance(self, asset, **params): res = self.get_account(**params) # find asset balance in list of balances if "balances" in res: - for bal in res['balances']: - if bal['asset'].lower() == asset.lower(): + for bal in res["balances"]: + if bal["asset"].lower() == asset.lower(): return bal return None @@ -2235,7 +2339,7 @@ def get_my_trades(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('myTrades', True, data=params) + return self._get("myTrades", True, data=params) def get_current_order_count(self): """Displays the user's current order count usage for all intervals. @@ -2264,7 +2368,7 @@ def get_current_order_count(self): ] """ - return self._get('rateLimit/order', True) + return self._get("rateLimit/order", True) def get_prevented_matches(self, **params): """Displays the list of orders that were expired because of STP. @@ -2301,7 +2405,7 @@ def get_prevented_matches(self, **params): } ] """ - return self._get('myPreventedMatches', True, data=params) + return self._get("myPreventedMatches", True, data=params) def get_allocations(self, **params): """Retrieves allocations resulting from SOR order placement. @@ -2345,7 +2449,7 @@ def get_allocations(self, **params): } ] """ - return self._get('myAllocations', True, data=params) + return self._get("myAllocations", True, data=params) def get_system_status(self): """Get system status detail. @@ -2364,7 +2468,7 @@ def get_system_status(self): :raises: BinanceAPIException """ - return self._request_margin_api('get', 'system/status') + return self._request_margin_api("get", "system/status") def get_account_status(self, version=1, **params): """Get account status detail. @@ -2384,11 +2488,11 @@ def get_account_status(self, version=1, **params): } """ - if self.tld == 'us': - path = 'accountStatus' + if self.tld == "us": + path = "accountStatus" else: - path = 'account/status' - return self._request_margin_api('get', path, True, version, data=params) + path = "account/status" + return self._request_margin_api("get", path, True, version, data=params) def get_account_api_trading_status(self, **params): """Fetch account api trading status detail. @@ -2458,7 +2562,9 @@ def get_account_api_trading_status(self, **params): } """ - return self._request_margin_api('get', 'account/apiTradingStatus', True, data=params) + return self._request_margin_api( + "get", "account/apiTradingStatus", True, data=params + ) def get_account_api_permissions(self, **params): """Fetch api key permissions. @@ -2487,7 +2593,9 @@ def get_account_api_permissions(self, **params): } """ - return self._request_margin_api('get', 'account/apiRestrictions', True, data=params) + return self._request_margin_api( + "get", "account/apiRestrictions", True, data=params + ) def get_dust_assets(self, **params): """Get assets that can be converted into BNB @@ -2516,7 +2624,7 @@ def get_dust_assets(self, **params): } """ - return self._request_margin_api('post', 'asset/dust-btc', True, data=params) + return self._request_margin_api("post", "asset/dust-btc", True, data=params) def get_dust_log(self, **params): """Get log of small amounts exchanged for BNB. @@ -2588,7 +2696,7 @@ def get_dust_log(self, **params): } """ - return self._request_margin_api('get', 'asset/dribblet', True, data=params) + return self._request_margin_api("get", "asset/dribblet", True, data=params) def transfer_dust(self, **params): """Convert dust assets to BNB. @@ -2626,7 +2734,7 @@ def transfer_dust(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'asset/dust', True, data=params) + return self._request_margin_api("post", "asset/dust", True, data=params) def get_asset_dividend_history(self, **params): """Query asset dividend record. @@ -2673,7 +2781,7 @@ def get_asset_dividend_history(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'asset/assetDividend', True, data=params) + return self._request_margin_api("get", "asset/assetDividend", True, data=params) def make_universal_transfer(self, **params): """User Universal Transfer @@ -2705,7 +2813,9 @@ def make_universal_transfer(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'asset/transfer', signed=True, data=params) + return self._request_margin_api( + "post", "asset/transfer", signed=True, data=params + ) def query_universal_transfer_history(self, **params): """Query User Universal Transfer History @@ -2759,7 +2869,9 @@ def query_universal_transfer_history(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'asset/transfer', signed=True, data=params) + return self._request_margin_api( + "get", "asset/transfer", signed=True, data=params + ) def get_trade_fee(self, **params): """Get trade fee. @@ -2789,12 +2901,12 @@ def get_trade_fee(self, **params): ] """ - if self.tld == 'us': - endpoint = 'asset/query/trading-fee' + if self.tld == "us": + endpoint = "asset/query/trading-fee" else: - endpoint = 'asset/tradeFee' + endpoint = "asset/tradeFee" - return self._request_margin_api('get', endpoint, True, data=params) + return self._request_margin_api("get", endpoint, True, data=params) def get_asset_details(self, **params): """Fetch details on assets. @@ -2827,12 +2939,12 @@ def get_asset_details(self, **params): } """ - return self._request_margin_api('get', 'asset/assetDetail', True, data=params) + return self._request_margin_api("get", "asset/assetDetail", True, data=params) def get_spot_delist_schedule(self, **params): """Get symbols delist schedule for spot - https://binance-docs.github.io/apidocs/spot/en/#get-symbols-delist-schedule-for-spot-market_data + https://binance-docs.github.io/apidocs/spot/en/#get-symbols-delist-schedule-for-spot-market_data :param recvWindow: optional - the number of milliseconds the request is valid for :type recvWindow: int @@ -2856,7 +2968,9 @@ def get_spot_delist_schedule(self, **params): } ] """ - return self._request_margin_api('get', '/spot/delist-schedule', True, data=params) + return self._request_margin_api( + "get", "/spot/delist-schedule", True, data=params + ) # Withdraw Endpoints @@ -2899,7 +3013,9 @@ def withdraw(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'capital/withdraw/apply', True, data=params) + return self._request_margin_api( + "post", "capital/withdraw/apply", True, data=params + ) def get_deposit_history(self, **params): """Fetch deposit history. @@ -2955,7 +3071,9 @@ def get_deposit_history(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'capital/deposit/hisrec', True, data=params) + return self._request_margin_api( + "get", "capital/deposit/hisrec", True, data=params + ) def get_withdraw_history(self, **params): """Fetch withdraw history. @@ -3009,7 +3127,9 @@ def get_withdraw_history(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'capital/withdraw/history', True, data=params) + return self._request_margin_api( + "get", "capital/withdraw/history", True, data=params + ) def get_withdraw_history_id(self, withdraw_id, **params): """Fetch withdraw history. @@ -3051,7 +3171,7 @@ def get_withdraw_history_id(self, withdraw_id, **params): result = self.get_withdraw_history(**params) for entry in result: - if 'id' in entry and entry['id'] == withdraw_id: + if "id" in entry and entry["id"] == withdraw_id: return entry raise Exception("There is no entry with withdraw id", result) @@ -3082,10 +3202,12 @@ def get_deposit_address(self, coin: str, network: Optional[str] = None, **params :raises: BinanceRequestException, BinanceAPIException """ - params['coin'] = coin + params["coin"] = coin if network: - params['network'] = network - return self._request_margin_api('get', 'capital/deposit/address', True, data=params) + params["network"] = network + return self._request_margin_api( + "get", "capital/deposit/address", True, data=params + ) # User Stream Endpoints @@ -3109,8 +3231,10 @@ def stream_get_listen_key(self): :raises: BinanceRequestException, BinanceAPIException """ - res = self._post('userDataStream', False, data={}, version=self.PRIVATE_API_VERSION) - return res['listenKey'] + res = self._post( + "userDataStream", False, data={}, version=self.PRIVATE_API_VERSION + ) + return res["listenKey"] def stream_keepalive(self, listenKey): """PING a user data stream to prevent a time out. @@ -3129,10 +3253,10 @@ def stream_keepalive(self, listenKey): :raises: BinanceRequestException, BinanceAPIException """ - params = { - 'listenKey': listenKey - } - return self._put('userDataStream', False, data=params, version=self.PRIVATE_API_VERSION) + params = {"listenKey": listenKey} + return self._put( + "userDataStream", False, data=params, version=self.PRIVATE_API_VERSION + ) def stream_close(self, listenKey): """Close out a user data stream. @@ -3151,10 +3275,10 @@ def stream_close(self, listenKey): :raises: BinanceRequestException, BinanceAPIException """ - params = { - 'listenKey': listenKey - } - return self._delete('userDataStream', False, data=params, version=self.PRIVATE_API_VERSION) + params = {"listenKey": listenKey} + return self._delete( + "userDataStream", False, data=params, version=self.PRIVATE_API_VERSION + ) # Margin Trading Endpoints @@ -3214,7 +3338,7 @@ def get_margin_account(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/account', True, data=params) + return self._request_margin_api("get", "margin/account", True, data=params) def get_isolated_margin_account(self, **params): """Query isolated margin account details @@ -3325,7 +3449,9 @@ def get_isolated_margin_account(self, **params): } """ - return self._request_margin_api('get', 'margin/isolated/account', True, data=params) + return self._request_margin_api( + "get", "margin/isolated/account", True, data=params + ) def enable_isolated_margin_account(self, **params): """Enable isolated margin account for a specific symbol. @@ -3346,7 +3472,9 @@ def enable_isolated_margin_account(self, **params): """ - return self._request_margin_api('post', 'margin/isolated/account', True, data=params) + return self._request_margin_api( + "post", "margin/isolated/account", True, data=params + ) def disable_isolated_margin_account(self, **params): """Disable isolated margin account for a specific symbol. Each trading pair can only @@ -3367,7 +3495,9 @@ def disable_isolated_margin_account(self, **params): } """ - return self._request_margin_api('delete', 'margin/isolated/account', True, data=params) + return self._request_margin_api( + "delete", "margin/isolated/account", True, data=params + ) def get_enabled_isolated_margin_account_limit(self, **params): """Query enabled isolated margin account limit. @@ -3383,7 +3513,9 @@ def get_enabled_isolated_margin_account_limit(self, **params): } """ - return self._request_margin_api('get', 'margin/isolated/accountLimit', True, data=params) + return self._request_margin_api( + "get", "margin/isolated/accountLimit", True, data=params + ) def get_margin_dustlog(self, **params): """ @@ -3454,7 +3586,7 @@ def get_margin_dustlog(self, **params): } """ - return self._request_margin_api('get', 'margin/dribblet', True, data=params) + return self._request_margin_api("get", "margin/dribblet", True, data=params) def get_margin_dust_assets(self, **params): """Get margin assets that can be converted into BNB. @@ -3482,7 +3614,7 @@ def get_margin_dust_assets(self, **params): } """ - return self._request_margin_api('get', 'margin/dust', True, data=params) + return self._request_margin_api("get", "margin/dust", True, data=params) def transfer_margin_dust(self, **params): """Convert dust assets to BNB. @@ -3516,7 +3648,7 @@ def transfer_margin_dust(self, **params): } """ - return self._request_margin_api('post', 'margin/dust', True, data=params) + return self._request_margin_api("post", "margin/dust", True, data=params) def get_cross_margin_collateral_ratio(self, **params): """ @@ -3565,7 +3697,9 @@ def get_cross_margin_collateral_ratio(self, **params): } ] """ - return self._request_margin_api('get', 'margin/crossMarginCollateralRatio', True, data=params) + return self._request_margin_api( + "get", "margin/crossMarginCollateralRatio", True, data=params + ) def get_small_liability_exchange_assets(self, **params): """Query the coins which can be small liability exchange @@ -3586,7 +3720,9 @@ def get_small_liability_exchange_assets(self, **params): ] """ - return self._request_margin_api('get', 'margin/exchange-small-liability', True, data=params) + return self._request_margin_api( + "get", "margin/exchange-small-liability", True, data=params + ) def exchange_small_liability_assets(self, **params): """Cross Margin Small Liability Exchange @@ -3602,7 +3738,9 @@ def exchange_small_liability_assets(self, **params): none """ - return self._request_margin_api('post', 'margin/exchange-small-liability', True, data=params) + return self._request_margin_api( + "post", "margin/exchange-small-liability", True, data=params + ) def get_small_liability_exchange_history(self, **params): """Get Small liability Exchange History @@ -3636,7 +3774,9 @@ def get_small_liability_exchange_history(self, **params): } """ - return self._request_margin_api('get', 'margin/exchange-small-liability-history', True, data=params) + return self._request_margin_api( + "get", "margin/exchange-small-liability-history", True, data=params + ) def get_future_hourly_interest_rate(self, **params): """Get user the next hourly estimate interest @@ -3663,7 +3803,9 @@ def get_future_hourly_interest_rate(self, **params): ] """ - return self._request_margin_api('get', 'margin/next-hourly-interest-rate', True, data=params) + return self._request_margin_api( + "get", "margin/next-hourly-interest-rate", True, data=params + ) def get_margin_capital_flow(self, **params): """Get cross or isolated margin capital flow @@ -3710,7 +3852,7 @@ def get_margin_capital_flow(self, **params): ] """ - return self._request_margin_api('get', 'margin/capital-flow', True, data=params) + return self._request_margin_api("get", "margin/capital-flow", True, data=params) def get_margin_asset(self, **params): """Query cross-margin asset @@ -3740,7 +3882,7 @@ def get_margin_asset(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/asset', data=params) + return self._request_margin_api("get", "margin/asset", data=params) def get_margin_symbol(self, **params): """Query cross-margin symbol info @@ -3772,7 +3914,7 @@ def get_margin_symbol(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/pair', data=params) + return self._request_margin_api("get", "margin/pair", data=params) def get_margin_all_assets(self, **params): """Get All Margin Assets (MARKET_DATA) @@ -3809,7 +3951,7 @@ def get_margin_all_assets(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/allAssets', data=params) + return self._request_margin_api("get", "margin/allAssets", data=params) def get_margin_all_pairs(self, **params): """Get All Cross Margin Pairs (MARKET_DATA) @@ -3848,7 +3990,7 @@ def get_margin_all_pairs(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/allPairs', data=params) + return self._request_margin_api("get", "margin/allPairs", data=params) def create_isolated_margin_account(self, **params): """Create isolated margin account for symbol @@ -3877,7 +4019,9 @@ def create_isolated_margin_account(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'margin/isolated/create', signed=True, data=params) + return self._request_margin_api( + "post", "margin/isolated/create", signed=True, data=params + ) def get_isolated_margin_symbol(self, **params): """Query isolated margin symbol info @@ -3908,7 +4052,9 @@ def get_isolated_margin_symbol(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/isolated/pair', signed=True, data=params) + return self._request_margin_api( + "get", "margin/isolated/pair", signed=True, data=params + ) def get_all_isolated_margin_symbols(self, **params): """Query isolated margin symbol info for all pairs @@ -3946,7 +4092,9 @@ def get_all_isolated_margin_symbols(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/isolated/allPairs', signed=True, data=params) + return self._request_margin_api( + "get", "margin/isolated/allPairs", signed=True, data=params + ) def get_isolated_margin_fee_data(self, **params): """Get isolated margin fee data collection with any vip level or user's current specific data as https://www.binance.com/en/margin-fee @@ -3981,7 +4129,9 @@ def get_isolated_margin_fee_data(self, **params): } ] """ - return self._request_margin_api('get', 'margin/isolatedMarginData', True, data=params) + return self._request_margin_api( + "get", "margin/isolatedMarginData", True, data=params + ) def get_isolated_margin_tier_data(self, **params): """Get isolated margin tier data collection with any tier as https://www.binance.com/en/margin-data @@ -4011,7 +4161,9 @@ def get_isolated_margin_tier_data(self, **params): ] """ - return self._request_margin_api('get', 'margin/isolatedMarginTier', True, data=params) + return self._request_margin_api( + "get", "margin/isolatedMarginTier", True, data=params + ) def margin_manual_liquidation(self, **params): """ @@ -4036,7 +4188,9 @@ def margin_manual_liquidation(self, **params): ] """ - return self._request_margin_api('post', 'margin/manual-liquidation', True, data=params) + return self._request_margin_api( + "post", "margin/manual-liquidation", True, data=params + ) def toggle_bnb_burn_spot_margin(self, **params): """Toggle BNB Burn On Spot Trade And Margin Interest @@ -4065,7 +4219,7 @@ def toggle_bnb_burn_spot_margin(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'bnbBurn', signed=True, data=params) + return self._request_margin_api("post", "bnbBurn", signed=True, data=params) def get_bnb_burn_spot_margin(self, **params): """Get BNB Burn Status @@ -4089,7 +4243,7 @@ def get_bnb_burn_spot_margin(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'bnbBurn', signed=True, data=params) + return self._request_margin_api("get", "bnbBurn", signed=True, data=params) def get_margin_price_index(self, **params): """Query margin priceIndex @@ -4116,7 +4270,7 @@ def get_margin_price_index(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/priceIndex', data=params) + return self._request_margin_api("get", "margin/priceIndex", data=params) def transfer_margin_to_spot(self, **params): """Execute transfer between cross-margin account and spot account. @@ -4145,8 +4299,10 @@ def transfer_margin_to_spot(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - params['type'] = 2 - return self._request_margin_api('post', 'margin/transfer', signed=True, data=params) + params["type"] = 2 + return self._request_margin_api( + "post", "margin/transfer", signed=True, data=params + ) def transfer_spot_to_margin(self, **params): """Execute transfer between spot account and cross-margin account. @@ -4175,8 +4331,10 @@ def transfer_spot_to_margin(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - params['type'] = 1 - return self._request_margin_api('post', 'margin/transfer', signed=True, data=params) + params["type"] = 1 + return self._request_margin_api( + "post", "margin/transfer", signed=True, data=params + ) def transfer_isolated_margin_to_spot(self, **params): """Execute transfer between isolated margin account and spot account. @@ -4208,9 +4366,11 @@ def transfer_isolated_margin_to_spot(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - params['transFrom'] = "ISOLATED_MARGIN" - params['transTo'] = "SPOT" - return self._request_margin_api('post', 'margin/isolated/transfer', signed=True, data=params) + params["transFrom"] = "ISOLATED_MARGIN" + params["transTo"] = "SPOT" + return self._request_margin_api( + "post", "margin/isolated/transfer", signed=True, data=params + ) def transfer_spot_to_isolated_margin(self, **params): """Execute transfer between spot account and isolated margin account. @@ -4242,9 +4402,11 @@ def transfer_spot_to_isolated_margin(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - params['transFrom'] = "SPOT" - params['transTo'] = "ISOLATED_MARGIN" - return self._request_margin_api('post', 'margin/isolated/transfer', signed=True, data=params) + params["transFrom"] = "SPOT" + params["transTo"] = "ISOLATED_MARGIN" + return self._request_margin_api( + "post", "margin/isolated/transfer", signed=True, data=params + ) def get_isolated_margin_tranfer_history(self, **params): """Get transfers to isolated margin account. @@ -4305,7 +4467,9 @@ def get_isolated_margin_tranfer_history(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/isolated/transfer', signed=True, data=params) + return self._request_margin_api( + "get", "margin/isolated/transfer", signed=True, data=params + ) def create_margin_loan(self, **params): """Apply for a loan in cross-margin or isolated-margin account. @@ -4341,7 +4505,7 @@ def create_margin_loan(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'margin/loan', signed=True, data=params) + return self._request_margin_api("post", "margin/loan", signed=True, data=params) def repay_margin_loan(self, **params): """Repay loan in cross-margin or isolated-margin account. @@ -4379,7 +4543,9 @@ def repay_margin_loan(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'margin/repay', signed=True, data=params) + return self._request_margin_api( + "post", "margin/repay", signed=True, data=params + ) def create_margin_order(self, **params): """Post a new order for margin account. @@ -4500,9 +4666,11 @@ def create_margin_order(self, **params): BinanceOrderInactiveSymbolException """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.SPOT_ORDER_PREFIX + self.uuid22() - return self._request_margin_api('post', 'margin/order', signed=True, data=params) + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.SPOT_ORDER_PREFIX + self.uuid22() + return self._request_margin_api( + "post", "margin/order", signed=True, data=params + ) def cancel_margin_order(self, **params): """Cancel an active order for margin account. @@ -4545,7 +4713,9 @@ def cancel_margin_order(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('delete', 'margin/order', signed=True, data=params) + return self._request_margin_api( + "delete", "margin/order", signed=True, data=params + ) def set_margin_max_leverage(self, **params): """Adjust cross margin max leverage @@ -4564,7 +4734,9 @@ def set_margin_max_leverage(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'margin/max-leverage', signed=True, data=params) + return self._request_margin_api( + "post", "margin/max-leverage", signed=True, data=params + ) def get_margin_transfer_history(self, **params): """Query margin transfer history @@ -4623,7 +4795,9 @@ def get_margin_transfer_history(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/transfer', signed=True, data=params) + return self._request_margin_api( + "get", "margin/transfer", signed=True, data=params + ) def get_margin_loan_details(self, **params): """Query loan record @@ -4667,7 +4841,7 @@ def get_margin_loan_details(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/loan', signed=True, data=params) + return self._request_margin_api("get", "margin/loan", signed=True, data=params) def get_margin_repay_details(self, **params): """Query repay record @@ -4717,7 +4891,7 @@ def get_margin_repay_details(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/repay', signed=True, data=params) + return self._request_margin_api("get", "margin/repay", signed=True, data=params) def get_cross_margin_data(self, **params): """Query Cross Margin Fee Data (USER_DATA) @@ -4748,7 +4922,9 @@ def get_cross_margin_data(self, **params): } ] """ - return self._request_margin_api('get', 'margin/crossMarginData', signed=True, data=params) + return self._request_margin_api( + "get", "margin/crossMarginData", signed=True, data=params + ) def get_margin_interest_history(self, **params): """Get Interest History (USER_DATA) @@ -4791,7 +4967,9 @@ def get_margin_interest_history(self, **params): """ - return self._request_margin_api('get', 'margin/interestHistory', signed=True, data=params) + return self._request_margin_api( + "get", "margin/interestHistory", signed=True, data=params + ) def get_margin_force_liquidation_rec(self, **params): """Get Force Liquidation Record (USER_DATA) @@ -4832,7 +5010,9 @@ def get_margin_force_liquidation_rec(self, **params): } """ - return self._request_margin_api('get', 'margin/forceLiquidationRec', signed=True, data=params) + return self._request_margin_api( + "get", "margin/forceLiquidationRec", signed=True, data=params + ) def get_margin_order(self, **params): """Query margin accounts order @@ -4878,7 +5058,7 @@ def get_margin_order(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/order', signed=True, data=params) + return self._request_margin_api("get", "margin/order", signed=True, data=params) def get_open_margin_orders(self, **params): """Query margin accounts open orders @@ -4925,7 +5105,9 @@ def get_open_margin_orders(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/openOrders', signed=True, data=params) + return self._request_margin_api( + "get", "margin/openOrders", signed=True, data=params + ) def get_all_margin_orders(self, **params): """Query all margin accounts orders @@ -4984,7 +5166,9 @@ def get_all_margin_orders(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/allOrders', signed=True, data=params) + return self._request_margin_api( + "get", "margin/allOrders", signed=True, data=params + ) def get_margin_trades(self, **params): """Query margin accounts trades @@ -5042,7 +5226,9 @@ def get_margin_trades(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/myTrades', signed=True, data=params) + return self._request_margin_api( + "get", "margin/myTrades", signed=True, data=params + ) def get_max_margin_loan(self, **params): """Query max borrow amount for an asset @@ -5065,7 +5251,9 @@ def get_max_margin_loan(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/maxBorrowable', signed=True, data=params) + return self._request_margin_api( + "get", "margin/maxBorrowable", signed=True, data=params + ) def get_max_margin_transfer(self, **params): """Query max transfer-out amount @@ -5088,7 +5276,9 @@ def get_max_margin_transfer(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'margin/maxTransferable', signed=True, data=params) + return self._request_margin_api( + "get", "margin/maxTransferable", signed=True, data=params + ) def get_margin_delist_schedule(self, **params): """Get tokens or symbols delist schedule for cross margin and isolated margin @@ -5122,7 +5312,9 @@ def get_margin_delist_schedule(self, **params): } ] """ - return self._request_margin_api('get', '/margin/delist-schedule', signed=True, data=params) + return self._request_margin_api( + "get", "/margin/delist-schedule", signed=True, data=params + ) # Margin OCO @@ -5232,7 +5424,9 @@ def create_margin_oco_order(self, **params): BinanceOrderInactiveSymbolException """ - return self._request_margin_api('post', 'margin/order/oco', signed=True, data=params) + return self._request_margin_api( + "post", "margin/order/oco", signed=True, data=params + ) def cancel_margin_oco_order(self, **params): """Cancel an entire Order List for a margin account. @@ -5312,8 +5506,10 @@ def cancel_margin_oco_order(self, **params): ] } - """ - return self._request_margin_api('delete', 'margin/orderList', signed=True, data=params) + """ + return self._request_margin_api( + "delete", "margin/orderList", signed=True, data=params + ) def get_margin_oco_order(self, **params): """Retrieves a specific OCO based on provided optional parameters @@ -5356,8 +5552,10 @@ def get_margin_oco_order(self, **params): ] } - """ - return self._request_margin_api('get', 'margin/orderList', signed=True, data=params) + """ + return self._request_margin_api( + "get", "margin/orderList", signed=True, data=params + ) def get_open_margin_oco_orders(self, **params): """Retrieves open OCO trades @@ -5427,8 +5625,10 @@ def get_open_margin_oco_orders(self, **params): } ] - """ - return self._request_margin_api('get', 'margin/openOrderList', signed=True, data=params) + """ + return self._request_margin_api( + "get", "margin/openOrderList", signed=True, data=params + ) # Cross-margin @@ -5452,8 +5652,8 @@ def margin_stream_get_listen_key(self): :raises: BinanceRequestException, BinanceAPIException """ - res = self._request_margin_api('post', 'userDataStream', signed=False, data={}) - return res['listenKey'] + res = self._request_margin_api("post", "userDataStream", signed=False, data={}) + return res["listenKey"] def margin_stream_keepalive(self, listenKey): """PING a cross-margin data stream to prevent a time out. @@ -5472,10 +5672,10 @@ def margin_stream_keepalive(self, listenKey): :raises: BinanceRequestException, BinanceAPIException """ - params = { - 'listenKey': listenKey - } - return self._request_margin_api('put', 'userDataStream', signed=False, data=params) + params = {"listenKey": listenKey} + return self._request_margin_api( + "put", "userDataStream", signed=False, data=params + ) def margin_stream_close(self, listenKey): """Close out a cross-margin data stream. @@ -5494,10 +5694,10 @@ def margin_stream_close(self, listenKey): :raises: BinanceRequestException, BinanceAPIException """ - params = { - 'listenKey': listenKey - } - return self._request_margin_api('delete', 'userDataStream', signed=False, data=params) + params = {"listenKey": listenKey} + return self._request_margin_api( + "delete", "userDataStream", signed=False, data=params + ) # Isolated margin @@ -5524,11 +5724,11 @@ def isolated_margin_stream_get_listen_key(self, symbol): :raises: BinanceRequestException, BinanceAPIException """ - params = { - 'symbol': symbol - } - res = self._request_margin_api('post', 'userDataStream/isolated', signed=False, data=params) - return res['listenKey'] + params = {"symbol": symbol} + res = self._request_margin_api( + "post", "userDataStream/isolated", signed=False, data=params + ) + return res["listenKey"] def isolated_margin_stream_keepalive(self, symbol, listenKey): """PING an isolated margin data stream to prevent a time out. @@ -5549,11 +5749,10 @@ def isolated_margin_stream_keepalive(self, symbol, listenKey): :raises: BinanceRequestException, BinanceAPIException """ - params = { - 'symbol': symbol, - 'listenKey': listenKey - } - return self._request_margin_api('put', 'userDataStream/isolated', signed=False, data=params) + params = {"symbol": symbol, "listenKey": listenKey} + return self._request_margin_api( + "put", "userDataStream/isolated", signed=False, data=params + ) def isolated_margin_stream_close(self, symbol, listenKey): """Close out an isolated margin data stream. @@ -5574,333 +5773,350 @@ def isolated_margin_stream_close(self, symbol, listenKey): :raises: BinanceRequestException, BinanceAPIException """ - params = { - 'symbol': symbol, - 'listenKey': listenKey - } - return self._request_margin_api('delete', 'userDataStream/isolated', signed=False, data=params) + params = {"symbol": symbol, "listenKey": listenKey} + return self._request_margin_api( + "delete", "userDataStream/isolated", signed=False, data=params + ) # Simple Earn Endpoints def get_simple_earn_flexible_product_list(self, **params): """Get available Simple Earn flexible product list - https://binance-docs.github.io/apidocs/spot/en/#get-simple-earn-flexible-product-list-user_data + https://binance-docs.github.io/apidocs/spot/en/#get-simple-earn-flexible-product-list-user_data - :param asset: optional - :type asset: str - :param current: optional - Currently querying page. Start from 1. Default:1 - :type current: int - :param size: optional - Default:10, Max:100 - :type size: int - :param recvWindow: the number of milliseconds the request is valid for - :type recvWindow: int + :param asset: optional + :type asset: str + :param current: optional - Currently querying page. Start from 1. Default:1 + :type current: int + :param size: optional - Default:10, Max:100 + :type size: int + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int - :returns: API response + :returns: API response - .. code-block:: python + .. code-block:: python - { - "rows":[ - { - "asset": "BTC", - "latestAnnualPercentageRate": "0.05000000", - "tierAnnualPercentageRate": { - "0-5BTC": 0.05, - "5-10BTC": 0.03 - }, - "airDropPercentageRate": "0.05000000", - "canPurchase": true, - "canRedeem": true, - "isSoldOut": true, - "hot": true, - "minPurchaseAmount": "0.01000000", - "productId": "BTC001", - "subscriptionStartTime": "1646182276000", - "status": "PURCHASING" - } - ], - "total": 1 - } + { + "rows":[ + { + "asset": "BTC", + "latestAnnualPercentageRate": "0.05000000", + "tierAnnualPercentageRate": { + "0-5BTC": 0.05, + "5-10BTC": 0.03 + }, + "airDropPercentageRate": "0.05000000", + "canPurchase": true, + "canRedeem": true, + "isSoldOut": true, + "hot": true, + "minPurchaseAmount": "0.01000000", + "productId": "BTC001", + "subscriptionStartTime": "1646182276000", + "status": "PURCHASING" + } + ], + "total": 1 + } - :raises: BinanceRequestException, BinanceAPIException + :raises: BinanceRequestException, BinanceAPIException - """ - return self._request_margin_api('get', 'simple-earn/flexible/list', signed=True, data=params) + """ + return self._request_margin_api( + "get", "simple-earn/flexible/list", signed=True, data=params + ) def get_simple_earn_locked_product_list(self, **params): """Get available Simple Earn flexible product list - https://binance-docs.github.io/apidocs/spot/en/#get-simple-earn-locked-product-list-user_data + https://binance-docs.github.io/apidocs/spot/en/#get-simple-earn-locked-product-list-user_data - :param asset: optional - :type asset: str - :param current: optional - Currently querying page. Start from 1. Default:1 - :type current: int - :param size: optional - Default:10, Max:100 - :type size: int - :param recvWindow: the number of milliseconds the request is valid for - :type recvWindow: int + :param asset: optional + :type asset: str + :param current: optional - Currently querying page. Start from 1. Default:1 + :type current: int + :param size: optional - Default:10, Max:100 + :type size: int + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int - :returns: API response + :returns: API response - .. code-block:: python + .. code-block:: python - { - "rows": [ - { - "projectId": "Axs*90", - "detail": { - "asset": "AXS", - "rewardAsset": "AXS", - "duration": 90, - "renewable": true, - "isSoldOut": true, - "apr": "1.2069", - "status": "CREATED", - "subscriptionStartTime": "1646182276000", - "extraRewardAsset": "BNB", - "extraRewardAPR": "0.23" - }, - "quota": { - "totalPersonalQuota": "2", - "minimum": "0.001" - } - } - ], - "total": 1 - } + { + "rows": [ + { + "projectId": "Axs*90", + "detail": { + "asset": "AXS", + "rewardAsset": "AXS", + "duration": 90, + "renewable": true, + "isSoldOut": true, + "apr": "1.2069", + "status": "CREATED", + "subscriptionStartTime": "1646182276000", + "extraRewardAsset": "BNB", + "extraRewardAPR": "0.23" + }, + "quota": { + "totalPersonalQuota": "2", + "minimum": "0.001" + } + } + ], + "total": 1 + } - :raises: BinanceRequestException, BinanceAPIException + :raises: BinanceRequestException, BinanceAPIException - """ - return self._request_margin_api('get', 'simple-earn/locked/list', signed=True, data=params) + """ + return self._request_margin_api( + "get", "simple-earn/locked/list", signed=True, data=params + ) def subscribe_simple_earn_flexible_product(self, **params): """Subscribe to a simple earn flexible product - https://binance-docs.github.io/apidocs/spot/en/#subscribe-locked-product-trade + https://binance-docs.github.io/apidocs/spot/en/#subscribe-locked-product-trade - :param productId: required - :type productId: str - :param amount: required - :type amount: str - :param autoSubscribe: optional - Default True - :type autoSubscribe: bool - :param recvWindow: the number of milliseconds the request is valid for - :type recvWindow: int + :param productId: required + :type productId: str + :param amount: required + :type amount: str + :param autoSubscribe: optional - Default True + :type autoSubscribe: bool + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int - :returns: API response + :returns: API response - .. code-block:: python + .. code-block:: python - { - "purchaseId": 40607, - "success": true - } + { + "purchaseId": 40607, + "success": true + } - :raises: BinanceRequestException, BinanceAPIException + :raises: BinanceRequestException, BinanceAPIException - """ - return self._request_margin_api('post', 'simple-earn/flexible/subscribe', signed=True, data=params) + """ + return self._request_margin_api( + "post", "simple-earn/flexible/subscribe", signed=True, data=params + ) def subscribe_simple_earn_locked_product(self, **params): """Subscribe to a simple earn locked product - https://binance-docs.github.io/apidocs/spot/en/#subscribe-locked-product-trade + https://binance-docs.github.io/apidocs/spot/en/#subscribe-locked-product-trade - :param productId: required - :type productId: str - :param amount: required - :type amount: str - :param autoSubscribe: optional - Default True - :type autoSubscribe: bool - :param recvWindow: the number of milliseconds the request is valid for - :type recvWindow: int + :param productId: required + :type productId: str + :param amount: required + :type amount: str + :param autoSubscribe: optional - Default True + :type autoSubscribe: bool + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int - :returns: API response + :returns: API response - .. code-block:: python + .. code-block:: python - { - "purchaseId": 40607, - "positionId": "12345", - "success": true - } + { + "purchaseId": 40607, + "positionId": "12345", + "success": true + } - :raises: BinanceRequestException, BinanceAPIException + :raises: BinanceRequestException, BinanceAPIException - """ - return self._request_margin_api('post', 'simple-earn/locked/subscribe', signed=True, data=params) + """ + return self._request_margin_api( + "post", "simple-earn/locked/subscribe", signed=True, data=params + ) def redeem_simple_earn_flexible_product(self, **params): """Redeem a simple earn flexible product - https://binance-docs.github.io/apidocs/spot/en/#redeem-flexible-product-trade + https://binance-docs.github.io/apidocs/spot/en/#redeem-flexible-product-trade - :param productId: required - :type productId: str - :param amount: optional - :type amount: str - :param redeemAll: optional - Default False - :type redeemAll: bool - :param recvWindow: the number of milliseconds the request is valid for - :type recvWindow: int + :param productId: required + :type productId: str + :param amount: optional + :type amount: str + :param redeemAll: optional - Default False + :type redeemAll: bool + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int - :returns: API response + :returns: API response - .. code-block:: python + .. code-block:: python - { - "redeemId": 40607, - "success": true - } + { + "redeemId": 40607, + "success": true + } - :raises: BinanceRequestException, BinanceAPIException + :raises: BinanceRequestException, BinanceAPIException - """ - return self._request_margin_api('post', 'simple-earn/flexible/redeem', signed=True, data=params) + """ + return self._request_margin_api( + "post", "simple-earn/flexible/redeem", signed=True, data=params + ) def redeem_simple_earn_locked_product(self, **params): """Redeem a simple earn locked product - https://binance-docs.github.io/apidocs/spot/en/#redeem-locked-product-trade + https://binance-docs.github.io/apidocs/spot/en/#redeem-locked-product-trade - :param productId: required - :type productId: str - :param recvWindow: the number of milliseconds the request is valid for - :type recvWindow: int + :param productId: required + :type productId: str + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int - :returns: API response + :returns: API response - .. code-block:: python + .. code-block:: python - { - "redeemId": 40607, - "success": true - } + { + "redeemId": 40607, + "success": true + } - :raises: BinanceRequestException, BinanceAPIException + :raises: BinanceRequestException, BinanceAPIException - """ - return self._request_margin_api('post', 'simple-earn/locked/redeem', signed=True, data=params) + """ + return self._request_margin_api( + "post", "simple-earn/locked/redeem", signed=True, data=params + ) def get_simple_earn_flexible_product_position(self, **params): """ - https://binance-docs.github.io/apidocs/spot/en/#get-flexible-product-position-user_data + https://binance-docs.github.io/apidocs/spot/en/#get-flexible-product-position-user_data - :param asset: optional - :type asset: str - :param current: optional - Currently querying page. Start from 1. Default:1 - :type current: int - :param size: optional - Default:10, Max:100 - :type size: int - :param recvWindow: the number of milliseconds the request is valid for - :type recvWindow: int + :param asset: optional + :type asset: str + :param current: optional - Currently querying page. Start from 1. Default:1 + :type current: int + :param size: optional - Default:10, Max:100 + :type size: int + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int - :returns: API response + :returns: API response - .. code-block:: python + .. code-block:: python - { - "rows":[ - { - "totalAmount": "75.46000000", - "tierAnnualPercentageRate": { - "0-5BTC": 0.05, - "5-10BTC": 0.03 - }, - "latestAnnualPercentageRate": "0.02599895", - "yesterdayAirdropPercentageRate": "0.02599895", - "asset": "USDT", - "airDropAsset": "BETH", - "canRedeem": true, - "collateralAmount": "232.23123213", - "productId": "USDT001", - "yesterdayRealTimeRewards": "0.10293829", - "cumulativeBonusRewards": "0.22759183", - "cumulativeRealTimeRewards": "0.22759183", - "cumulativeTotalRewards": "0.45459183", - "autoSubscribe": true - } - ], - "total": 1 - } + { + "rows":[ + { + "totalAmount": "75.46000000", + "tierAnnualPercentageRate": { + "0-5BTC": 0.05, + "5-10BTC": 0.03 + }, + "latestAnnualPercentageRate": "0.02599895", + "yesterdayAirdropPercentageRate": "0.02599895", + "asset": "USDT", + "airDropAsset": "BETH", + "canRedeem": true, + "collateralAmount": "232.23123213", + "productId": "USDT001", + "yesterdayRealTimeRewards": "0.10293829", + "cumulativeBonusRewards": "0.22759183", + "cumulativeRealTimeRewards": "0.22759183", + "cumulativeTotalRewards": "0.45459183", + "autoSubscribe": true + } + ], + "total": 1 + } - :raises: BinanceRequestException, BinanceAPIException + :raises: BinanceRequestException, BinanceAPIException - """ - return self._request_margin_api('get', 'simple-earn/flexible/position', signed=True, data=params) + """ + return self._request_margin_api( + "get", "simple-earn/flexible/position", signed=True, data=params + ) def get_simple_earn_locked_product_position(self, **params): """ - https://binance-docs.github.io/apidocs/spot/en/#get-locked-product-position-user_data + https://binance-docs.github.io/apidocs/spot/en/#get-locked-product-position-user_data - :param asset: optional - :type asset: str - :param current: optional - Currently querying page. Start from 1. Default:1 - :type current: int - :param size: optional - Default:10, Max:100 - :type size: int - :param recvWindow: the number of milliseconds the request is valid for - :type recvWindow: int + :param asset: optional + :type asset: str + :param current: optional - Currently querying page. Start from 1. Default:1 + :type current: int + :param size: optional - Default:10, Max:100 + :type size: int + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int - :returns: API response + :returns: API response - .. code-block:: python + .. code-block:: python - { - "rows":[ - { - "positionId": "123123", - "projectId": "Axs*90", - "asset": "AXS", - "amount": "122.09202928", - "purchaseTime": "1646182276000", - "duration": "60", - "accrualDays": "4", - "rewardAsset": "AXS", - "APY": "0.23", - "isRenewable": true, - "isAutoRenew": true, - "redeemDate": "1732182276000" - } - ], - "total": 1 - } + { + "rows":[ + { + "positionId": "123123", + "projectId": "Axs*90", + "asset": "AXS", + "amount": "122.09202928", + "purchaseTime": "1646182276000", + "duration": "60", + "accrualDays": "4", + "rewardAsset": "AXS", + "APY": "0.23", + "isRenewable": true, + "isAutoRenew": true, + "redeemDate": "1732182276000" + } + ], + "total": 1 + } - :raises: BinanceRequestException, BinanceAPIException + :raises: BinanceRequestException, BinanceAPIException - """ - return self._request_margin_api('get', 'simple-earn/locked/position', signed=True, data=params) + """ + return self._request_margin_api( + "get", "simple-earn/locked/position", signed=True, data=params + ) def get_simple_earn_account(self, **params): """ - https://binance-docs.github.io/apidocs/spot/en/#simple-account-user_data + https://binance-docs.github.io/apidocs/spot/en/#simple-account-user_data - :param recvWindow: the number of milliseconds the request is valid for - :type recvWindow: int + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int - :returns: API response + :returns: API response - .. code-block:: python + .. code-block:: python - { - "totalAmountInBTC": "0.01067982", - "totalAmountInUSDT": "77.13289230", - "totalFlexibleAmountInBTC": "0.00000000", - "totalFlexibleAmountInUSDT": "0.00000000", - "totalLockedInBTC": "0.01067982", - "totalLockedInUSDT": "77.13289230" - } + { + "totalAmountInBTC": "0.01067982", + "totalAmountInUSDT": "77.13289230", + "totalFlexibleAmountInBTC": "0.00000000", + "totalFlexibleAmountInUSDT": "0.00000000", + "totalLockedInBTC": "0.01067982", + "totalLockedInUSDT": "77.13289230" + } - :raises: BinanceRequestException, BinanceAPIException + :raises: BinanceRequestException, BinanceAPIException - """ - return self._request_margin_api('get', 'simple-earn/account', signed=True, data=params) + """ + return self._request_margin_api( + "get", "simple-earn/account", signed=True, data=params + ) # Lending Endpoints @@ -5952,7 +6168,9 @@ def get_fixed_activity_project_list(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'lending/project/list', signed=True, data=params) + return self._request_margin_api( + "get", "lending/project/list", signed=True, data=params + ) def change_fixed_activity_to_daily_position(self, **params): """Change Fixed/Activity Position to Daily Position @@ -5960,7 +6178,9 @@ def change_fixed_activity_to_daily_position(self, **params): https://binance-docs.github.io/apidocs/spot/en/#change-fixed-activity-position-to-daily-position-user_data """ - return self._request_margin_api('post', 'lending/positionChanged', signed=True, data=params) + return self._request_margin_api( + "post", "lending/positionChanged", signed=True, data=params + ) # Staking Endpoints @@ -5970,7 +6190,9 @@ def get_staking_product_list(self, **params): https://binance-docs.github.io/apidocs/spot/en/#get-staking-product-list-user_data """ - return self._request_margin_api('get', 'staking/productList', signed=True, data=params) + return self._request_margin_api( + "get", "staking/productList", signed=True, data=params + ) def purchase_staking_product(self, **params): """Purchase Staking Product @@ -5978,7 +6200,9 @@ def purchase_staking_product(self, **params): https://binance-docs.github.io/apidocs/spot/en/#purchase-staking-product-user_data """ - return self._request_margin_api('post', 'staking/purchase', signed=True, data=params) + return self._request_margin_api( + "post", "staking/purchase", signed=True, data=params + ) def redeem_staking_product(self, **params): """Redeem Staking Product @@ -5986,7 +6210,9 @@ def redeem_staking_product(self, **params): https://binance-docs.github.io/apidocs/spot/en/#redeem-staking-product-user_data """ - return self._request_margin_api('post', 'staking/redeem', signed=True, data=params) + return self._request_margin_api( + "post", "staking/redeem", signed=True, data=params + ) def get_staking_position(self, **params): """Get Staking Product Position @@ -5994,7 +6220,9 @@ def get_staking_position(self, **params): https://binance-docs.github.io/apidocs/spot/en/#get-staking-product-position-user_data """ - return self._request_margin_api('get', 'staking/position', signed=True, data=params) + return self._request_margin_api( + "get", "staking/position", signed=True, data=params + ) def get_staking_purchase_history(self, **params): """Get Staking Purchase History @@ -6002,7 +6230,9 @@ def get_staking_purchase_history(self, **params): https://binance-docs.github.io/apidocs/spot/en/#get-staking-history-user_data """ - return self._request_margin_api('get', 'staking/purchaseRecord', signed=True, data=params) + return self._request_margin_api( + "get", "staking/purchaseRecord", signed=True, data=params + ) def set_auto_staking(self, **params): """Set Auto Staking on Locked Staking or Locked DeFi Staking @@ -6010,7 +6240,9 @@ def set_auto_staking(self, **params): https://binance-docs.github.io/apidocs/spot/en/#set-auto-staking-user_data """ - return self._request_margin_api('post', 'staking/setAutoStaking', signed=True, data=params) + return self._request_margin_api( + "post", "staking/setAutoStaking", signed=True, data=params + ) def get_personal_left_quota(self, **params): """Get Personal Left Quota of Staking Product @@ -6018,7 +6250,9 @@ def get_personal_left_quota(self, **params): https://binance-docs.github.io/apidocs/spot/en/#get-personal-left-quota-of-staking-product-user_data """ - return self._request_margin_api('get', 'staking/personalLeftQuota', signed=True, data=params) + return self._request_margin_api( + "get", "staking/personalLeftQuota", signed=True, data=params + ) # US Staking Endpoints @@ -6056,7 +6290,9 @@ def get_staking_balance_us(self, **params): """ assert self.tld == "us", "Endpoint only available on binance.us" - return self._request_margin_api("get", "staking/stakingBalance", True, data=params) + return self._request_margin_api( + "get", "staking/stakingBalance", True, data=params + ) def get_staking_history_us(self, **params): """Get staking history @@ -6074,7 +6310,9 @@ def get_staking_rewards_history_us(self, **params): """ assert self.tld == "us", "Endpoint only available on binance.us" - return self._request_margin_api("get", "staking/stakingRewardsHistory", True, data=params) + return self._request_margin_api( + "get", "staking/stakingRewardsHistory", True, data=params + ) # Sub Accounts @@ -6116,7 +6354,7 @@ def get_sub_account_list(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/list', True, data=params) + return self._request_margin_api("get", "sub-account/list", True, data=params) def get_sub_account_transfer_history(self, **params): """Query Sub-account Transfer History. @@ -6166,7 +6404,9 @@ def get_sub_account_transfer_history(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/sub/transfer/history', True, data=params) + return self._request_margin_api( + "get", "sub-account/sub/transfer/history", True, data=params + ) def get_sub_account_futures_transfer_history(self, **params): """Query Sub-account Futures Transfer History. @@ -6216,7 +6456,9 @@ def get_sub_account_futures_transfer_history(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/futures/internalTransfer', True, data=params) + return self._request_margin_api( + "get", "sub-account/futures/internalTransfer", True, data=params + ) def create_sub_account_futures_transfer(self, **params): """Execute sub-account Futures transfer @@ -6248,7 +6490,9 @@ def create_sub_account_futures_transfer(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'sub-account/futures/internalTransfer', True, data=params) + return self._request_margin_api( + "post", "sub-account/futures/internalTransfer", True, data=params + ) def get_sub_account_assets(self, **params): """Fetch sub-account assets @@ -6297,7 +6541,9 @@ def get_sub_account_assets(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/assets', True, data=params, version=4) + return self._request_margin_api( + "get", "sub-account/assets", True, data=params, version=4 + ) def query_subaccount_spot_summary(self, **params): """Query Sub-account Spot Assets Summary (For Master Account) @@ -6335,7 +6581,9 @@ def query_subaccount_spot_summary(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/spotSummary', True, data=params) + return self._request_margin_api( + "get", "sub-account/spotSummary", True, data=params + ) def get_subaccount_deposit_address(self, **params): """Get Sub-account Deposit Address (For Master Account) @@ -6365,7 +6613,9 @@ def get_subaccount_deposit_address(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'capital/deposit/subAddress', True, data=params) + return self._request_margin_api( + "get", "capital/deposit/subAddress", True, data=params + ) def get_subaccount_deposit_history(self, **params): """Get Sub-account Deposit History (For Master Account) @@ -6423,7 +6673,9 @@ def get_subaccount_deposit_history(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'capital/deposit/subHisrec', True, data=params) + return self._request_margin_api( + "get", "capital/deposit/subHisrec", True, data=params + ) def get_subaccount_futures_margin_status(self, **params): """Get Sub-account's Status on Margin/Futures (For Master Account) @@ -6454,7 +6706,7 @@ def get_subaccount_futures_margin_status(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/status', True, data=params) + return self._request_margin_api("get", "sub-account/status", True, data=params) def enable_subaccount_margin(self, **params): """Enable Margin for Sub-account (For Master Account) @@ -6481,7 +6733,9 @@ def enable_subaccount_margin(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'sub-account/margin/enable', True, data=params) + return self._request_margin_api( + "post", "sub-account/margin/enable", True, data=params + ) def get_subaccount_margin_details(self, **params): """Get Detail on Sub-account's Margin Account (For Master Account) @@ -6548,7 +6802,9 @@ def get_subaccount_margin_details(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/margin/account', True, data=params) + return self._request_margin_api( + "get", "sub-account/margin/account", True, data=params + ) def get_subaccount_margin_summary(self, **params): """Get Summary of Sub-account's Margin Account (For Master Account) @@ -6585,7 +6841,9 @@ def get_subaccount_margin_summary(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/margin/accountSummary', True, data=params) + return self._request_margin_api( + "get", "sub-account/margin/accountSummary", True, data=params + ) def enable_subaccount_futures(self, **params): """Enable Futures for Sub-account (For Master Account) @@ -6612,7 +6870,9 @@ def enable_subaccount_futures(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'sub-account/futures/enable', True, data=params) + return self._request_margin_api( + "post", "sub-account/futures/enable", True, data=params + ) def get_subaccount_futures_details(self, **params): """Get Detail on Sub-account's Futures Account (For Master Account) @@ -6662,7 +6922,9 @@ def get_subaccount_futures_details(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/futures/account', True, data=params, version=2) + return self._request_margin_api( + "get", "sub-account/futures/account", True, data=params, version=2 + ) def get_subaccount_futures_summary(self, **params): """Get Summary of Sub-account's Futures Account (For Master Account) @@ -6714,7 +6976,9 @@ def get_subaccount_futures_summary(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/futures/accountSummary', True, data=params, version=2) + return self._request_margin_api( + "get", "sub-account/futures/accountSummary", True, data=params, version=2 + ) def get_subaccount_futures_positionrisk(self, **params): """Get Futures Position-Risk of Sub-account (For Master Account) @@ -6746,7 +7010,9 @@ def get_subaccount_futures_positionrisk(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/futures/positionRisk', True, data=params, version=2) + return self._request_margin_api( + "get", "sub-account/futures/positionRisk", True, data=params, version=2 + ) def make_subaccount_futures_transfer(self, **params): """Futures Transfer for Sub-account (For Master Account) @@ -6776,7 +7042,9 @@ def make_subaccount_futures_transfer(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'sub-account/futures/transfer', True, data=params) + return self._request_margin_api( + "post", "sub-account/futures/transfer", True, data=params + ) def make_subaccount_margin_transfer(self, **params): """Margin Transfer for Sub-account (For Master Account) @@ -6804,7 +7072,9 @@ def make_subaccount_margin_transfer(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'sub-account/margin/transfer', True, data=params) + return self._request_margin_api( + "post", "sub-account/margin/transfer", True, data=params + ) def make_subaccount_to_subaccount_transfer(self, **params): """Transfer to Sub-account of Same Master (For Sub-account) @@ -6831,7 +7101,9 @@ def make_subaccount_to_subaccount_transfer(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'sub-account/transfer/subToSub', True, data=params) + return self._request_margin_api( + "post", "sub-account/transfer/subToSub", True, data=params + ) def make_subaccount_to_master_transfer(self, **params): """Transfer to Master (For Sub-account) @@ -6856,7 +7128,9 @@ def make_subaccount_to_master_transfer(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'sub-account/transfer/subToMaster', True, data=params) + return self._request_margin_api( + "post", "sub-account/transfer/subToMaster", True, data=params + ) def get_subaccount_transfer_history(self, **params): """Sub-account Transfer History (For Sub-account) @@ -6906,7 +7180,9 @@ def get_subaccount_transfer_history(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/transfer/subUserHistory', True, data=params) + return self._request_margin_api( + "get", "sub-account/transfer/subUserHistory", True, data=params + ) def make_subaccount_universal_transfer(self, **params): """Universal Transfer (For Master Account) @@ -6939,7 +7215,9 @@ def make_subaccount_universal_transfer(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'sub-account/universalTransfer', True, data=params) + return self._request_margin_api( + "post", "sub-account/universalTransfer", True, data=params + ) def get_universal_transfer_history(self, **params): """Universal Transfer (For Master Account) @@ -6993,7 +7271,9 @@ def get_universal_transfer_history(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'sub-account/universalTransfer', True, data=params) + return self._request_margin_api( + "get", "sub-account/universalTransfer", True, data=params + ) # Futures API @@ -7003,7 +7283,7 @@ def futures_ping(self): https://binance-docs.github.io/apidocs/futures/en/#test-connectivity """ - return self._request_futures_api('get', 'ping') + return self._request_futures_api("get", "ping") def futures_time(self): """Test connectivity to the Rest API and get the current server time. @@ -7011,7 +7291,7 @@ def futures_time(self): https://binance-docs.github.io/apidocs/futures/en/#check-server-time """ - return self._request_futures_api('get', 'time') + return self._request_futures_api("get", "time") def futures_exchange_info(self): """Current exchange trading rules and symbol information @@ -7019,7 +7299,7 @@ def futures_exchange_info(self): https://binance-docs.github.io/apidocs/futures/en/#exchange-information-market_data """ - return self._request_futures_api('get', 'exchangeInfo') + return self._request_futures_api("get", "exchangeInfo") def futures_order_book(self, **params): """Get the Order Book for the market @@ -7027,7 +7307,7 @@ def futures_order_book(self, **params): https://binance-docs.github.io/apidocs/futures/en/#order-book-market_data """ - return self._request_futures_api('get', 'depth', data=params) + return self._request_futures_api("get", "depth", data=params) def futures_recent_trades(self, **params): """Get recent trades (up to last 500). @@ -7035,7 +7315,7 @@ def futures_recent_trades(self, **params): https://binance-docs.github.io/apidocs/futures/en/#recent-trades-list-market_data """ - return self._request_futures_api('get', 'trades', data=params) + return self._request_futures_api("get", "trades", data=params) def futures_historical_trades(self, **params): """Get older market historical trades. @@ -7043,7 +7323,7 @@ def futures_historical_trades(self, **params): https://binance-docs.github.io/apidocs/futures/en/#old-trades-lookup-market_data """ - return self._request_futures_api('get', 'historicalTrades', data=params) + return self._request_futures_api("get", "historicalTrades", data=params) def futures_aggregate_trades(self, **params): """Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same @@ -7052,7 +7332,7 @@ def futures_aggregate_trades(self, **params): https://binance-docs.github.io/apidocs/futures/en/#compressed-aggregate-trades-list-market_data """ - return self._request_futures_api('get', 'aggTrades', data=params) + return self._request_futures_api("get", "aggTrades", data=params) def futures_klines(self, **params): """Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. @@ -7060,7 +7340,7 @@ def futures_klines(self, **params): https://binance-docs.github.io/apidocs/futures/en/#kline-candlestick-data-market_data """ - return self._request_futures_api('get', 'klines', data=params) + return self._request_futures_api("get", "klines", data=params) def futures_continous_klines(self, **params): """Kline/candlestick bars for a specific contract type. Klines are uniquely identified by their open time. @@ -7068,9 +7348,11 @@ def futures_continous_klines(self, **params): https://binance-docs.github.io/apidocs/futures/en/#continuous-contract-kline-candlestick-data """ - return self._request_futures_api('get', 'continuousKlines', data=params) + return self._request_futures_api("get", "continuousKlines", data=params) - def futures_historical_klines(self, symbol, interval, start_str, end_str=None, limit=500): + def futures_historical_klines( + self, symbol, interval, start_str, end_str=None, limit=500 + ): """Get historical futures klines from Binance :param symbol: Name of symbol pair e.g. BNBBTC @@ -7087,9 +7369,18 @@ def futures_historical_klines(self, symbol, interval, start_str, end_str=None, l :return: list of OHLCV values (Open time, Open, High, Low, Close, Volume, Close time, Quote asset volume, Number of trades, Taker buy base asset volume, Taker buy quote asset volume, Ignore) """ - return self._historical_klines(symbol, interval, start_str, end_str=end_str, limit=limit, klines_type=HistoricalKlinesType.FUTURES) + return self._historical_klines( + symbol, + interval, + start_str, + end_str=end_str, + limit=limit, + klines_type=HistoricalKlinesType.FUTURES, + ) - def futures_historical_klines_generator(self, symbol, interval, start_str, end_str=None): + def futures_historical_klines_generator( + self, symbol, interval, start_str, end_str=None + ): """Get historical futures klines generator from Binance :param symbol: Name of symbol pair e.g. BNBBTC @@ -7105,7 +7396,13 @@ def futures_historical_klines_generator(self, symbol, interval, start_str, end_s """ - return self._historical_klines_generator(symbol, interval, start_str, end_str=end_str, klines_type=HistoricalKlinesType.FUTURES) + return self._historical_klines_generator( + symbol, + interval, + start_str, + end_str=end_str, + klines_type=HistoricalKlinesType.FUTURES, + ) def futures_mark_price(self, **params): """Get Mark Price and Funding Rate @@ -7113,7 +7410,7 @@ def futures_mark_price(self, **params): https://binance-docs.github.io/apidocs/futures/en/#mark-price-market_data """ - return self._request_futures_api('get', 'premiumIndex', data=params) + return self._request_futures_api("get", "premiumIndex", data=params) def futures_funding_rate(self, **params): """Get funding rate history @@ -7121,28 +7418,34 @@ def futures_funding_rate(self, **params): https://binance-docs.github.io/apidocs/futures/en/#get-funding-rate-history-market_data """ - return self._request_futures_api('get', 'fundingRate', data=params) + return self._request_futures_api("get", "fundingRate", data=params) def futures_top_longshort_account_ratio(self, **params): """Get present long to short ratio for top accounts of a specific symbol. https://binance-docs.github.io/apidocs/futures/en/#top-trader-long-short-ratio-accounts-market_data """ - return self._request_futures_data_api('get', 'topLongShortAccountRatio', data=params) + return self._request_futures_data_api( + "get", "topLongShortAccountRatio", data=params + ) def futures_top_longshort_position_ratio(self, **params): """Get present long to short ratio for top positions of a specific symbol. https://binance-docs.github.io/apidocs/futures/en/#top-trader-long-short-ratio-positions """ - return self._request_futures_data_api('get', 'topLongShortPositionRatio', data=params) + return self._request_futures_data_api( + "get", "topLongShortPositionRatio", data=params + ) def futures_global_longshort_ratio(self, **params): """Get present global long to short ratio of a specific symbol. https://binance-docs.github.io/apidocs/futures/en/#long-short-ratio """ - return self._request_futures_data_api('get', 'globalLongShortAccountRatio', data=params) + return self._request_futures_data_api( + "get", "globalLongShortAccountRatio", data=params + ) def futures_ticker(self, **params): """24 hour rolling window price change statistics. @@ -7150,7 +7453,7 @@ def futures_ticker(self, **params): https://binance-docs.github.io/apidocs/futures/en/#24hr-ticker-price-change-statistics-market_data """ - return self._request_futures_api('get', 'ticker/24hr', data=params) + return self._request_futures_api("get", "ticker/24hr", data=params) def futures_symbol_ticker(self, **params): """Latest price for a symbol or symbols. @@ -7158,7 +7461,7 @@ def futures_symbol_ticker(self, **params): https://binance-docs.github.io/apidocs/futures/en/#symbol-price-ticker-market_data """ - return self._request_futures_api('get', 'ticker/price', data=params) + return self._request_futures_api("get", "ticker/price", data=params) def futures_orderbook_ticker(self, **params): """Best price/qty on the order book for a symbol or symbols. @@ -7166,7 +7469,7 @@ def futures_orderbook_ticker(self, **params): https://binance-docs.github.io/apidocs/futures/en/#symbol-order-book-ticker-market_data """ - return self._request_futures_api('get', 'ticker/bookTicker', data=params) + return self._request_futures_api("get", "ticker/bookTicker", data=params) def futures_liquidation_orders(self, **params): """Get all liquidation orders @@ -7174,7 +7477,7 @@ def futures_liquidation_orders(self, **params): https://binance-docs.github.io/apidocs/futures/en/#get-all-liquidation-orders-market_data """ - return self._request_futures_api('get', 'forceOrders', signed=True, data=params) + return self._request_futures_api("get", "forceOrders", signed=True, data=params) def futures_api_trading_status(self, **params): """Get quantitative trading rules for order placement, such as Unfilled Ratio (UFR), Good-Til-Canceled Ratio (GCR), @@ -7259,7 +7562,9 @@ def futures_api_trading_status(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_futures_api('get', 'apiTradingStatus', signed=True, data=params) + return self._request_futures_api( + "get", "apiTradingStatus", signed=True, data=params + ) def futures_commission_rate(self, **params): """Get Futures commission rate @@ -7282,7 +7587,9 @@ def futures_commission_rate(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_futures_api('get', 'commissionRate', signed=True, data=params) + return self._request_futures_api( + "get", "commissionRate", signed=True, data=params + ) def futures_adl_quantile_estimate(self, **params): """Get Position ADL Quantile Estimate @@ -7290,7 +7597,7 @@ def futures_adl_quantile_estimate(self, **params): https://binance-docs.github.io/apidocs/futures/en/#position-adl-quantile-estimation-user_data """ - return self._request_futures_api('get', 'adlQuantile', signed=True, data=params) + return self._request_futures_api("get", "adlQuantile", signed=True, data=params) def futures_open_interest(self, **params): """Get present open interest of a specific symbol. @@ -7298,7 +7605,7 @@ def futures_open_interest(self, **params): https://binance-docs.github.io/apidocs/futures/en/#open-interest """ - return self._request_futures_api('get', 'openInterest', data=params) + return self._request_futures_api("get", "openInterest", data=params) def futures_index_info(self, **params): """Get index_info @@ -7306,7 +7613,7 @@ def futures_index_info(self, **params): https://binance-docs.github.io/apidocs/futures/en/#indexInfo """ - return self._request_futures_api('get', 'indexInfo', data=params) + return self._request_futures_api("get", "indexInfo", data=params) def futures_open_interest_hist(self, **params): """Get open interest statistics of a specific symbol. @@ -7314,7 +7621,7 @@ def futures_open_interest_hist(self, **params): https://binance-docs.github.io/apidocs/futures/en/#open-interest-statistics """ - return self._request_futures_data_api('get', 'openInterestHist', data=params) + return self._request_futures_data_api("get", "openInterestHist", data=params) def futures_leverage_bracket(self, **params): """Notional and Leverage Brackets @@ -7322,7 +7629,7 @@ def futures_leverage_bracket(self, **params): https://binance-docs.github.io/apidocs/futures/en/#notional-and-leverage-brackets-market_data """ - return self._request_futures_api('get', 'leverageBracket', True, data=params) + return self._request_futures_api("get", "leverageBracket", True, data=params) def futures_account_transfer(self, **params): """Execute transfer between spot account and futures account. @@ -7330,7 +7637,7 @@ def futures_account_transfer(self, **params): https://binance-docs.github.io/apidocs/futures/en/#new-future-account-transfer """ - return self._request_margin_api('post', 'futures/transfer', True, data=params) + return self._request_margin_api("post", "futures/transfer", True, data=params) def transfer_history(self, **params): """Get future account transaction history list @@ -7338,25 +7645,37 @@ def transfer_history(self, **params): https://binance-docs.github.io/apidocs/futures/en/#get-future-account-transaction-history-list-user_data """ - return self._request_margin_api('get', 'futures/transfer', True, data=params) + return self._request_margin_api("get", "futures/transfer", True, data=params) def futures_loan_borrow_history(self, **params): - return self._request_margin_api('get', 'futures/loan/borrow/history', True, data=params) + return self._request_margin_api( + "get", "futures/loan/borrow/history", True, data=params + ) def futures_loan_repay_history(self, **params): - return self._request_margin_api('get', 'futures/loan/repay/history', True, data=params) + return self._request_margin_api( + "get", "futures/loan/repay/history", True, data=params + ) def futures_loan_wallet(self, **params): - return self._request_margin_api('get', 'futures/loan/wallet', True, data=params, version=2) + return self._request_margin_api( + "get", "futures/loan/wallet", True, data=params, version=2 + ) def futures_cross_collateral_adjust_history(self, **params): - return self._request_margin_api('get', 'futures/loan/adjustCollateral/history', True, data=params) + return self._request_margin_api( + "get", "futures/loan/adjustCollateral/history", True, data=params + ) def futures_cross_collateral_liquidation_history(self, **params): - return self._request_margin_api('get', 'futures/loan/liquidationHistory', True, data=params) + return self._request_margin_api( + "get", "futures/loan/liquidationHistory", True, data=params + ) def futures_loan_interest_history(self, **params): - return self._request_margin_api('get', 'futures/loan/interestHistory', True, data=params) + return self._request_margin_api( + "get", "futures/loan/interestHistory", True, data=params + ) def futures_create_order(self, **params): """Send in a new order. @@ -7364,9 +7683,9 @@ def futures_create_order(self, **params): https://binance-docs.github.io/apidocs/futures/en/#new-order-trade """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return self._request_futures_api('post', 'order', True, data=params) + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return self._request_futures_api("post", "order", True, data=params) def futures_modify_order(self, **params): """Modify an existing order. Currently only LIMIT order modification is supported. @@ -7374,7 +7693,7 @@ def futures_modify_order(self, **params): https://binance-docs.github.io/apidocs/futures/en/#modify-order-trade """ - return self._request_futures_api('put', 'order', True, data=params) + return self._request_futures_api("put", "order", True, data=params) def futures_create_test_order(self, **params): """Testing order request, this order will not be submitted to matching engine @@ -7382,7 +7701,7 @@ def futures_create_test_order(self, **params): https://binance-docs.github.io/apidocs/futures/en/#test-order-trade """ - return self._request_futures_api('post', 'order/test', True, data=params) + return self._request_futures_api("post", "order/test", True, data=params) def futures_place_batch_order(self, **params): """Send in new orders. @@ -7393,13 +7712,13 @@ def futures_place_batch_order(self, **params): the url encoding is done on the special query param, batchOrders, in the early stage. """ - for order in params['batchOrders']: - if 'newClientOrderId' not in order: - order['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + for order in params["batchOrders"]: + if "newClientOrderId" not in order: + order["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() query_string = urlencode(params) - query_string = query_string.replace('%27', '%22') - params['batchOrders'] = query_string[12:] - return self._request_futures_api('post', 'batchOrders', True, data=params) + query_string = query_string.replace("%27", "%22") + params["batchOrders"] = query_string[12:] + return self._request_futures_api("post", "batchOrders", True, data=params) def futures_get_order(self, **params): """Check an order's status. @@ -7407,7 +7726,7 @@ def futures_get_order(self, **params): https://binance-docs.github.io/apidocs/futures/en/#query-order-user_data """ - return self._request_futures_api('get', 'order', True, data=params) + return self._request_futures_api("get", "order", True, data=params) def futures_get_open_orders(self, **params): """Get all open orders on a symbol. @@ -7415,7 +7734,7 @@ def futures_get_open_orders(self, **params): https://binance-docs.github.io/apidocs/futures/en/#current-open-orders-user_data """ - return self._request_futures_api('get', 'openOrders', True, data=params) + return self._request_futures_api("get", "openOrders", True, data=params) def futures_get_all_orders(self, **params): """Get all futures account orders; active, canceled, or filled. @@ -7423,7 +7742,7 @@ def futures_get_all_orders(self, **params): https://binance-docs.github.io/apidocs/futures/en/#all-orders-user_data """ - return self._request_futures_api('get', 'allOrders', True, data=params) + return self._request_futures_api("get", "allOrders", True, data=params) def futures_cancel_order(self, **params): """Cancel an active futures order. @@ -7431,7 +7750,7 @@ def futures_cancel_order(self, **params): https://binance-docs.github.io/apidocs/futures/en/#cancel-order-trade """ - return self._request_futures_api('delete', 'order', True, data=params) + return self._request_futures_api("delete", "order", True, data=params) def futures_cancel_all_open_orders(self, **params): """Cancel all open futures orders @@ -7439,7 +7758,7 @@ def futures_cancel_all_open_orders(self, **params): https://binance-docs.github.io/apidocs/futures/en/#cancel-all-open-orders-trade """ - return self._request_futures_api('delete', 'allOpenOrders', True, data=params) + return self._request_futures_api("delete", "allOpenOrders", True, data=params) def futures_cancel_orders(self, **params): """Cancel multiple futures orders @@ -7447,7 +7766,7 @@ def futures_cancel_orders(self, **params): https://binance-docs.github.io/apidocs/futures/en/#cancel-multiple-orders-trade """ - return self._request_futures_api('delete', 'batchOrders', True, data=params) + return self._request_futures_api("delete", "batchOrders", True, data=params) def futures_countdown_cancel_all(self, **params): """Cancel all open orders of the specified symbol at the end of the specified countdown. @@ -7470,7 +7789,9 @@ def futures_countdown_cancel_all(self, **params): } """ - return self._request_futures_api('post', 'countdownCancelAll', True, data=params) + return self._request_futures_api( + "post", "countdownCancelAll", True, data=params + ) def futures_account_balance(self, **params): """Get futures account balance @@ -7478,7 +7799,7 @@ def futures_account_balance(self, **params): https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Futures-Account-Balance-V3 """ - return self._request_futures_api('get', 'balance', True, 3, data=params) + return self._request_futures_api("get", "balance", True, 3, data=params) def futures_account(self, **params): """Get current account information. @@ -7486,7 +7807,7 @@ def futures_account(self, **params): https://binance-docs.github.io/apidocs/futures/en/#account-information-user_data """ - return self._request_futures_api('get', 'account', True, 2, data=params) + return self._request_futures_api("get", "account", True, 2, data=params) def futures_change_leverage(self, **params): """Change user's initial leverage of specific symbol market @@ -7494,7 +7815,7 @@ def futures_change_leverage(self, **params): https://binance-docs.github.io/apidocs/futures/en/#change-initial-leverage-trade """ - return self._request_futures_api('post', 'leverage', True, data=params) + return self._request_futures_api("post", "leverage", True, data=params) def futures_change_margin_type(self, **params): """Change the margin type for a symbol @@ -7502,7 +7823,7 @@ def futures_change_margin_type(self, **params): https://binance-docs.github.io/apidocs/futures/en/#change-margin-type-trade """ - return self._request_futures_api('post', 'marginType', True, data=params) + return self._request_futures_api("post", "marginType", True, data=params) def futures_change_position_margin(self, **params): """Change the position margin for a symbol @@ -7510,7 +7831,7 @@ def futures_change_position_margin(self, **params): https://binance-docs.github.io/apidocs/futures/en/#modify-isolated-position-margin-trade """ - return self._request_futures_api('post', 'positionMargin', True, data=params) + return self._request_futures_api("post", "positionMargin", True, data=params) def futures_position_margin_history(self, **params): """Get position margin change history @@ -7518,7 +7839,9 @@ def futures_position_margin_history(self, **params): https://binance-docs.github.io/apidocs/futures/en/#get-postion-margin-change-history-trade """ - return self._request_futures_api('get', 'positionMargin/history', True, data=params) + return self._request_futures_api( + "get", "positionMargin/history", True, data=params + ) def futures_position_information(self, **params): """Get position information @@ -7526,7 +7849,7 @@ def futures_position_information(self, **params): https://binance-docs.github.io/apidocs/futures/en/#position-information-user_data """ - return self._request_futures_api('get', 'positionRisk', True, 3, data=params) + return self._request_futures_api("get", "positionRisk", True, 3, data=params) def futures_account_trades(self, **params): """Get trades for the authenticated account and symbol. @@ -7534,7 +7857,7 @@ def futures_account_trades(self, **params): https://binance-docs.github.io/apidocs/futures/en/#account-trade-list-user_data """ - return self._request_futures_api('get', 'userTrades', True, data=params) + return self._request_futures_api("get", "userTrades", True, data=params) def futures_income_history(self, **params): """Get income history for authenticated account @@ -7542,7 +7865,7 @@ def futures_income_history(self, **params): https://binance-docs.github.io/apidocs/futures/en/#get-income-history-user_data """ - return self._request_futures_api('get', 'income', True, data=params) + return self._request_futures_api("get", "income", True, data=params) def futures_change_position_mode(self, **params): """Change position mode for authenticated account @@ -7550,7 +7873,7 @@ def futures_change_position_mode(self, **params): https://binance-docs.github.io/apidocs/futures/en/#change-position-mode-trade """ - return self._request_futures_api('post', 'positionSide/dual', True, data=params) + return self._request_futures_api("post", "positionSide/dual", True, data=params) def futures_get_position_mode(self, **params): """Get position mode for authenticated account @@ -7558,7 +7881,7 @@ def futures_get_position_mode(self, **params): https://binance-docs.github.io/apidocs/futures/en/#get-current-position-mode-user_data """ - return self._request_futures_api('get', 'positionSide/dual', True, data=params) + return self._request_futures_api("get", "positionSide/dual", True, data=params) def futures_change_multi_assets_mode(self, multiAssetsMargin: bool): """Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on Every symbol @@ -7566,10 +7889,8 @@ def futures_change_multi_assets_mode(self, multiAssetsMargin: bool): https://binance-docs.github.io/apidocs/futures/en/#change-multi-assets-mode-trade """ - params = { - 'multiAssetsMargin': 'true' if multiAssetsMargin else 'false' - } - return self._request_futures_api('post', 'multiAssetsMargin', True, data=params) + params = {"multiAssetsMargin": "true" if multiAssetsMargin else "false"} + return self._request_futures_api("post", "multiAssetsMargin", True, data=params) def futures_get_multi_assets_mode(self): """Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on Every symbol @@ -7577,30 +7898,32 @@ def futures_get_multi_assets_mode(self): https://binance-docs.github.io/apidocs/futures/en/#get-current-multi-assets-mode-user_data """ - return self._request_futures_api('get', 'multiAssetsMargin', True, data={}) + return self._request_futures_api("get", "multiAssetsMargin", True, data={}) def futures_stream_get_listen_key(self): - res = self._request_futures_api('post', 'listenKey', signed=False, data={}) - return res['listenKey'] + res = self._request_futures_api("post", "listenKey", signed=False, data={}) + return res["listenKey"] def futures_stream_keepalive(self, listenKey): - params = { - 'listenKey': listenKey - } - return self._request_futures_api('put', 'listenKey', signed=False, data=params) + params = {"listenKey": listenKey} + return self._request_futures_api("put", "listenKey", signed=False, data=params) def futures_stream_close(self, listenKey): - params = { - 'listenKey': listenKey - } - return self._request_futures_api('delete', 'listenKey', signed=False, data=params) + params = {"listenKey": listenKey} + return self._request_futures_api( + "delete", "listenKey", signed=False, data=params + ) # new methods def futures_account_config(self, **params): - return self._request_futures_api('get', 'accountConfig', signed=True, version=1, data=params) + return self._request_futures_api( + "get", "accountConfig", signed=True, version=1, data=params + ) def futures_symbol_config(self, **params): - return self._request_futures_api('get', 'symbolConfig', signed=True, version=1, data=params) + return self._request_futures_api( + "get", "symbolConfig", signed=True, version=1, data=params + ) # COIN Futures API def futures_coin_ping(self): @@ -7738,7 +8061,9 @@ def futures_coin_liquidation_orders(self, **params): https://binance-docs.github.io/apidocs/delivery/en/#user-39-s-force-orders-user_data """ - return self._request_futures_coin_api("get", "forceOrders", signed=True, data=params) + return self._request_futures_coin_api( + "get", "forceOrders", signed=True, data=params + ) def futures_coin_open_interest(self, **params): """Get present open interest of a specific symbol. @@ -7754,7 +8079,9 @@ def futures_coin_open_interest_hist(self, **params): https://binance-docs.github.io/apidocs/delivery/en/#open-interest-statistics-market-data """ - return self._request_futures_coin_data_api("get", "openInterestHist", data=params) + return self._request_futures_coin_data_api( + "get", "openInterestHist", data=params + ) def futures_coin_leverage_bracket(self, **params): """Notional and Leverage Brackets @@ -7775,10 +8102,14 @@ def new_transfer_history(self, **params): return self._request_margin_api("get", "asset/transfer", True, data=params) def funding_wallet(self, **params): - return self._request_margin_api("post", "asset/get-funding-asset", True, data=params) + return self._request_margin_api( + "post", "asset/get-funding-asset", True, data=params + ) def get_user_asset(self, **params): - return self._request_margin_api("post", "asset/getUserAsset", True, data=params, version=3) + return self._request_margin_api( + "post", "asset/getUserAsset", True, data=params, version=3 + ) def universal_transfer(self, **params): """Unviversal transfer api accross different binance account types @@ -7795,8 +8126,8 @@ def futures_coin_create_order(self, **params): https://binance-docs.github.io/apidocs/delivery/en/#new-order-trade """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() return self._request_futures_coin_api("post", "order", True, data=params) def futures_coin_place_batch_order(self, **params): @@ -7808,14 +8139,14 @@ def futures_coin_place_batch_order(self, **params): the url encoding is done on the special query param, batchOrders, in the early stage. """ - for order in params['batchOrders']: - if 'newClientOrderId' not in order: - order['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + for order in params["batchOrders"]: + if "newClientOrderId" not in order: + order["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() query_string = urlencode(params) - query_string = query_string.replace('%27', '%22') - params['batchOrders'] = query_string[12:] + query_string = query_string.replace("%27", "%22") + params["batchOrders"] = query_string[12:] - return self._request_futures_coin_api('post', 'batchOrders', True, data=params) + return self._request_futures_coin_api("post", "batchOrders", True, data=params) def futures_coin_get_order(self, **params): """Check an order's status. @@ -7962,7 +8293,9 @@ def futures_coin_change_position_mode(self, **params): https://binance-docs.github.io/apidocs/delivery/en/#change-position-mode-trade """ - return self._request_futures_coin_api("post", "positionSide/dual", True, data=params) + return self._request_futures_coin_api( + "post", "positionSide/dual", True, data=params + ) def futures_coin_get_position_mode(self, **params): """Get user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol @@ -7970,23 +8303,25 @@ def futures_coin_get_position_mode(self, **params): https://binance-docs.github.io/apidocs/delivery/en/#get-current-position-mode-user_data """ - return self._request_futures_coin_api("get", "positionSide/dual", True, data=params) + return self._request_futures_coin_api( + "get", "positionSide/dual", True, data=params + ) def futures_coin_stream_get_listen_key(self): - res = self._request_futures_coin_api('post', 'listenKey', signed=False, data={}) - return res['listenKey'] + res = self._request_futures_coin_api("post", "listenKey", signed=False, data={}) + return res["listenKey"] def futures_coin_stream_keepalive(self, listenKey): - params = { - 'listenKey': listenKey - } - return self._request_futures_coin_api('put', 'listenKey', signed=False, data=params) + params = {"listenKey": listenKey} + return self._request_futures_coin_api( + "put", "listenKey", signed=False, data=params + ) def futures_coin_stream_close(self, listenKey): - params = { - 'listenKey': listenKey - } - return self._request_futures_coin_api('delete', 'listenKey', signed=False, data=params) + params = {"listenKey": listenKey} + return self._request_futures_coin_api( + "delete", "listenKey", signed=False, data=params + ) def get_all_coins_info(self, **params): """Get information of coins (available for deposit and withdraw) for user. @@ -8061,7 +8396,9 @@ def get_all_coins_info(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'capital/config/getall', True, data=params) + return self._request_margin_api( + "get", "capital/config/getall", True, data=params + ) def get_account_snapshot(self, **params): """Get daily account snapshot of specific type. @@ -8176,7 +8513,7 @@ def get_account_snapshot(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('get', 'accountSnapshot', True, data=params) + return self._request_margin_api("get", "accountSnapshot", True, data=params) def disable_fast_withdraw_switch(self, **params): """Disable Fast Withdraw Switch @@ -8191,7 +8528,9 @@ def disable_fast_withdraw_switch(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'disableFastWithdrawSwitch', True, data=params) + return self._request_margin_api( + "post", "disableFastWithdrawSwitch", True, data=params + ) def enable_fast_withdraw_switch(self, **params): """Enable Fast Withdraw Switch @@ -8206,7 +8545,9 @@ def enable_fast_withdraw_switch(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._request_margin_api('post', 'enableFastWithdrawSwitch', True, data=params) + return self._request_margin_api( + "post", "enableFastWithdrawSwitch", True, data=params + ) """ ==================================================================================================================== @@ -8221,7 +8562,7 @@ def options_ping(self): https://binance-docs.github.io/apidocs/voptions/en/#test-connectivity """ - return self._request_options_api('get', 'ping') + return self._request_options_api("get", "ping") def options_time(self): """Get server time @@ -8229,7 +8570,7 @@ def options_time(self): https://binance-docs.github.io/apidocs/voptions/en/#get-server-time """ - return self._request_options_api('get', 'time') + return self._request_options_api("get", "time") def options_info(self): """Get current trading pair info @@ -8237,7 +8578,7 @@ def options_info(self): https://binance-docs.github.io/apidocs/voptions/en/#get-current-trading-pair-info """ - return self._request_options_api('get', 'optionInfo') + return self._request_options_api("get", "optionInfo") def options_exchange_info(self): """Get current limit info and trading pair info @@ -8245,7 +8586,7 @@ def options_exchange_info(self): https://binance-docs.github.io/apidocs/voptions/en/#get-current-limit-info-and-trading-pair-info """ - return self._request_options_api('get', 'exchangeInfo') + return self._request_options_api("get", "exchangeInfo") def options_index_price(self, **params): """Get the spot index price @@ -8256,7 +8597,7 @@ def options_index_price(self, **params): :type underlying: str """ - return self._request_options_api('get', 'index', data=params) + return self._request_options_api("get", "index", data=params) def options_price(self, **params): """Get the latest price @@ -8267,7 +8608,7 @@ def options_price(self, **params): :type symbol: str """ - return self._request_options_api('get', 'ticker', data=params) + return self._request_options_api("get", "ticker", data=params) def options_mark_price(self, **params): """Get the latest mark price @@ -8278,7 +8619,7 @@ def options_mark_price(self, **params): :type symbol: str """ - return self._request_options_api('get', 'mark', data=params) + return self._request_options_api("get", "mark", data=params) def options_order_book(self, **params): """Depth information @@ -8291,7 +8632,7 @@ def options_order_book(self, **params): :type limit: int """ - return self._request_options_api('get', 'depth', data=params) + return self._request_options_api("get", "depth", data=params) def options_klines(self, **params): """Candle data @@ -8310,7 +8651,7 @@ def options_klines(self, **params): :type limit: int """ - return self._request_options_api('get', 'klines', data=params) + return self._request_options_api("get", "klines", data=params) def options_recent_trades(self, **params): """Recently completed Option trades @@ -8323,7 +8664,7 @@ def options_recent_trades(self, **params): :type limit: int """ - return self._request_options_api('get', 'trades', data=params) + return self._request_options_api("get", "trades", data=params) def options_historical_trades(self, **params): """Query trade history @@ -8338,7 +8679,7 @@ def options_historical_trades(self, **params): :type limit: int """ - return self._request_options_api('get', 'historicalTrades', data=params) + return self._request_options_api("get", "historicalTrades", data=params) # Account and trading interface endpoints @@ -8351,7 +8692,7 @@ def options_account_info(self, **params): :type recvWindow: int """ - return self._request_options_api('get', 'account', signed=True, data=params) + return self._request_options_api("get", "account", signed=True, data=params) def options_funds_transfer(self, **params): """Funds transfer (USER_DATA) @@ -8368,7 +8709,7 @@ def options_funds_transfer(self, **params): :type recvWindow: int """ - return self._request_options_api('post', 'transfer', signed=True, data=params) + return self._request_options_api("post", "transfer", signed=True, data=params) def options_positions(self, **params): """Option holdings info (USER_DATA) @@ -8381,7 +8722,7 @@ def options_positions(self, **params): :type recvWindow: int """ - return self._request_options_api('get', 'position', signed=True, data=params) + return self._request_options_api("get", "position", signed=True, data=params) def options_bill(self, **params): """Account funding flow (USER_DATA) @@ -8402,7 +8743,7 @@ def options_bill(self, **params): :type recvWindow: int """ - return self._request_options_api('post', 'bill', signed=True, data=params) + return self._request_options_api("post", "bill", signed=True, data=params) def options_place_order(self, **params): """Option order (TRADE) @@ -8433,9 +8774,9 @@ def options_place_order(self, **params): :type recvWindow: int """ - if 'clientOrderId' not in params: - params['clientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return self._request_options_api('post', 'order', signed=True, data=params) + if "clientOrderId" not in params: + params["clientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return self._request_options_api("post", "order", signed=True, data=params) def options_place_batch_order(self, **params): """Place Multiple Option orders (TRADE) @@ -8448,10 +8789,12 @@ def options_place_batch_order(self, **params): :type recvWindow: int """ - for order in params['batchOrders']: - if 'newClientOrderId' not in order: - order['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return self._request_options_api('post', 'batchOrders', signed=True, data=params) + for order in params["batchOrders"]: + if "newClientOrderId" not in order: + order["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return self._request_options_api( + "post", "batchOrders", signed=True, data=params + ) def options_cancel_order(self, **params): """Cancel Option order (TRADE) @@ -8468,7 +8811,7 @@ def options_cancel_order(self, **params): :type recvWindow: int """ - return self._request_options_api('delete', 'order', signed=True, data=params) + return self._request_options_api("delete", "order", signed=True, data=params) def options_cancel_batch_order(self, **params): """Cancel Multiple Option orders (TRADE) @@ -8485,7 +8828,9 @@ def options_cancel_batch_order(self, **params): :type recvWindow: int """ - return self._request_options_api('delete', 'batchOrders', signed=True, data=params) + return self._request_options_api( + "delete", "batchOrders", signed=True, data=params + ) def options_cancel_all_orders(self, **params): """Cancel all Option orders (TRADE) @@ -8498,7 +8843,9 @@ def options_cancel_all_orders(self, **params): :type recvWindow: int """ - return self._request_options_api('delete', 'allOpenOrders', signed=True, data=params) + return self._request_options_api( + "delete", "allOpenOrders", signed=True, data=params + ) def options_query_order(self, **params): """Query Option order (TRADE) @@ -8515,7 +8862,7 @@ def options_query_order(self, **params): :type recvWindow: int """ - return self._request_options_api('get', 'order', signed=True, data=params) + return self._request_options_api("get", "order", signed=True, data=params) def options_query_pending_orders(self, **params): """Query current pending Option orders (TRADE) @@ -8536,7 +8883,7 @@ def options_query_pending_orders(self, **params): :type recvWindow: int """ - return self._request_options_api('get', 'openOrders', signed=True, data=params) + return self._request_options_api("get", "openOrders", signed=True, data=params) def options_query_order_history(self, **params): """Query Option order history (TRADE) @@ -8557,7 +8904,9 @@ def options_query_order_history(self, **params): :type recvWindow: int """ - return self._request_options_api('get', 'historyOrders', signed=True, data=params) + return self._request_options_api( + "get", "historyOrders", signed=True, data=params + ) def options_user_trades(self, **params): """Option Trade List (USER_DATA) @@ -8578,7 +8927,7 @@ def options_user_trades(self, **params): :type recvWindow: int """ - return self._request_options_api('get', 'userTrades', signed=True, data=params) + return self._request_options_api("get", "userTrades", signed=True, data=params) # Fiat Endpoints @@ -8601,7 +8950,7 @@ def get_fiat_deposit_withdraw_history(self, **params): :type recvWindow: int """ - return self._request_margin_api('get', 'fiat/orders', signed=True, data=params) + return self._request_margin_api("get", "fiat/orders", signed=True, data=params) def get_fiat_payments_history(self, **params): """Get Fiat Payments History @@ -8622,7 +8971,9 @@ def get_fiat_payments_history(self, **params): :type recvWindow: int """ - return self._request_margin_api('get', 'fiat/payments', signed=True, data=params) + return self._request_margin_api( + "get", "fiat/payments", signed=True, data=params + ) # C2C Endpoints @@ -8672,7 +9023,9 @@ def get_c2c_trade_history(self, **params): } """ - return self._request_margin_api('get', 'c2c/orderMatch/listUserOrderHistory', signed=True, data=params) + return self._request_margin_api( + "get", "c2c/orderMatch/listUserOrderHistory", signed=True, data=params + ) # Pay Endpoints @@ -8693,7 +9046,9 @@ def get_pay_trade_history(self, **params): :returns: API response """ - return self._request_margin_api('get', 'pay/transactions', signed=True, data=params) + return self._request_margin_api( + "get", "pay/transactions", signed=True, data=params + ) # Convert Endpoints @@ -8714,7 +9069,9 @@ def get_convert_trade_history(self, **params): :returns: API response """ - return self._request_margin_api('get', 'convert/tradeFlow', signed=True, data=params) + return self._request_margin_api( + "get", "convert/tradeFlow", signed=True, data=params + ) def convert_request_quote(self, **params): """Request a quote for the requested token pairs @@ -8736,7 +9093,9 @@ def convert_request_quote(self, **params): :returns: API response """ - return self._request_margin_api('post', 'convert/getQuote', signed=True, data=params) + return self._request_margin_api( + "post", "convert/getQuote", signed=True, data=params + ) def convert_accept_quote(self, **params): """Accept the offered quote by quote ID. @@ -8752,7 +9111,9 @@ def convert_accept_quote(self, **params): :returns: API response """ - return self._request_margin_api('post', 'convert/acceptQuote', signed=True, data=params) + return self._request_margin_api( + "post", "convert/acceptQuote", signed=True, data=params + ) """ ==================================================================================================================== @@ -8774,7 +9135,7 @@ def papi_get_balance(self, **params): :returns: API response """ - return self._request_papi_api('get', 'balance', signed=True, data=params) + return self._request_papi_api("get", "balance", signed=True, data=params) def papi_get_account(self, **params): """Query account information. @@ -8787,7 +9148,7 @@ def papi_get_account(self, **params): :returns: API response """ - return self._request_papi_api('get', 'account', signed=True, data=params) + return self._request_papi_api("get", "account", signed=True, data=params) def papi_get_margin_max_borrowable(self, **params): """Query margin max borrow. @@ -8803,8 +9164,9 @@ def papi_get_margin_max_borrowable(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/maxBorrowable', signed=True, data=params) - + return self._request_papi_api( + "get", "margin/maxBorrowable", signed=True, data=params + ) def papi_get_margin_max_withdraw(self, **params): """Query margin max borrow. @@ -8820,8 +9182,9 @@ def papi_get_margin_max_withdraw(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/maxWithdraw', signed=True, data=params) - + return self._request_papi_api( + "get", "margin/maxWithdraw", signed=True, data=params + ) def papi_get_um_position_risk(self, **params): """Query margin max borrow. @@ -8837,9 +9200,9 @@ def papi_get_um_position_risk(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/positionRisk', signed=True, data=params) - - + return self._request_papi_api( + "get", "um/positionRisk", signed=True, data=params + ) def papi_get_cm_position_risk(self, **params): """Query margin max borrow. @@ -8855,9 +9218,9 @@ def papi_get_cm_position_risk(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/positionRisk', signed=True, data=params) - - + return self._request_papi_api( + "get", "cm/positionRisk", signed=True, data=params + ) def papi_set_um_leverage(self, **params): """Query margin max borrow. @@ -8876,8 +9239,7 @@ def papi_set_um_leverage(self, **params): :returns: API response """ - return self._request_papi_api('post', 'um/leverage', signed=True, data=params) - + return self._request_papi_api("post", "um/leverage", signed=True, data=params) def papi_set_cm_leverage(self, **params): """Query margin max borrow. @@ -8896,8 +9258,7 @@ def papi_set_cm_leverage(self, **params): :returns: API response """ - return self._request_papi_api('post', 'cm/leverage', signed=True, data=params) - + return self._request_papi_api("post", "cm/leverage", signed=True, data=params) def papi_change_um_position_side_dual(self, **params): """Change user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol in UM. @@ -8913,8 +9274,9 @@ def papi_change_um_position_side_dual(self, **params): :returns: API response """ - return self._request_papi_api('post', 'um/positionSide/dual', signed=True, data=params) - + return self._request_papi_api( + "post", "um/positionSide/dual", signed=True, data=params + ) def papi_get_um_position_side_dual(self, **params): """Get user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol in UM. @@ -8927,8 +9289,9 @@ def papi_get_um_position_side_dual(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/positionSide/dual', signed=True, data=params) - + return self._request_papi_api( + "get", "um/positionSide/dual", signed=True, data=params + ) def papi_get_cm_position_side_dual(self, **params): """Get user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol in CM. @@ -8941,8 +9304,9 @@ def papi_get_cm_position_side_dual(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/positionSide/dual', signed=True, data=params) - + return self._request_papi_api( + "get", "cm/positionSide/dual", signed=True, data=params + ) def papi_get_um_leverage_bracket(self, **params): """Query UM notional and leverage brackets. @@ -8958,8 +9322,9 @@ def papi_get_um_leverage_bracket(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/leverageBracket', signed=True, data=params) - + return self._request_papi_api( + "get", "um/leverageBracket", signed=True, data=params + ) def papi_get_cm_leverage_bracket(self, **params): """Query CM notional and leverage brackets. @@ -8975,7 +9340,9 @@ def papi_get_cm_leverage_bracket(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/leverageBracket', signed=True, data=params) + return self._request_papi_api( + "get", "cm/leverageBracket", signed=True, data=params + ) def papi_get_um_api_trading_status(self, **params): """Portfolio Margin UM Trading Quantitative Rules Indicators. @@ -8991,8 +9358,9 @@ def papi_get_um_api_trading_status(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/apiTradingStatus', signed=True, data=params) - + return self._request_papi_api( + "get", "um/apiTradingStatus", signed=True, data=params + ) def papi_get_um_comission_rate(self, **params): """Get User Commission Rate for UM. @@ -9008,8 +9376,9 @@ def papi_get_um_comission_rate(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/commissionRate', signed=True, data=params) - + return self._request_papi_api( + "get", "um/commissionRate", signed=True, data=params + ) def papi_get_cm_comission_rate(self, **params): """Get User Commission Rate for CM. @@ -9025,7 +9394,9 @@ def papi_get_cm_comission_rate(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/commissionRate', signed=True, data=params) + return self._request_papi_api( + "get", "cm/commissionRate", signed=True, data=params + ) def papi_get_margin_margin_loan(self, **params): """Query margin loan record. @@ -9041,7 +9412,9 @@ def papi_get_margin_margin_loan(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/marginLoan', signed=True, data=params) + return self._request_papi_api( + "get", "margin/marginLoan", signed=True, data=params + ) def papi_get_margin_repay_loan(self, **params): """Query margin repay record. @@ -9057,8 +9430,9 @@ def papi_get_margin_repay_loan(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/repayLoan', signed=True, data=params) - + return self._request_papi_api( + "get", "margin/repayLoan", signed=True, data=params + ) def papi_get_repay_futures_switch(self, **params): """Query Auto-repay-futures Status. @@ -9071,8 +9445,9 @@ def papi_get_repay_futures_switch(self, **params): :returns: API response """ - return self._request_papi_api('get', 'repay-futures-switch', signed=True, data=params) - + return self._request_papi_api( + "get", "repay-futures-switch", signed=True, data=params + ) def papi_repay_futures_switch(self, **params): """Change Auto-repay-futures Status. @@ -9088,8 +9463,9 @@ def papi_repay_futures_switch(self, **params): :returns: API response """ - return self._request_papi_api('post', 'repay-futures-switch', signed=True, data=params) - + return self._request_papi_api( + "post", "repay-futures-switch", signed=True, data=params + ) def papi_get_margin_interest_history(self, **params): """Get Margin Borrow/Loan Interest History. @@ -9102,8 +9478,9 @@ def papi_get_margin_interest_history(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/marginInterestHistory', signed=True, data=params) - + return self._request_papi_api( + "get", "margin/marginInterestHistory", signed=True, data=params + ) def papi_repay_futures_negative_balance(self, **params): """Repay futures Negative Balance. @@ -9116,8 +9493,9 @@ def papi_repay_futures_negative_balance(self, **params): :returns: API response """ - return self._request_papi_api('post', 'repay-futures-negative-balance', signed=True, data=params) - + return self._request_papi_api( + "post", "repay-futures-negative-balance", signed=True, data=params + ) def papi_get_portfolio_interest_history(self, **params): """GQuery interest history of negative balance for portfolio margin. @@ -9130,8 +9508,9 @@ def papi_get_portfolio_interest_history(self, **params): :returns: API response """ - return self._request_papi_api('get', 'portfolio/interest-history', signed=True, data=params) - + return self._request_papi_api( + "get", "portfolio/interest-history", signed=True, data=params + ) def papi_fund_auto_collection(self, **params): """Fund collection for Portfolio Margin. @@ -9144,8 +9523,9 @@ def papi_fund_auto_collection(self, **params): :returns: API response """ - return self._request_papi_api('post', 'auto-collection', signed=True, data=params) - + return self._request_papi_api( + "post", "auto-collection", signed=True, data=params + ) def papi_fund_asset_collection(self, **params): """Transfers specific asset from Futures Account to Margin account. @@ -9158,8 +9538,9 @@ def papi_fund_asset_collection(self, **params): :returns: API response """ - return self._request_papi_api('post', 'asset-collection', signed=True, data=params) - + return self._request_papi_api( + "post", "asset-collection", signed=True, data=params + ) def papi_bnb_transfer(self, **params): """Transfer BNB in and out of UM. @@ -9172,8 +9553,7 @@ def papi_bnb_transfer(self, **params): :returns: API response """ - return self._request_papi_api('post', 'bnb-transfer', signed=True, data=params) - + return self._request_papi_api("post", "bnb-transfer", signed=True, data=params) def papi_get_um_income_history(self, **params): """Get UM Income History. @@ -9186,8 +9566,7 @@ def papi_get_um_income_history(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/income', signed=True, data=params) - + return self._request_papi_api("get", "um/income", signed=True, data=params) def papi_get_cm_income_history(self, **params): """Get CM Income History. @@ -9200,8 +9579,7 @@ def papi_get_cm_income_history(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/income', signed=True, data=params) - + return self._request_papi_api("get", "cm/income", signed=True, data=params) def papi_get_um_account(self, **params): """Get current UM account asset and position information. @@ -9214,7 +9592,7 @@ def papi_get_um_account(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/account', signed=True, data=params) + return self._request_papi_api("get", "um/account", signed=True, data=params) def papi_get_um_account_v2(self, **params): """Get current UM account asset and position information. @@ -9227,8 +9605,9 @@ def papi_get_um_account_v2(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/account', version=2, signed=True, data=params) - + return self._request_papi_api( + "get", "um/account", version=2, signed=True, data=params + ) def papi_get_cm_account(self, **params): """Get current CM account asset and position information. @@ -9241,8 +9620,7 @@ def papi_get_cm_account(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/account', signed=True, data=params) - + return self._request_papi_api("get", "cm/account", signed=True, data=params) def papi_get_um_account_config(self, **params): """Query UM Futures account configuration. @@ -9255,8 +9633,9 @@ def papi_get_um_account_config(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/accountConfig', signed=True, data=params) - + return self._request_papi_api( + "get", "um/accountConfig", signed=True, data=params + ) def papi_get_um_symbol_config(self, **params): """Get current UM account symbol configuration. @@ -9269,8 +9648,9 @@ def papi_get_um_symbol_config(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/symbolConfig', signed=True, data=params) - + return self._request_papi_api( + "get", "um/symbolConfig", signed=True, data=params + ) def papi_get_um_trade_asyn(self, **params): """Get download id for UM futures trade history. @@ -9283,8 +9663,7 @@ def papi_get_um_trade_asyn(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/trade/asyn', signed=True, data=params) - + return self._request_papi_api("get", "um/trade/asyn", signed=True, data=params) def papi_get_um_trade_asyn_id(self, **params): """Get UM futures trade download link by Id. @@ -9297,9 +9676,9 @@ def papi_get_um_trade_asyn_id(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/trade/asyn/id', signed=True, data=params) - - + return self._request_papi_api( + "get", "um/trade/asyn/id", signed=True, data=params + ) def papi_get_um_order_asyn(self, **params): """Get download id for UM futures order history. @@ -9312,8 +9691,7 @@ def papi_get_um_order_asyn(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/order/asyn', signed=True, data=params) - + return self._request_papi_api("get", "um/order/asyn", signed=True, data=params) def papi_get_um_order_asyn_id(self, **params): """Get UM futures order download link by Id. @@ -9326,8 +9704,9 @@ def papi_get_um_order_asyn_id(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/order/asyn/id', signed=True, data=params) - + return self._request_papi_api( + "get", "um/order/asyn/id", signed=True, data=params + ) def papi_get_um_income_asyn(self, **params): """Get download id for UM futures transaction history. @@ -9340,8 +9719,7 @@ def papi_get_um_income_asyn(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/income/asyn', signed=True, data=params) - + return self._request_papi_api("get", "um/income/asyn", signed=True, data=params) def papi_get_um_income_asyn_id(self, **params): """Get UM futures Transaction download link by Id. @@ -9354,7 +9732,9 @@ def papi_get_um_income_asyn_id(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/income/asyn/id', signed=True, data=params) + return self._request_papi_api( + "get", "um/income/asyn/id", signed=True, data=params + ) # Public papi endpoints @@ -9366,7 +9746,7 @@ def papi_ping(self, **params): :returns: API response """ - return self._request_papi_api('get', 'ping', signed=False, data=params) + return self._request_papi_api("get", "ping", signed=False, data=params) # Trade papi endpoints @@ -9378,10 +9758,9 @@ def papi_create_um_order(self, **params): :returns: API response """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return self._request_papi_api('post', 'um/order', signed=True, data=params) - + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return self._request_papi_api("post", "um/order", signed=True, data=params) def papi_create_um_conditional_order(self, **params): """Place new UM Conditional order. @@ -9391,10 +9770,11 @@ def papi_create_um_conditional_order(self, **params): :returns: API response """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return self._request_papi_api('post', 'um/conditional/order', signed=True, data=params) - + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return self._request_papi_api( + "post", "um/conditional/order", signed=True, data=params + ) def papi_create_cm_order(self, **params): """Place new CM order. @@ -9404,10 +9784,9 @@ def papi_create_cm_order(self, **params): :returns: API response """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return self._request_papi_api('post', 'cm/order', signed=True, data=params) - + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return self._request_papi_api("post", "cm/order", signed=True, data=params) def papi_create_cm_conditional_order(self, **params): """Place new CM Conditional order. @@ -9417,10 +9796,11 @@ def papi_create_cm_conditional_order(self, **params): :returns: API response """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return self._request_papi_api('post', 'cm/conditional/order', signed=True, data=params) - + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return self._request_papi_api( + "post", "cm/conditional/order", signed=True, data=params + ) def papi_create_margin_order(self, **params): """New Margin Order. @@ -9430,10 +9810,9 @@ def papi_create_margin_order(self, **params): :returns: API response """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return self._request_papi_api('post', 'margin/order', signed=True, data=params) - + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return self._request_papi_api("post", "margin/order", signed=True, data=params) def papi_margin_loan(self, **params): """Apply for a margin loan. @@ -9443,8 +9822,7 @@ def papi_margin_loan(self, **params): :returns: API response """ - return self._request_papi_api('post', 'marginLoan', signed=True, data=params) - + return self._request_papi_api("post", "marginLoan", signed=True, data=params) def papi_repay_loan(self, **params): """Repay for a margin loan. @@ -9454,8 +9832,7 @@ def papi_repay_loan(self, **params): :returns: API response """ - return self._request_papi_api('post', 'repayLoan', signed=True, data=params) - + return self._request_papi_api("post", "repayLoan", signed=True, data=params) def papi_margin_order_oco(self, **params): """Send in a new OCO for a margin account. @@ -9465,8 +9842,9 @@ def papi_margin_order_oco(self, **params): :returns: API response """ - return self._request_papi_api('post', 'margin/order/oco', signed=True, data=params) - + return self._request_papi_api( + "post", "margin/order/oco", signed=True, data=params + ) def papi_cancel_um_order(self, **params): """Cancel an active UM LIMIT order. @@ -9476,7 +9854,7 @@ def papi_cancel_um_order(self, **params): :returns: API response """ - return self._request_papi_api('delete', 'um/order', signed=True, data=params) + return self._request_papi_api("delete", "um/order", signed=True, data=params) def papi_cancel_um_all_open_orders(self, **params): """Cancel an active UM LIMIT order. @@ -9486,8 +9864,9 @@ def papi_cancel_um_all_open_orders(self, **params): :returns: API response """ - return self._request_papi_api('delete', 'um/allOpenOrders', signed=True, data=params) - + return self._request_papi_api( + "delete", "um/allOpenOrders", signed=True, data=params + ) def papi_cancel_um_conditional_order(self, **params): """Cancel UM Conditional Order. @@ -9497,8 +9876,9 @@ def papi_cancel_um_conditional_order(self, **params): :returns: API response """ - return self._request_papi_api('delete', 'um/conditional/order', signed=True, data=params) - + return self._request_papi_api( + "delete", "um/conditional/order", signed=True, data=params + ) def papi_cancel_um_conditional_all_open_orders(self, **params): """Cancel All UM Open Conditional Orders. @@ -9508,8 +9888,9 @@ def papi_cancel_um_conditional_all_open_orders(self, **params): :returns: API response """ - return self._request_papi_api('delete', 'um/conditional/allOpenOrders', signed=True, data=params) - + return self._request_papi_api( + "delete", "um/conditional/allOpenOrders", signed=True, data=params + ) def papi_cancel_cm_order(self, **params): """Cancel an active CM LIMIT order. @@ -9519,7 +9900,7 @@ def papi_cancel_cm_order(self, **params): :returns: API response """ - return self._request_papi_api('delete', 'cm/order', signed=True, data=params) + return self._request_papi_api("delete", "cm/order", signed=True, data=params) def papi_cancel_cm_all_open_orders(self, **params): """Cancel an active CM LIMIT order. @@ -9529,7 +9910,9 @@ def papi_cancel_cm_all_open_orders(self, **params): :returns: API response """ - return self._request_papi_api('delete', 'cm/allOpenOrders', signed=True, data=params) + return self._request_papi_api( + "delete", "cm/allOpenOrders", signed=True, data=params + ) def papi_cancel_cm_conditional_order(self, **params): """Cancel CM Conditional Order. @@ -9539,8 +9922,9 @@ def papi_cancel_cm_conditional_order(self, **params): :returns: API response """ - return self._request_papi_api('delete', 'cm/conditional/order', signed=True, data=params) - + return self._request_papi_api( + "delete", "cm/conditional/order", signed=True, data=params + ) def papi_cancel_cm_conditional_all_open_orders(self, **params): """Cancel All CM Open Conditional Orders. @@ -9550,8 +9934,9 @@ def papi_cancel_cm_conditional_all_open_orders(self, **params): :returns: API response """ - return self._request_papi_api('delete', 'cm/conditional/allOpenOrders', signed=True, data=params) - + return self._request_papi_api( + "delete", "cm/conditional/allOpenOrders", signed=True, data=params + ) def papi_cancel_margin_order(self, **params): """Cancel Margin Account Order. @@ -9561,8 +9946,9 @@ def papi_cancel_margin_order(self, **params): :returns: API response """ - return self._request_papi_api('delete', 'margin/order', signed=True, data=params) - + return self._request_papi_api( + "delete", "margin/order", signed=True, data=params + ) def papi_cancel_margin_order_list(self, **params): """Cancel Margin Account OCO Orders. @@ -9572,8 +9958,9 @@ def papi_cancel_margin_order_list(self, **params): :returns: API response """ - return self._request_papi_api('delete', 'margin/orderList', signed=True, data=params) - + return self._request_papi_api( + "delete", "margin/orderList", signed=True, data=params + ) def papi_cancel_margin_all_open_orders(self, **params): """Cancel Margin Account All Open Orders on a Symbol. @@ -9583,8 +9970,9 @@ def papi_cancel_margin_all_open_orders(self, **params): :returns: API response """ - return self._request_papi_api('delete', 'margin/allOpenOrders', signed=True, data=params) - + return self._request_papi_api( + "delete", "margin/allOpenOrders", signed=True, data=params + ) def papi_modify_um_order(self, **params): """Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue. @@ -9594,8 +9982,7 @@ def papi_modify_um_order(self, **params): :returns: API response """ - return self._request_papi_api('put', 'um/order', signed=True, data=params) - + return self._request_papi_api("put", "um/order", signed=True, data=params) def papi_modify_cm_order(self, **params): """Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue. @@ -9605,7 +9992,7 @@ def papi_modify_cm_order(self, **params): :returns: API response """ - return self._request_papi_api('put', 'cm/order', signed=True, data=params) + return self._request_papi_api("put", "cm/order", signed=True, data=params) def papi_get_um_order(self, **params): """Check an UM order's status. @@ -9615,8 +10002,7 @@ def papi_get_um_order(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/order', signed=True, data=params) - + return self._request_papi_api("get", "um/order", signed=True, data=params) def papi_get_um_all_orders(self, **params): """Get all account UM orders; active, canceled, or filled. @@ -9626,8 +10012,7 @@ def papi_get_um_all_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/allOrders', signed=True, data=params) - + return self._request_papi_api("get", "um/allOrders", signed=True, data=params) def papi_get_um_open_order(self, **params): """Query current UM open order. @@ -9637,8 +10022,7 @@ def papi_get_um_open_order(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/openOrder', signed=True, data=params) - + return self._request_papi_api("get", "um/openOrder", signed=True, data=params) def papi_get_um_open_orders(self, **params): """Get all open orders on a symbol. @@ -9648,8 +10032,7 @@ def papi_get_um_open_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/openOrders', signed=True, data=params) - + return self._request_papi_api("get", "um/openOrders", signed=True, data=params) def papi_get_um_conditional_all_orders(self, **params): """Query All UM Conditional Orders. @@ -9659,8 +10042,9 @@ def papi_get_um_conditional_all_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/conditional/allOrders', signed=True, data=params) - + return self._request_papi_api( + "get", "um/conditional/allOrders", signed=True, data=params + ) def papi_get_um_conditional_open_orders(self, **params): """Get all open conditional orders on a symbol. @@ -9670,8 +10054,9 @@ def papi_get_um_conditional_open_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/conditional/openOrders', signed=True, data=params) - + return self._request_papi_api( + "get", "um/conditional/openOrders", signed=True, data=params + ) def papi_get_um_conditional_open_order(self, **params): """Query Current UM Open Conditional Order. @@ -9681,8 +10066,9 @@ def papi_get_um_conditional_open_order(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/conditional/openOrder', signed=True, data=params) - + return self._request_papi_api( + "get", "um/conditional/openOrder", signed=True, data=params + ) def papi_get_um_conditional_order_history(self, **params): """Get all open conditional orders on a symbol. @@ -9692,9 +10078,9 @@ def papi_get_um_conditional_order_history(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/conditional/orderHistory', signed=True, data=params) - - + return self._request_papi_api( + "get", "um/conditional/orderHistory", signed=True, data=params + ) def papi_get_cm_order(self, **params): """Check an CM order's status. @@ -9704,8 +10090,7 @@ def papi_get_cm_order(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/order', signed=True, data=params) - + return self._request_papi_api("get", "cm/order", signed=True, data=params) def papi_get_cm_all_orders(self, **params): """Get all account CM orders; active, canceled, or filled. @@ -9715,8 +10100,7 @@ def papi_get_cm_all_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/allOrders', signed=True, data=params) - + return self._request_papi_api("get", "cm/allOrders", signed=True, data=params) def papi_get_cm_open_order(self, **params): """Query current CM open order. @@ -9726,8 +10110,7 @@ def papi_get_cm_open_order(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/openOrder', signed=True, data=params) - + return self._request_papi_api("get", "cm/openOrder", signed=True, data=params) def papi_get_cm_open_orders(self, **params): """Get all open orders on a symbol. @@ -9737,8 +10120,7 @@ def papi_get_cm_open_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/openOrders', signed=True, data=params) - + return self._request_papi_api("get", "cm/openOrders", signed=True, data=params) def papi_get_cm_conditional_all_orders(self, **params): """Query All CM Conditional Orders. @@ -9748,8 +10130,9 @@ def papi_get_cm_conditional_all_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/conditional/allOrders', signed=True, data=params) - + return self._request_papi_api( + "get", "cm/conditional/allOrders", signed=True, data=params + ) def papi_get_cm_conditional_open_orders(self, **params): """Get all open conditional orders on a symbol. @@ -9759,8 +10142,9 @@ def papi_get_cm_conditional_open_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/conditional/openOrders', signed=True, data=params) - + return self._request_papi_api( + "get", "cm/conditional/openOrders", signed=True, data=params + ) def papi_get_cm_conditional_open_order(self, **params): """Query Current UM Open Conditional Order. @@ -9770,8 +10154,9 @@ def papi_get_cm_conditional_open_order(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/conditional/openOrder', signed=True, data=params) - + return self._request_papi_api( + "get", "cm/conditional/openOrder", signed=True, data=params + ) def papi_get_cm_conditional_order_history(self, **params): """Get all open conditional orders on a symbol. @@ -9781,8 +10166,9 @@ def papi_get_cm_conditional_order_history(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/conditional/orderHistory', signed=True, data=params) - + return self._request_papi_api( + "get", "cm/conditional/orderHistory", signed=True, data=params + ) def papi_get_um_force_orders(self, **params): """Query User's UM Force Orders. @@ -9792,8 +10178,7 @@ def papi_get_um_force_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/forceOrders', signed=True, data=params) - + return self._request_papi_api("get", "um/forceOrders", signed=True, data=params) def papi_get_cm_force_orders(self, **params): """Query User's CM Force Orders. @@ -9803,8 +10188,7 @@ def papi_get_cm_force_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/forceOrders', signed=True, data=params) - + return self._request_papi_api("get", "cm/forceOrders", signed=True, data=params) def papi_get_um_order_amendment(self, **params): """Get order modification history. @@ -9814,8 +10198,9 @@ def papi_get_um_order_amendment(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/orderAmendment', signed=True, data=params) - + return self._request_papi_api( + "get", "um/orderAmendment", signed=True, data=params + ) def papi_get_cm_order_amendment(self, **params): """Get order modification history. @@ -9825,8 +10210,9 @@ def papi_get_cm_order_amendment(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/orderAmendment', signed=True, data=params) - + return self._request_papi_api( + "get", "cm/orderAmendment", signed=True, data=params + ) def papi_get_margin_force_orders(self, **params): """Query user's margin force orders. @@ -9836,7 +10222,9 @@ def papi_get_margin_force_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/forceOrders', signed=True, data=params) + return self._request_papi_api( + "get", "margin/forceOrders", signed=True, data=params + ) def papi_get_um_user_trades(self, **params): """Get trades for a specific account and UM symbol. @@ -9846,8 +10234,7 @@ def papi_get_um_user_trades(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/userTrades', signed=True, data=params) - + return self._request_papi_api("get", "um/userTrades", signed=True, data=params) def papi_get_cm_user_trades(self, **params): """Get trades for a specific account and CM symbol. @@ -9857,8 +10244,7 @@ def papi_get_cm_user_trades(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/userTrades', signed=True, data=params) - + return self._request_papi_api("get", "cm/userTrades", signed=True, data=params) def papi_get_um_adl_quantile(self, **params): """Query UM Position ADL Quantile Estimation. @@ -9868,8 +10254,7 @@ def papi_get_um_adl_quantile(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/adlQuantile', signed=True, data=params) - + return self._request_papi_api("get", "um/adlQuantile", signed=True, data=params) def papi_get_cm_adl_quantile(self, **params): """Query CM Position ADL Quantile Estimation. @@ -9879,8 +10264,7 @@ def papi_get_cm_adl_quantile(self, **params): :returns: API response """ - return self._request_papi_api('get', 'cm/adlQuantile', signed=True, data=params) - + return self._request_papi_api("get", "cm/adlQuantile", signed=True, data=params) def papi_set_um_fee_burn(self, **params): """Change user's BNB Fee Discount for UM Futures (Fee Discount On or Fee Discount Off ) on EVERY symbol. @@ -9890,8 +10274,7 @@ def papi_set_um_fee_burn(self, **params): :returns: API response """ - return self._request_papi_api('post', 'um/feeBurn', signed=True, data=params) - + return self._request_papi_api("post", "um/feeBurn", signed=True, data=params) def papi_get_um_fee_burn(self, **params): """Get user's BNB Fee Discount for UM Futures (Fee Discount On or Fee Discount Off). @@ -9901,8 +10284,7 @@ def papi_get_um_fee_burn(self, **params): :returns: API response """ - return self._request_papi_api('get', 'um/feeBurn', signed=True, data=params) - + return self._request_papi_api("get", "um/feeBurn", signed=True, data=params) def papi_get_margin_order(self, **params): """Query Margin Account Order. @@ -9912,8 +10294,7 @@ def papi_get_margin_order(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/order', signed=True, data=params) - + return self._request_papi_api("get", "margin/order", signed=True, data=params) def papi_get_margin_open_orders(self, **params): """Query Current Margin Open Order. @@ -9923,8 +10304,9 @@ def papi_get_margin_open_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/openOrders', signed=True, data=params) - + return self._request_papi_api( + "get", "margin/openOrders", signed=True, data=params + ) def papi_get_margin_all_orders(self, **params): """Query All Margin Account Orders. @@ -9934,8 +10316,9 @@ def papi_get_margin_all_orders(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/allOrders', signed=True, data=params) - + return self._request_papi_api( + "get", "margin/allOrders", signed=True, data=params + ) def papi_get_margin_order_list(self, **params): """Retrieves a specific OCO based on provided optional parameters. @@ -9945,8 +10328,9 @@ def papi_get_margin_order_list(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/orderList', signed=True, data=params) - + return self._request_papi_api( + "get", "margin/orderList", signed=True, data=params + ) def papi_get_margin_all_order_list(self, **params): """Query all OCO for a specific margin account based on provided optional parameters. @@ -9956,8 +10340,9 @@ def papi_get_margin_all_order_list(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/allOrderList', signed=True, data=params) - + return self._request_papi_api( + "get", "margin/allOrderList", signed=True, data=params + ) def papi_get_margin_open_order_list(self, **params): """Query Margin Account's Open OCO. @@ -9967,8 +10352,9 @@ def papi_get_margin_open_order_list(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/openOrderList', signed=True, data=params) - + return self._request_papi_api( + "get", "margin/openOrderList", signed=True, data=params + ) def papi_get_margin_my_trades(self, **params): """Margin Account Trade List. @@ -9978,8 +10364,9 @@ def papi_get_margin_my_trades(self, **params): :returns: API response """ - return self._request_papi_api('get', 'margin/myTrades', signed=True, data=params) - + return self._request_papi_api( + "get", "margin/myTrades", signed=True, data=params + ) def papi_get_margin_repay_debt(self, **params): """Repay debt for a margin loan. @@ -9989,8 +10376,9 @@ def papi_get_margin_repay_debt(self, **params): :returns: API response """ - return self._request_papi_api('post', 'margin/repay-debt', signed=True, data=params) - + return self._request_papi_api( + "post", "margin/repay-debt", signed=True, data=params + ) def close_connection(self): if self.session: @@ -10001,38 +10389,65 @@ def __del__(self): class AsyncClient(BaseClient): - def __init__( - self, api_key: Optional[str] = None, api_secret: Optional[str] = None, - requests_params: Optional[Dict[str, Any]] = None, tld: str = 'com', + self, + api_key: Optional[str] = None, + api_secret: Optional[str] = None, + requests_params: Optional[Dict[str, Any]] = None, + tld: str = "com", base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT, - testnet: bool = False, loop=None, session_params: Optional[Dict[str, Any]] = None, - private_key: Optional[Union[str, Path]] = None, private_key_pass: Optional[str] = None, - https_proxy: Optional[str] = None + testnet: bool = False, + loop=None, + session_params: Optional[Dict[str, Any]] = None, + private_key: Optional[Union[str, Path]] = None, + private_key_pass: Optional[str] = None, + https_proxy: Optional[str] = None, ): self.https_proxy = https_proxy self.loop = loop or get_loop() self._session_params: Dict[str, Any] = session_params or {} - super().__init__(api_key, api_secret, requests_params, tld, base_endpoint, testnet, private_key, private_key_pass) + super().__init__( + api_key, + api_secret, + requests_params, + tld, + base_endpoint, + testnet, + private_key, + private_key_pass, + ) @classmethod async def create( - cls, api_key: Optional[str] = None, api_secret: Optional[str] = None, - requests_params: Optional[Dict[str, Any]] = None, tld: str = 'com', + cls, + api_key: Optional[str] = None, + api_secret: Optional[str] = None, + requests_params: Optional[Dict[str, Any]] = None, + tld: str = "com", base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT, - testnet: bool = False, loop=None, session_params: Optional[Dict[str, Any]] = None, - https_proxy: Optional[str] = None + testnet: bool = False, + loop=None, + session_params: Optional[Dict[str, Any]] = None, + https_proxy: Optional[str] = None, ): - - self = cls(api_key, api_secret, requests_params, tld, base_endpoint, testnet, loop, session_params) - self.https_proxy = https_proxy # move this to the constructor + self = cls( + api_key, + api_secret, + requests_params, + tld, + base_endpoint, + testnet, + loop, + session_params, + ) + self.https_proxy = https_proxy # move this to the constructor try: await self.ping() # calculate timestamp offset between local and binance server res = await self.get_server_time() - self.timestamp_offset = res['serverTime'] - int(time.time() * 1000) + self.timestamp_offset = res["serverTime"] - int(time.time() * 1000) return self except Exception: @@ -10042,11 +10457,8 @@ async def create( raise def _init_session(self) -> aiohttp.ClientSession: - session = aiohttp.ClientSession( - loop=self.loop, - headers=self._get_headers(), - **self._session_params + loop=self.loop, headers=self._get_headers(), **self._session_params ) return session @@ -10055,11 +10467,14 @@ async def close_connection(self): assert self.session await self.session.close() - async def _request(self, method, uri: str, signed: bool, force_params: bool = False, **kwargs): - + async def _request( + self, method, uri: str, signed: bool, force_params: bool = False, **kwargs + ): kwargs = self._get_request_kwargs(method, signed, force_params, **kwargs) - async with getattr(self.session, method)(uri, proxy=self.https_proxy, **kwargs) as response: + async with getattr(self.session, method)( + uri, proxy=self.https_proxy, **kwargs + ) as response: self.response = response return await self._handle_response(response) @@ -10068,36 +10483,51 @@ async def _handle_response(self, response: aiohttp.ClientResponse): Raises the appropriate exceptions when necessary; otherwise, returns the response. """ - if not str(response.status).startswith('2'): + if not str(response.status).startswith("2"): raise BinanceAPIException(response, response.status, await response.text()) try: return await response.json() except ValueError: txt = await response.text() - raise BinanceRequestException(f'Invalid Response: {txt}') - - async def _request_api(self, method, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs): + raise BinanceRequestException(f"Invalid Response: {txt}") + + async def _request_api( + self, + method, + path, + signed=False, + version=BaseClient.PUBLIC_API_VERSION, + **kwargs, + ): uri = self._create_api_uri(path, signed, version) return await self._request(method, uri, signed, **kwargs) - async def _request_futures_api(self, method, path, signed=False, version=1, **kwargs) -> Dict: + async def _request_futures_api( + self, method, path, signed=False, version=1, **kwargs + ) -> Dict: version = self._get_version(version, **kwargs) uri = self._create_futures_api_uri(path, version=version) return await self._request(method, uri, signed, False, **kwargs) - async def _request_futures_data_api(self, method, path, signed=False, **kwargs) -> Dict: + async def _request_futures_data_api( + self, method, path, signed=False, **kwargs + ) -> Dict: uri = self._create_futures_data_api_uri(path) return await self._request(method, uri, signed, True, **kwargs) - async def _request_futures_coin_api(self, method, path, signed=False, version=1, **kwargs) -> Dict: + async def _request_futures_coin_api( + self, method, path, signed=False, version=1, **kwargs + ) -> Dict: version = self._get_version(version, **kwargs) uri = self._create_futures_coin_api_url(path, version=version) return await self._request(method, uri, signed, False, **kwargs) - async def _request_futures_coin_data_api(self, method, path, signed=False, version=1, **kwargs) -> Dict: + async def _request_futures_coin_data_api( + self, method, path, signed=False, version=1, **kwargs + ) -> Dict: version = self._get_version(version, **kwargs) uri = self._create_futures_coin_data_api_url(path, version=version) @@ -10108,13 +10538,17 @@ async def _request_options_api(self, method, path, signed=False, **kwargs) -> Di return await self._request(method, uri, signed, True, **kwargs) - async def _request_margin_api(self, method, path, signed=False, version=1, **kwargs) -> Dict: + async def _request_margin_api( + self, method, path, signed=False, version=1, **kwargs + ) -> Dict: version = self._get_version(version, **kwargs) uri = self._create_margin_api_uri(path, version) return await self._request(method, uri, signed, **kwargs) - async def _request_papi_api(self, method, path, signed=False, version=1, **kwargs) -> Dict: + async def _request_papi_api( + self, method, path, signed=False, version=1, **kwargs + ) -> Dict: version = self._get_version(version, **kwargs) uri = self._create_papi_api_uri(path, version) @@ -10124,56 +10558,77 @@ async def _request_website(self, method, path, signed=False, **kwargs) -> Dict: uri = self._create_website_uri(path) return await self._request(method, uri, signed, **kwargs) - async def _get(self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs): - return await self._request_api('get', path, signed, version, **kwargs) + async def _get( + self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs + ): + return await self._request_api("get", path, signed, version, **kwargs) - async def _post(self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs) -> Dict: - return await self._request_api('post', path, signed, version, **kwargs) + async def _post( + self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs + ) -> Dict: + return await self._request_api("post", path, signed, version, **kwargs) - async def _put(self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs) -> Dict: - return await self._request_api('put', path, signed, version, **kwargs) + async def _put( + self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs + ) -> Dict: + return await self._request_api("put", path, signed, version, **kwargs) - async def _delete(self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs) -> Dict: - return await self._request_api('delete', path, signed, version, **kwargs) + async def _delete( + self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs + ) -> Dict: + return await self._request_api("delete", path, signed, version, **kwargs) # Exchange Endpoints async def get_products(self) -> Dict: - products = await self._request_website('get', 'bapi/asset/v2/public/asset-service/product/get-products?includeEtf=true') + products = await self._request_website( + "get", + "bapi/asset/v2/public/asset-service/product/get-products?includeEtf=true", + ) return products + get_products.__doc__ = Client.get_products.__doc__ async def get_exchange_info(self) -> Dict: - return await self._get('exchangeInfo', version=self.PRIVATE_API_VERSION) + return await self._get("exchangeInfo", version=self.PRIVATE_API_VERSION) + get_exchange_info.__doc__ = Client.get_exchange_info.__doc__ async def get_symbol_info(self, symbol) -> Optional[Dict]: res = await self.get_exchange_info() - for item in res['symbols']: - if item['symbol'] == symbol.upper(): + for item in res["symbols"]: + if item["symbol"] == symbol.upper(): return item return None + get_symbol_info.__doc__ = Client.get_symbol_info.__doc__ # General Endpoints async def ping(self) -> Dict: - return await self._get('ping', version=self.PRIVATE_API_VERSION) + return await self._get("ping", version=self.PRIVATE_API_VERSION) + ping.__doc__ = Client.ping.__doc__ async def get_server_time(self) -> Dict: - return await self._get('time', version=self.PRIVATE_API_VERSION) + return await self._get("time", version=self.PRIVATE_API_VERSION) + get_server_time.__doc__ = Client.get_server_time.__doc__ # Market Data Endpoints - async def get_all_tickers(self, symbol: Optional[str] = None) -> List[Dict[str, str]]: + async def get_all_tickers( + self, symbol: Optional[str] = None + ) -> List[Dict[str, str]]: params = {} if symbol: - params['symbol'] = symbol - return await self._get('ticker/price', version=self.PRIVATE_API_VERSION, data=params) + params["symbol"] = symbol + return await self._get( + "ticker/price", version=self.PRIVATE_API_VERSION, data=params + ) + get_all_tickers.__doc__ = Client.get_all_tickers.__doc__ async def get_orderbook_tickers(self, **params) -> Dict: @@ -10182,29 +10637,41 @@ async def get_orderbook_tickers(self, **params) -> Dict: data["symbol"] = params["symbol"] elif "symbols" in params: data["symbols"] = params["symbols"] - return await self._get('ticker/bookTicker', data=data, version=self.PRIVATE_API_VERSION) + return await self._get( + "ticker/bookTicker", data=data, version=self.PRIVATE_API_VERSION + ) + get_orderbook_tickers.__doc__ = Client.get_orderbook_tickers.__doc__ async def get_order_book(self, **params) -> Dict: - return await self._get('depth', data=params, version=self.PRIVATE_API_VERSION) + return await self._get("depth", data=params, version=self.PRIVATE_API_VERSION) + get_order_book.__doc__ = Client.get_order_book.__doc__ async def get_recent_trades(self, **params) -> Dict: - return await self._get('trades', data=params) + return await self._get("trades", data=params) + get_recent_trades.__doc__ = Client.get_recent_trades.__doc__ async def get_historical_trades(self, **params) -> Dict: - return await self._get('historicalTrades', data=params, version=self.PRIVATE_API_VERSION) + return await self._get( + "historicalTrades", data=params, version=self.PRIVATE_API_VERSION + ) + get_historical_trades.__doc__ = Client.get_historical_trades.__doc__ async def get_aggregate_trades(self, **params) -> Dict: - return await self._get('aggTrades', data=params, version=self.PRIVATE_API_VERSION) + return await self._get( + "aggTrades", data=params, version=self.PRIVATE_API_VERSION + ) + get_aggregate_trades.__doc__ = Client.get_aggregate_trades.__doc__ async def aggregate_trade_iter(self, symbol, start_str=None, last_id=None): if start_str is not None and last_id is not None: raise ValueError( - 'start_time and last_id may not be simultaneously specified.') + "start_time and last_id may not be simultaneously specified." + ) # If there's no last_id, get one. if last_id is None: @@ -10223,9 +10690,8 @@ async def aggregate_trade_iter(self, symbol, start_str=None, last_id=None): while True: end_ts = start_ts + (60 * 60 * 1000) trades = await self.get_aggregate_trades( - symbol=symbol, - startTime=start_ts, - endTime=end_ts) + symbol=symbol, startTime=start_ts, endTime=end_ts + ) if len(trades) > 0: break # If we reach present moment and find no trades then there is @@ -10253,15 +10719,19 @@ async def aggregate_trade_iter(self, symbol, start_str=None, last_id=None): for t in trades: yield t last_id = trades[-1][self.AGG_ID] + aggregate_trade_iter.__doc__ = Client.aggregate_trade_iter.__doc__ async def get_klines(self, **params) -> Dict: - return await self._get('klines', data=params, version=self.PRIVATE_API_VERSION) + return await self._get("klines", data=params, version=self.PRIVATE_API_VERSION) + get_klines.__doc__ = Client.get_klines.__doc__ - async def _klines(self, klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, **params) -> Dict: - if 'endTime' in params and not params['endTime']: - del params['endTime'] + async def _klines( + self, klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, **params + ) -> Dict: + if "endTime" in params and not params["endTime"]: + del params["endTime"] if HistoricalKlinesType.SPOT == klines_type: return await self.get_klines(**params) elif HistoricalKlinesType.FUTURES == klines_type: @@ -10270,29 +10740,56 @@ async def _klines(self, klines_type: HistoricalKlinesType = HistoricalKlinesType return await self.futures_coin_klines(**params) else: raise NotImplementedException(klines_type) + _klines.__doc__ = Client._klines.__doc__ - async def _get_earliest_valid_timestamp(self, symbol, interval, - klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT): + async def _get_earliest_valid_timestamp( + self, + symbol, + interval, + klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, + ): kline = await self._klines( klines_type=klines_type, symbol=symbol, interval=interval, limit=1, startTime=0, - endTime=int(time.time() * 1000) + endTime=int(time.time() * 1000), ) return kline[0][0] + _get_earliest_valid_timestamp.__doc__ = Client._get_earliest_valid_timestamp.__doc__ - async def get_historical_klines(self, symbol, interval, start_str=None, end_str=None, limit=None, - klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT): - return await self._historical_klines(symbol, interval, start_str, end_str=end_str, limit=limit, klines_type=klines_type) - get_historical_klines.__doc__ = Client.get_historical_klines.__doc__ + async def get_historical_klines( + self, + symbol, + interval, + start_str=None, + end_str=None, + limit=None, + klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, + ): + return await self._historical_klines( + symbol, + interval, + start_str, + end_str=end_str, + limit=limit, + klines_type=klines_type, + ) - async def _historical_klines(self, symbol, interval, start_str=None, end_str=None, limit=None, - klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT): + get_historical_klines.__doc__ = Client.get_historical_klines.__doc__ + async def _historical_klines( + self, + symbol, + interval, + start_str=None, + end_str=None, + limit=None, + klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, + ): initial_limit_set = True if limit is None: limit = 1000 @@ -10307,7 +10804,9 @@ async def _historical_klines(self, symbol, interval, start_str=None, end_str=Non # establish first available start timestamp start_ts = convert_ts_str(start_str) if start_ts is not None: - first_valid_ts = await self._get_earliest_valid_timestamp(symbol, interval, klines_type) + first_valid_ts = await self._get_earliest_valid_timestamp( + symbol, interval, klines_type + ) start_ts = max(start_ts, first_valid_ts) # if an end time was passed convert it @@ -10324,7 +10823,7 @@ async def _historical_klines(self, symbol, interval, start_str=None, end_str=Non interval=interval, limit=limit, startTime=start_ts, - endTime=end_ts + endTime=end_ts, ) # append this loops data to our output data @@ -10356,18 +10855,40 @@ async def _historical_klines(self, symbol, interval, start_str=None, end_str=Non await asyncio.sleep(1) return output_data + _historical_klines.__doc__ = Client._historical_klines.__doc__ - async def get_historical_klines_generator(self, symbol, interval, start_str=None, end_str=None, limit=1000, - klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT): + async def get_historical_klines_generator( + self, + symbol, + interval, + start_str=None, + end_str=None, + limit=1000, + klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, + ): return self._historical_klines_generator( - symbol, interval, start_str, end_str=end_str, limit=limit, klines_type=klines_type + symbol, + interval, + start_str, + end_str=end_str, + limit=limit, + klines_type=klines_type, ) - get_historical_klines_generator.__doc__ = Client.get_historical_klines_generator.__doc__ - - async def _historical_klines_generator(self, symbol, interval, start_str=None, end_str=None, limit=1000, - klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT): + get_historical_klines_generator.__doc__ = ( + Client.get_historical_klines_generator.__doc__ + ) + + async def _historical_klines_generator( + self, + symbol, + interval, + start_str=None, + end_str=None, + limit=1000, + klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, + ): # convert interval to useful value in seconds timeframe = interval_to_milliseconds(interval) @@ -10376,7 +10897,9 @@ async def _historical_klines_generator(self, symbol, interval, start_str=None, e # establish first available start timestamp if start_ts is not None: - first_valid_ts = await self._get_earliest_valid_timestamp(symbol, interval, klines_type) + first_valid_ts = await self._get_earliest_valid_timestamp( + symbol, interval, klines_type + ) start_ts = max(start_ts, first_valid_ts) # if an end time was passed convert it @@ -10393,7 +10916,7 @@ async def _historical_klines_generator(self, symbol, interval, start_str=None, e interval=interval, limit=limit, startTime=start_ts, - endTime=end_ts + endTime=end_ts, ) # yield data @@ -10418,893 +10941,1327 @@ async def _historical_klines_generator(self, symbol, interval, start_str=None, e idx += 1 if idx % 3 == 0: await asyncio.sleep(1) + _historical_klines_generator.__doc__ = Client._historical_klines_generator.__doc__ async def get_avg_price(self, **params): - return await self._get('avgPrice', data=params, version=self.PRIVATE_API_VERSION) + return await self._get( + "avgPrice", data=params, version=self.PRIVATE_API_VERSION + ) + get_avg_price.__doc__ = Client.get_avg_price.__doc__ async def get_ticker(self, **params): - return await self._get('ticker/24hr', data=params, version=self.PRIVATE_API_VERSION) + return await self._get( + "ticker/24hr", data=params, version=self.PRIVATE_API_VERSION + ) + get_ticker.__doc__ = Client.get_ticker.__doc__ async def get_symbol_ticker(self, **params): - return await self._get('ticker/price', data=params, version=self.PRIVATE_API_VERSION) + return await self._get( + "ticker/price", data=params, version=self.PRIVATE_API_VERSION + ) + get_symbol_ticker.__doc__ = Client.get_symbol_ticker.__doc__ async def get_symbol_ticker_window(self, **params): - return await self._get('ticker', data=params, version=self.PRIVATE_API_VERSION) + return await self._get("ticker", data=params, version=self.PRIVATE_API_VERSION) + get_symbol_ticker_window.__doc__ = Client.get_symbol_ticker_window.__doc__ async def get_orderbook_ticker(self, **params): - return await self._get('ticker/bookTicker', data=params, version=self.PRIVATE_API_VERSION) + return await self._get( + "ticker/bookTicker", data=params, version=self.PRIVATE_API_VERSION + ) + get_orderbook_ticker.__doc__ = Client.get_orderbook_ticker.__doc__ # Account Endpoints async def create_order(self, **params): - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.SPOT_ORDER_PREFIX + self.uuid22() - return await self._post('order', True, data=params) + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.SPOT_ORDER_PREFIX + self.uuid22() + return await self._post("order", True, data=params) + create_order.__doc__ = Client.create_order.__doc__ async def order_limit(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params): - params.update({ - 'type': self.ORDER_TYPE_LIMIT, - 'timeInForce': timeInForce - }) + params.update({"type": self.ORDER_TYPE_LIMIT, "timeInForce": timeInForce}) return await self.create_order(**params) + order_limit.__doc__ = Client.order_limit.__doc__ async def order_limit_buy(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params): - params.update({ - 'side': self.SIDE_BUY, - }) + params.update( + { + "side": self.SIDE_BUY, + } + ) return await self.order_limit(timeInForce=timeInForce, **params) + order_limit_buy.__doc__ = Client.order_limit_buy.__doc__ - async def order_limit_sell(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params): - params.update({ - 'side': self.SIDE_SELL - }) + async def order_limit_sell( + self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params + ): + params.update({"side": self.SIDE_SELL}) return await self.order_limit(timeInForce=timeInForce, **params) + order_limit_sell.__doc__ = Client.order_limit_sell.__doc__ async def order_market(self, **params): - params.update({ - 'type': self.ORDER_TYPE_MARKET - }) + params.update({"type": self.ORDER_TYPE_MARKET}) return await self.create_order(**params) + order_market.__doc__ = Client.order_market.__doc__ async def order_market_buy(self, **params): - params.update({ - 'side': self.SIDE_BUY - }) + params.update({"side": self.SIDE_BUY}) return await self.order_market(**params) + order_market_buy.__doc__ = Client.order_market_buy.__doc__ async def order_market_sell(self, **params): - params.update({ - 'side': self.SIDE_SELL - }) + params.update({"side": self.SIDE_SELL}) return await self.order_market(**params) + order_market_sell.__doc__ = Client.order_market_sell.__doc__ async def create_oco_order(self, **params): - return await self._post('order/oco', True, data=params) + return await self._post("order/oco", True, data=params) + create_oco_order.__doc__ = Client.create_oco_order.__doc__ async def order_oco_buy(self, **params): - params.update({ - 'side': self.SIDE_BUY - }) + params.update({"side": self.SIDE_BUY}) return await self.create_oco_order(**params) + order_oco_buy.__doc__ = Client.order_oco_buy.__doc__ async def order_oco_sell(self, **params): - params.update({ - 'side': self.SIDE_SELL - }) + params.update({"side": self.SIDE_SELL}) return await self.create_oco_order(**params) + order_oco_sell.__doc__ = Client.order_oco_sell.__doc__ async def create_test_order(self, **params): - return await self._post('order/test', True, data=params) + return await self._post("order/test", True, data=params) + create_test_order.__doc__ = Client.create_test_order.__doc__ async def get_order(self, **params): - return await self._get('order', True, data=params) + return await self._get("order", True, data=params) + get_order.__doc__ = Client.get_order.__doc__ async def get_all_orders(self, **params): - return await self._get('allOrders', True, data=params) + return await self._get("allOrders", True, data=params) + get_all_orders.__doc__ = Client.get_all_orders.__doc__ async def cancel_order(self, **params): - return await self._delete('order', True, data=params) + return await self._delete("order", True, data=params) + cancel_order.__doc__ = Client.cancel_order.__doc__ async def get_open_orders(self, **params): - return await self._get('openOrders', True, data=params) + return await self._get("openOrders", True, data=params) + get_open_orders.__doc__ = Client.get_open_orders.__doc__ async def get_open_oco_orders(self, **params): - return await self._get('openOrderList', True, data=params) + return await self._get("openOrderList", True, data=params) + get_open_oco_orders.__doc__ = Client.get_open_oco_orders.__doc__ # User Stream Endpoints async def get_account(self, **params): - return await self._get('account', True, data=params) + return await self._get("account", True, data=params) + get_account.__doc__ = Client.get_account.__doc__ async def get_asset_balance(self, asset, **params): res = await self.get_account(**params) # find asset balance in list of balances if "balances" in res: - for bal in res['balances']: - if bal['asset'].lower() == asset.lower(): + for bal in res["balances"]: + if bal["asset"].lower() == asset.lower(): return bal return None + get_asset_balance.__doc__ = Client.get_asset_balance.__doc__ async def get_my_trades(self, **params): - return await self._get('myTrades', True, data=params) + return await self._get("myTrades", True, data=params) + get_my_trades.__doc__ = Client.get_my_trades.__doc__ async def get_current_order_count(self): - return await self._get('rateLimit/order', True) + return await self._get("rateLimit/order", True) + get_current_order_count.__doc__ = Client.get_current_order_count.__doc__ async def get_prevented_matches(self, **params): - return await self._get('myPreventedMatches', True, data=params) + return await self._get("myPreventedMatches", True, data=params) + get_prevented_matches.__doc__ = Client.get_prevented_matches.__doc__ async def get_allocations(self, **params): - return await self._get('myAllocations', True, data=params) + return await self._get("myAllocations", True, data=params) + get_allocations.__doc__ = Client.get_allocations.__doc__ async def get_system_status(self): - return await self._request_margin_api('get', 'system/status') + return await self._request_margin_api("get", "system/status") + get_system_status.__doc__ = Client.get_system_status.__doc__ async def get_account_status(self, **params): - return await self._request_margin_api('get', 'account/status', True, data=params) + return await self._request_margin_api( + "get", "account/status", True, data=params + ) + get_account_status.__doc__ = Client.get_account_status.__doc__ async def get_account_api_trading_status(self, **params): - return await self._request_margin_api('get', 'account/apiTradingStatus', True, data=params) - get_account_api_trading_status.__doc__ = Client.get_account_api_trading_status.__doc__ + return await self._request_margin_api( + "get", "account/apiTradingStatus", True, data=params + ) + + get_account_api_trading_status.__doc__ = ( + Client.get_account_api_trading_status.__doc__ + ) async def get_account_api_permissions(self, **params): - return await self._request_margin_api('get', 'account/apiRestrictions', True, data=params) + return await self._request_margin_api( + "get", "account/apiRestrictions", True, data=params + ) + get_account_api_permissions.__doc__ = Client.get_account_api_permissions.__doc__ async def get_dust_assets(self, **params): - return await self._request_margin_api('post', 'asset/dust-btc', True, data=params) + return await self._request_margin_api( + "post", "asset/dust-btc", True, data=params + ) + get_dust_assets.__doc__ = Client.get_dust_assets.__doc__ async def get_dust_log(self, **params): - return await self._request_margin_api('get', 'asset/dribblet', True, data=params) + return await self._request_margin_api( + "get", "asset/dribblet", True, data=params + ) + get_dust_log.__doc__ = Client.get_dust_log.__doc__ async def transfer_dust(self, **params): - return await self._request_margin_api('post', 'asset/dust', True, data=params) + return await self._request_margin_api("post", "asset/dust", True, data=params) + transfer_dust.__doc__ = Client.transfer_dust.__doc__ async def get_asset_dividend_history(self, **params): - return await self._request_margin_api('get', 'asset/assetDividend', True, data=params) + return await self._request_margin_api( + "get", "asset/assetDividend", True, data=params + ) + get_asset_dividend_history.__doc__ = Client.get_asset_dividend_history.__doc__ async def make_universal_transfer(self, **params): - return await self._request_margin_api('post', 'asset/transfer', signed=True, data=params) + return await self._request_margin_api( + "post", "asset/transfer", signed=True, data=params + ) + make_universal_transfer.__doc__ = Client.make_universal_transfer.__doc__ async def query_universal_transfer_history(self, **params): - return await self._request_margin_api('get', 'asset/transfer', signed=True, data=params) - query_universal_transfer_history.__doc__ = Client.query_universal_transfer_history.__doc__ + return await self._request_margin_api( + "get", "asset/transfer", signed=True, data=params + ) + + query_universal_transfer_history.__doc__ = ( + Client.query_universal_transfer_history.__doc__ + ) async def get_trade_fee(self, **params): - if self.tld == 'us': - endpoint = 'asset/query/trading-fee' + if self.tld == "us": + endpoint = "asset/query/trading-fee" else: - endpoint = 'asset/tradeFee' - return await self._request_margin_api('get', endpoint, True, data=params) + endpoint = "asset/tradeFee" + return await self._request_margin_api("get", endpoint, True, data=params) + get_trade_fee.__doc__ = Client.get_trade_fee.__doc__ async def get_asset_details(self, **params): - return await self._request_margin_api('get', 'asset/assetDetail', True, data=params) + return await self._request_margin_api( + "get", "asset/assetDetail", True, data=params + ) + get_asset_details.__doc__ = Client.get_asset_details.__doc__ async def get_spot_delist_schedule(self, **params): - return await self._request_margin_api('get', '/spot/delist-schedule', signed=True, data=params) + return await self._request_margin_api( + "get", "/spot/delist-schedule", signed=True, data=params + ) # Withdraw Endpoints async def withdraw(self, **params): # force a name for the withdrawal if one not set - if 'coin' in params and 'name' not in params: - params['name'] = params['coin'] - return await self._request_margin_api('post', 'capital/withdraw/apply', True, data=params) + if "coin" in params and "name" not in params: + params["name"] = params["coin"] + return await self._request_margin_api( + "post", "capital/withdraw/apply", True, data=params + ) + withdraw.__doc__ = Client.withdraw.__doc__ async def get_deposit_history(self, **params): - return await self._request_margin_api('get', 'capital/deposit/hisrec', True, data=params) + return await self._request_margin_api( + "get", "capital/deposit/hisrec", True, data=params + ) + get_deposit_history.__doc__ = Client.get_deposit_history.__doc__ async def get_withdraw_history(self, **params): - return await self._request_margin_api('get', 'capital/withdraw/history', True, data=params) + return await self._request_margin_api( + "get", "capital/withdraw/history", True, data=params + ) + get_withdraw_history.__doc__ = Client.get_withdraw_history.__doc__ async def get_withdraw_history_id(self, withdraw_id, **params): result = await self.get_withdraw_history(**params) for entry in result: - if 'id' in entry and entry['id'] == withdraw_id: + if "id" in entry and entry["id"] == withdraw_id: return entry raise Exception("There is no entry with withdraw id", result) + get_withdraw_history_id.__doc__ = Client.get_withdraw_history_id.__doc__ - async def get_deposit_address(self, coin: str, network: Optional[str] = None, **params): - params['coin'] = coin + async def get_deposit_address( + self, coin: str, network: Optional[str] = None, **params + ): + params["coin"] = coin if network: - params['network'] = network - return await self._request_margin_api('get', 'capital/deposit/address', True, data=params) + params["network"] = network + return await self._request_margin_api( + "get", "capital/deposit/address", True, data=params + ) + get_deposit_address.__doc__ = Client.get_deposit_address.__doc__ # User Stream Endpoints async def stream_get_listen_key(self): - res = await self._post('userDataStream', False, data={}) - return res['listenKey'] + res = await self._post("userDataStream", False, data={}) + return res["listenKey"] + stream_get_listen_key.__doc__ = Client.stream_get_listen_key.__doc__ async def stream_keepalive(self, listenKey): - params = { - 'listenKey': listenKey - } - return await self._put('userDataStream', False, data=params) + params = {"listenKey": listenKey} + return await self._put("userDataStream", False, data=params) + stream_keepalive.__doc__ = Client.stream_keepalive.__doc__ async def stream_close(self, listenKey): - params = { - 'listenKey': listenKey - } - return await self._delete('userDataStream', False, data=params) + params = {"listenKey": listenKey} + return await self._delete("userDataStream", False, data=params) + stream_close.__doc__ = Client.stream_close.__doc__ # Margin Trading Endpoints async def get_margin_account(self, **params): - return await self._request_margin_api('get', 'margin/account', True, data=params) + return await self._request_margin_api( + "get", "margin/account", True, data=params + ) + get_margin_account.__doc__ = Client.get_margin_account.__doc__ async def get_isolated_margin_account(self, **params): - return await self._request_margin_api('get', 'margin/isolated/account', True, data=params) + return await self._request_margin_api( + "get", "margin/isolated/account", True, data=params + ) + get_isolated_margin_account.__doc__ = Client.get_isolated_margin_account.__doc__ async def enable_isolated_margin_account(self, **params): - return await self._request_margin_api('post', 'margin/isolated/account', True, data=params) - enable_isolated_margin_account.__doc__ = Client.enable_isolated_margin_account.__doc__ + return await self._request_margin_api( + "post", "margin/isolated/account", True, data=params + ) + + enable_isolated_margin_account.__doc__ = ( + Client.enable_isolated_margin_account.__doc__ + ) async def disable_isolated_margin_account(self, **params): - return await self._request_margin_api('delete', 'margin/isolated/account', True, data=params) - disable_isolated_margin_account.__doc__ = Client.disable_isolated_margin_account.__doc__ + return await self._request_margin_api( + "delete", "margin/isolated/account", True, data=params + ) + + disable_isolated_margin_account.__doc__ = ( + Client.disable_isolated_margin_account.__doc__ + ) async def get_enabled_isolated_margin_account_limit(self, **params): - return await self._request_margin_api('get', 'margin/isolated/accountLimit', True, data=params) - get_enabled_isolated_margin_account_limit.__doc__ = Client.get_enabled_isolated_margin_account_limit.__doc__ + return await self._request_margin_api( + "get", "margin/isolated/accountLimit", True, data=params + ) + + get_enabled_isolated_margin_account_limit.__doc__ = ( + Client.get_enabled_isolated_margin_account_limit.__doc__ + ) async def get_margin_dustlog(self, **params): - return await self._request_margin_api('get', 'margin/dribblet', True, data=params) + return await self._request_margin_api( + "get", "margin/dribblet", True, data=params + ) + get_margin_dustlog.__doc__ = Client.get_margin_dustlog.__doc__ async def get_margin_dust_assets(self, **params): - return await self._request_margin_api('get', 'margin/dust', True, data=params) + return await self._request_margin_api("get", "margin/dust", True, data=params) + get_margin_dust_assets.__doc__ = Client.get_margin_dust_assets.__doc__ async def transfer_margin_dust(self, **params): - return await self._request_margin_api('post', 'margin/dust', True, data=params) + return await self._request_margin_api("post", "margin/dust", True, data=params) + transfer_margin_dust.__doc__ = Client.transfer_margin_dust.__doc__ async def get_cross_margin_collateral_ratio(self, **params): - return await self._request_margin_api('get', 'margin/crossMarginCollateralRatio', True, data=params) - get_cross_margin_collateral_ratio.__doc__ = Client.get_cross_margin_collateral_ratio.__doc__ + return await self._request_margin_api( + "get", "margin/crossMarginCollateralRatio", True, data=params + ) + + get_cross_margin_collateral_ratio.__doc__ = ( + Client.get_cross_margin_collateral_ratio.__doc__ + ) async def get_small_liability_exchange_assets(self, **params): - return await self._request_margin_api('get', 'margin/exchange-small-liability', True, data=params) - get_small_liability_exchange_assets.__doc__ = Client.get_small_liability_exchange_assets.__doc__ + return await self._request_margin_api( + "get", "margin/exchange-small-liability", True, data=params + ) + + get_small_liability_exchange_assets.__doc__ = ( + Client.get_small_liability_exchange_assets.__doc__ + ) async def exchange_small_liability_assets(self, **params): - return await self._request_margin_api('post', 'margin/exchange-small-liability', True, data=params) - exchange_small_liability_assets.__doc__ = Client.exchange_small_liability_assets.__doc__ + return await self._request_margin_api( + "post", "margin/exchange-small-liability", True, data=params + ) + + exchange_small_liability_assets.__doc__ = ( + Client.exchange_small_liability_assets.__doc__ + ) async def get_small_liability_exchange_history(self, **params): - return await self._request_margin_api('get', 'margin/exchange-small-liability-history', True, data=params) - get_small_liability_exchange_history.__doc__ = Client.get_small_liability_exchange_history.__doc__ + return await self._request_margin_api( + "get", "margin/exchange-small-liability-history", True, data=params + ) + + get_small_liability_exchange_history.__doc__ = ( + Client.get_small_liability_exchange_history.__doc__ + ) async def get_future_hourly_interest_rate(self, **params): - return await self._request_margin_api('get', 'margin/next-hourly-interest-rate', True, data=params) - get_future_hourly_interest_rate.__doc__ = Client.get_future_hourly_interest_rate.__doc__ + return await self._request_margin_api( + "get", "margin/next-hourly-interest-rate", True, data=params + ) + + get_future_hourly_interest_rate.__doc__ = ( + Client.get_future_hourly_interest_rate.__doc__ + ) async def get_margin_capital_flow(self, **params): - return await self._request_margin_api('get', 'margin/capital-flow', True, data=params) + return await self._request_margin_api( + "get", "margin/capital-flow", True, data=params + ) + get_margin_capital_flow.__doc__ = Client.get_margin_capital_flow.__doc__ async def get_margin_delist_schedule(self, **params): - return await self._request_margin_api('get', 'margin/delist-schedule', True, data=params) + return await self._request_margin_api( + "get", "margin/delist-schedule", True, data=params + ) + get_margin_delist_schedule.__doc__ = Client.get_margin_delist_schedule.__doc__ async def get_margin_asset(self, **params): - return await self._request_margin_api('get', 'margin/asset', data=params) + return await self._request_margin_api("get", "margin/asset", data=params) + get_margin_asset.__doc__ = Client.get_margin_asset.__doc__ async def get_margin_symbol(self, **params): - return await self._request_margin_api('get', 'margin/pair', data=params) + return await self._request_margin_api("get", "margin/pair", data=params) + get_margin_symbol.__doc__ = Client.get_margin_symbol.__doc__ async def get_margin_all_assets(self, **params): - return await self._request_margin_api('get', 'margin/allAssets', data=params) + return await self._request_margin_api("get", "margin/allAssets", data=params) + get_margin_all_assets.__doc__ = Client.get_margin_all_assets.__doc__ async def get_margin_all_pairs(self, **params): - return await self._request_margin_api('get', 'margin/allPairs', data=params) + return await self._request_margin_api("get", "margin/allPairs", data=params) + get_margin_all_pairs.__doc__ = Client.get_margin_all_pairs.__doc__ async def create_isolated_margin_account(self, **params): - return await self._request_margin_api('post', 'margin/isolated/create', signed=True, data=params) - create_isolated_margin_account.__doc__ = Client.create_isolated_margin_account.__doc__ + return await self._request_margin_api( + "post", "margin/isolated/create", signed=True, data=params + ) + + create_isolated_margin_account.__doc__ = ( + Client.create_isolated_margin_account.__doc__ + ) async def get_isolated_margin_symbol(self, **params): - return await self._request_margin_api('get', 'margin/isolated/pair', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/isolated/pair", signed=True, data=params + ) + get_isolated_margin_symbol.__doc__ = Client.get_isolated_margin_symbol.__doc__ async def get_all_isolated_margin_symbols(self, **params): - return await self._request_margin_api('get', 'margin/isolated/allPairs', signed=True, data=params) - get_all_isolated_margin_symbols.__doc__ = Client.get_all_isolated_margin_symbols.__doc__ + return await self._request_margin_api( + "get", "margin/isolated/allPairs", signed=True, data=params + ) + + get_all_isolated_margin_symbols.__doc__ = ( + Client.get_all_isolated_margin_symbols.__doc__ + ) async def get_isolated_margin_fee_data(self, **params): - return await self._request_margin_api('get', 'margin/isolatedMarginData', True, data=params) + return await self._request_margin_api( + "get", "margin/isolatedMarginData", True, data=params + ) + get_isolated_margin_fee_data.__doc__ = Client.get_isolated_margin_fee_data.__doc__ async def get_isolated_margin_tier_data(self, **params): - return await self._request_margin_api('get', 'margin/isolatedMarginTier', True, data=params) + return await self._request_margin_api( + "get", "margin/isolatedMarginTier", True, data=params + ) + get_isolated_margin_tier_data.__doc__ = Client.get_isolated_margin_tier_data.__doc__ async def margin_manual_liquidation(self, **params): - return await self._request_margin_api('get', 'margin/manual-liquidation', True, data=params) + return await self._request_margin_api( + "get", "margin/manual-liquidation", True, data=params + ) + margin_manual_liquidation.__doc__ = Client.margin_manual_liquidation.__doc__ async def toggle_bnb_burn_spot_margin(self, **params): - return await self._request_margin_api('post', 'bnbBurn', signed=True, data=params) + return await self._request_margin_api( + "post", "bnbBurn", signed=True, data=params + ) + toggle_bnb_burn_spot_margin.__doc__ = Client.toggle_bnb_burn_spot_margin.__doc__ async def get_bnb_burn_spot_margin(self, **params): - return await self._request_margin_api('get', 'bnbBurn', signed=True, data=params) + return await self._request_margin_api( + "get", "bnbBurn", signed=True, data=params + ) + get_bnb_burn_spot_margin.__doc__ = Client.get_bnb_burn_spot_margin.__doc__ async def get_margin_price_index(self, **params): - return await self._request_margin_api('get', 'margin/priceIndex', data=params) + return await self._request_margin_api("get", "margin/priceIndex", data=params) + get_margin_price_index.__doc__ = Client.get_margin_price_index.__doc__ async def transfer_margin_to_spot(self, **params): - params['type'] = 2 - return await self._request_margin_api('post', 'margin/transfer', signed=True, data=params) + params["type"] = 2 + return await self._request_margin_api( + "post", "margin/transfer", signed=True, data=params + ) + transfer_margin_to_spot.__doc__ = Client.transfer_margin_to_spot.__doc__ async def transfer_spot_to_margin(self, **params): - params['type'] = 1 - return await self._request_margin_api('post', 'margin/transfer', signed=True, data=params) + params["type"] = 1 + return await self._request_margin_api( + "post", "margin/transfer", signed=True, data=params + ) + transfer_spot_to_margin.__doc__ = Client.transfer_spot_to_margin.__doc__ async def transfer_isolated_margin_to_spot(self, **params): - params['transFrom'] = "ISOLATED_MARGIN" - params['transTo'] = "SPOT" - return await self._request_margin_api('post', 'margin/isolated/transfer', signed=True, data=params) - transfer_isolated_margin_to_spot.__doc__ = Client.transfer_isolated_margin_to_spot.__doc__ + params["transFrom"] = "ISOLATED_MARGIN" + params["transTo"] = "SPOT" + return await self._request_margin_api( + "post", "margin/isolated/transfer", signed=True, data=params + ) + + transfer_isolated_margin_to_spot.__doc__ = ( + Client.transfer_isolated_margin_to_spot.__doc__ + ) async def transfer_spot_to_isolated_margin(self, **params): - params['transFrom'] = "SPOT" - params['transTo'] = "ISOLATED_MARGIN" - return await self._request_margin_api('post', 'margin/isolated/transfer', signed=True, data=params) - transfer_spot_to_isolated_margin.__doc__ = Client.transfer_spot_to_isolated_margin.__doc__ + params["transFrom"] = "SPOT" + params["transTo"] = "ISOLATED_MARGIN" + return await self._request_margin_api( + "post", "margin/isolated/transfer", signed=True, data=params + ) + + transfer_spot_to_isolated_margin.__doc__ = ( + Client.transfer_spot_to_isolated_margin.__doc__ + ) async def create_margin_loan(self, **params): - return await self._request_margin_api('post', 'margin/loan', signed=True, data=params) + return await self._request_margin_api( + "post", "margin/loan", signed=True, data=params + ) + create_margin_loan.__doc__ = Client.create_margin_loan.__doc__ async def repay_margin_loan(self, **params): - return await self._request_margin_api('post', 'margin/repay', signed=True, data=params) + return await self._request_margin_api( + "post", "margin/repay", signed=True, data=params + ) + repay_margin_loan.__doc__ = Client.repay_margin_loan.__doc__ async def create_margin_order(self, **params): - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.SPOT_ORDER_PREFIX + self.uuid22() - return await self._request_margin_api('post', 'margin/order', signed=True, data=params) + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.SPOT_ORDER_PREFIX + self.uuid22() + return await self._request_margin_api( + "post", "margin/order", signed=True, data=params + ) + create_margin_order.__doc__ = Client.create_margin_order.__doc__ async def cancel_margin_order(self, **params): - return await self._request_margin_api('delete', 'margin/order', signed=True, data=params) + return await self._request_margin_api( + "delete", "margin/order", signed=True, data=params + ) + cancel_margin_order.__doc__ = Client.cancel_margin_order.__doc__ async def set_margin_max_leverage(self, **params): - return await self._request_margin_api('post', 'margin/max-leverage', signed=True, data=params) + return await self._request_margin_api( + "post", "margin/max-leverage", signed=True, data=params + ) + set_margin_max_leverage.__doc__ = Client.set_margin_max_leverage.__doc__ async def get_margin_transfer_history(self, **params): - return await self._request_margin_api('get', 'margin/transfer', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/transfer", signed=True, data=params + ) + get_margin_transfer_history.__doc__ = Client.get_margin_transfer_history.__doc__ async def get_margin_loan_details(self, **params): - return await self._request_margin_api('get', 'margin/loan', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/loan", signed=True, data=params + ) + get_margin_loan_details.__doc__ = Client.get_margin_loan_details.__doc__ async def get_margin_repay_details(self, **params): - return await self._request_margin_api('get', 'margin/repay', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/repay", signed=True, data=params + ) async def get_cross_margin_data(self, **params): - return await self._request_margin_api('get', 'margin/crossMarginData', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/crossMarginData", signed=True, data=params + ) async def get_margin_interest_history(self, **params): - return await self._request_margin_api('get', 'margin/interestHistory', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/interestHistory", signed=True, data=params + ) async def get_margin_force_liquidation_rec(self, **params): - return await self._request_margin_api('get', 'margin/forceLiquidationRec', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/forceLiquidationRec", signed=True, data=params + ) async def get_margin_order(self, **params): - return await self._request_margin_api('get', 'margin/order', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/order", signed=True, data=params + ) async def get_open_margin_orders(self, **params): - return await self._request_margin_api('get', 'margin/openOrders', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/openOrders", signed=True, data=params + ) async def get_all_margin_orders(self, **params): - return await self._request_margin_api('get', 'margin/allOrders', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/allOrders", signed=True, data=params + ) async def get_margin_trades(self, **params): - return await self._request_margin_api('get', 'margin/myTrades', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/myTrades", signed=True, data=params + ) async def get_max_margin_loan(self, **params): - return await self._request_margin_api('get', 'margin/maxBorrowable', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/maxBorrowable", signed=True, data=params + ) async def get_max_margin_transfer(self, **params): - return await self._request_margin_api('get', 'margin/maxTransferable', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/maxTransferable", signed=True, data=params + ) # Margin OCO async def create_margin_oco_order(self, **params): - return await self._request_margin_api('post', 'margin/order/oco', signed=True, data=params) + return await self._request_margin_api( + "post", "margin/order/oco", signed=True, data=params + ) async def cancel_margin_oco_order(self, **params): - return await self._request_margin_api('delete', 'margin/orderList', signed=True, data=params) + return await self._request_margin_api( + "delete", "margin/orderList", signed=True, data=params + ) async def get_margin_oco_order(self, **params): - return await self._request_margin_api('get', 'margin/orderList', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/orderList", signed=True, data=params + ) async def get_open_margin_oco_orders(self, **params): - return await self._request_margin_api('get', 'margin/openOrderList', signed=True, data=params) + return await self._request_margin_api( + "get", "margin/openOrderList", signed=True, data=params + ) # Cross-margin async def margin_stream_get_listen_key(self): - res = await self._request_margin_api('post', 'userDataStream', signed=False, data={}) - return res['listenKey'] + res = await self._request_margin_api( + "post", "userDataStream", signed=False, data={} + ) + return res["listenKey"] async def margin_stream_keepalive(self, listenKey): - params = { - 'listenKey': listenKey - } - return await self._request_margin_api('put', 'userDataStream', signed=False, data=params) + params = {"listenKey": listenKey} + return await self._request_margin_api( + "put", "userDataStream", signed=False, data=params + ) async def margin_stream_close(self, listenKey): - params = { - 'listenKey': listenKey - } - return await self._request_margin_api('delete', 'userDataStream', signed=False, data=params) + params = {"listenKey": listenKey} + return await self._request_margin_api( + "delete", "userDataStream", signed=False, data=params + ) # Isolated margin async def isolated_margin_stream_get_listen_key(self, symbol): - params = { - 'symbol': symbol - } - res = await self._request_margin_api('post', 'userDataStream/isolated', signed=False, data=params) - return res['listenKey'] + params = {"symbol": symbol} + res = await self._request_margin_api( + "post", "userDataStream/isolated", signed=False, data=params + ) + return res["listenKey"] async def isolated_margin_stream_keepalive(self, symbol, listenKey): - params = { - 'symbol': symbol, - 'listenKey': listenKey - } - return await self._request_margin_api('put', 'userDataStream/isolated', signed=False, data=params) + params = {"symbol": symbol, "listenKey": listenKey} + return await self._request_margin_api( + "put", "userDataStream/isolated", signed=False, data=params + ) async def isolated_margin_stream_close(self, symbol, listenKey): - params = { - 'symbol': symbol, - 'listenKey': listenKey - } - return await self._request_margin_api('delete', 'userDataStream/isolated', signed=False, data=params) + params = {"symbol": symbol, "listenKey": listenKey} + return await self._request_margin_api( + "delete", "userDataStream/isolated", signed=False, data=params + ) # Simple Earn Endpoints async def get_simple_earn_flexible_product_list(self, **params): - return await self._request_margin_api('get', 'simple-earn/flexible/list', signed=True, data=params) - get_simple_earn_flexible_product_list.__doc__ = Client.get_simple_earn_flexible_product_list.__doc__ + return await self._request_margin_api( + "get", "simple-earn/flexible/list", signed=True, data=params + ) + + get_simple_earn_flexible_product_list.__doc__ = ( + Client.get_simple_earn_flexible_product_list.__doc__ + ) async def get_simple_earn_locked_product_list(self, **params): - return await self._request_margin_api('get', 'simple-earn/locked/list', signed=True, data=params) - get_simple_earn_locked_product_list.__doc__ = Client.get_simple_earn_locked_product_list.__doc__ + return await self._request_margin_api( + "get", "simple-earn/locked/list", signed=True, data=params + ) + + get_simple_earn_locked_product_list.__doc__ = ( + Client.get_simple_earn_locked_product_list.__doc__ + ) async def subscribe_simple_earn_flexible_product(self, **params): - return await self._request_margin_api('post', 'simple-earn/flexible/subscribe', signed=True, data=params) - subscribe_simple_earn_flexible_product.__doc__ = Client.subscribe_simple_earn_flexible_product.__doc__ + return await self._request_margin_api( + "post", "simple-earn/flexible/subscribe", signed=True, data=params + ) + + subscribe_simple_earn_flexible_product.__doc__ = ( + Client.subscribe_simple_earn_flexible_product.__doc__ + ) async def subscribe_simple_earn_locked_product(self, **params): - return await self._request_margin_api('post', 'simple-earn/locked/subscribe', signed=True, data=params) - subscribe_simple_earn_locked_product.__doc__ = Client.subscribe_simple_earn_locked_product.__doc__ + return await self._request_margin_api( + "post", "simple-earn/locked/subscribe", signed=True, data=params + ) + + subscribe_simple_earn_locked_product.__doc__ = ( + Client.subscribe_simple_earn_locked_product.__doc__ + ) async def redeem_simple_earn_flexible_product(self, **params): - return await self._request_margin_api('post', 'simple-earn/flexible/redeem', signed=True, data=params) - redeem_simple_earn_flexible_product.__doc__ = Client.redeem_simple_earn_flexible_product.__doc__ + return await self._request_margin_api( + "post", "simple-earn/flexible/redeem", signed=True, data=params + ) + + redeem_simple_earn_flexible_product.__doc__ = ( + Client.redeem_simple_earn_flexible_product.__doc__ + ) async def redeem_simple_earn_locked_product(self, **params): - return await self._request_margin_api('post', 'simple-earn/locked/redeem', signed=True, data=params) - redeem_simple_earn_locked_product.__doc__ = Client.redeem_simple_earn_locked_product.__doc__ + return await self._request_margin_api( + "post", "simple-earn/locked/redeem", signed=True, data=params + ) + + redeem_simple_earn_locked_product.__doc__ = ( + Client.redeem_simple_earn_locked_product.__doc__ + ) async def get_simple_earn_flexible_product_position(self, **params): - return await self._request_margin_api('get', 'simple-earn/flexible/position', signed=True, data=params) - get_simple_earn_flexible_product_position.__doc__ = Client.get_simple_earn_flexible_product_position.__doc__ + return await self._request_margin_api( + "get", "simple-earn/flexible/position", signed=True, data=params + ) + + get_simple_earn_flexible_product_position.__doc__ = ( + Client.get_simple_earn_flexible_product_position.__doc__ + ) async def get_simple_earn_locked_product_position(self, **params): - return await self._request_margin_api('get', 'simple-earn/locked/position', signed=True, data=params) - get_simple_earn_locked_product_position.__doc__ = Client.get_simple_earn_locked_product_position.__doc__ + return await self._request_margin_api( + "get", "simple-earn/locked/position", signed=True, data=params + ) + + get_simple_earn_locked_product_position.__doc__ = ( + Client.get_simple_earn_locked_product_position.__doc__ + ) async def get_simple_earn_account(self, **params): - return await self._request_margin_api('get', 'simple-earn/account', signed=True, data=params) + return await self._request_margin_api( + "get", "simple-earn/account", signed=True, data=params + ) + get_simple_earn_account.__doc__ = Client.get_simple_earn_account.__doc__ # Lending Endpoints async def get_fixed_activity_project_list(self, **params): - return await self._request_margin_api('get', 'lending/project/list', signed=True, data=params) + return await self._request_margin_api( + "get", "lending/project/list", signed=True, data=params + ) async def change_fixed_activity_to_daily_position(self, **params): - return await self._request_margin_api('post', 'lending/positionChanged', signed=True, data=params) + return await self._request_margin_api( + "post", "lending/positionChanged", signed=True, data=params + ) # Staking Endpoints async def get_staking_product_list(self, **params): - return await self._request_margin_api('get', 'staking/productList', signed=True, data=params) + return await self._request_margin_api( + "get", "staking/productList", signed=True, data=params + ) async def purchase_staking_product(self, **params): - return await self._request_margin_api('post', 'staking/purchase', signed=True, data=params) + return await self._request_margin_api( + "post", "staking/purchase", signed=True, data=params + ) async def redeem_staking_product(self, **params): - return await self._request_margin_api('post', 'staking/redeem', signed=True, data=params) + return await self._request_margin_api( + "post", "staking/redeem", signed=True, data=params + ) async def get_staking_position(self, **params): - return await self._request_margin_api('get', 'staking/position', signed=True, data=params) + return await self._request_margin_api( + "get", "staking/position", signed=True, data=params + ) async def get_staking_purchase_history(self, **params): - return await self._request_margin_api('get', 'staking/purchaseRecord', signed=True, data=params) + return await self._request_margin_api( + "get", "staking/purchaseRecord", signed=True, data=params + ) async def set_auto_staking(self, **params): - return await self._request_margin_api('post', 'staking/setAutoStaking', signed=True, data=params) + return await self._request_margin_api( + "post", "staking/setAutoStaking", signed=True, data=params + ) async def get_personal_left_quota(self, **params): - return await self._request_margin_api('get', 'staking/personalLeftQuota', signed=True, data=params) + return await self._request_margin_api( + "get", "staking/personalLeftQuota", signed=True, data=params + ) # US Staking Endpoints async def get_staking_asset_us(self, **params): assert self.tld == "us", "Endpoint only available on binance.us" return await self._request_margin_api("get", "staking/asset", True, data=params) + get_staking_asset_us.__doc__ = Client.get_staking_asset_us.__doc__ async def stake_asset_us(self, **params): assert self.tld == "us", "Endpoint only available on binance.us" - return await self._request_margin_api("post", "staking/stake", True, data=params) + return await self._request_margin_api( + "post", "staking/stake", True, data=params + ) + stake_asset_us.__doc__ = Client.stake_asset_us.__doc__ async def unstake_asset_us(self, **params): assert self.tld == "us", "Endpoint only available on binance.us" - return await self._request_margin_api("post", "staking/unstake", True, data=params) + return await self._request_margin_api( + "post", "staking/unstake", True, data=params + ) + unstake_asset_us.__doc__ = Client.unstake_asset_us.__doc__ async def get_staking_balance_us(self, **params): assert self.tld == "us", "Endpoint only available on binance.us" - return await self._request_margin_api("get", "staking/stakingBalance", True, data=params) + return await self._request_margin_api( + "get", "staking/stakingBalance", True, data=params + ) + get_staking_balance_us.__doc__ = Client.get_staking_balance_us.__doc__ async def get_staking_history_us(self, **params): assert self.tld == "us", "Endpoint only available on binance.us" - return await self._request_margin_api("get", "staking/history", True, data=params) + return await self._request_margin_api( + "get", "staking/history", True, data=params + ) + get_staking_history_us.__doc__ = Client.get_staking_history_us.__doc__ async def get_staking_rewards_history_us(self, **params): assert self.tld == "us", "Endpoint only available on binance.us" - return await self._request_margin_api("get", "staking/stakingRewardsHistory", True, data=params) - get_staking_rewards_history_us.__doc__ = Client.get_staking_rewards_history_us.__doc__ + return await self._request_margin_api( + "get", "staking/stakingRewardsHistory", True, data=params + ) + + get_staking_rewards_history_us.__doc__ = ( + Client.get_staking_rewards_history_us.__doc__ + ) # Sub Accounts async def get_sub_account_list(self, **params): - return await self._request_margin_api('get', 'sub-account/list', True, data=params) + return await self._request_margin_api( + "get", "sub-account/list", True, data=params + ) async def get_sub_account_transfer_history(self, **params): - return await self._request_margin_api('get', 'sub-account/sub/transfer/history', True, data=params) + return await self._request_margin_api( + "get", "sub-account/sub/transfer/history", True, data=params + ) async def get_sub_account_futures_transfer_history(self, **params): - return await self._request_margin_api('get', 'sub-account/futures/internalTransfer', True, data=params) + return await self._request_margin_api( + "get", "sub-account/futures/internalTransfer", True, data=params + ) async def create_sub_account_futures_transfer(self, **params): - return await self._request_margin_api('post', 'sub-account/futures/internalTransfer', True, data=params) + return await self._request_margin_api( + "post", "sub-account/futures/internalTransfer", True, data=params + ) async def get_sub_account_assets(self, **params): - return await self._request_margin_api('get', 'sub-account/assets', True, data=params, version=4) + return await self._request_margin_api( + "get", "sub-account/assets", True, data=params, version=4 + ) async def query_subaccount_spot_summary(self, **params): - return await self._request_margin_api('get', 'sub-account/spotSummary', True, data=params) + return await self._request_margin_api( + "get", "sub-account/spotSummary", True, data=params + ) async def get_subaccount_deposit_address(self, **params): - return await self._request_margin_api('get', 'capital/deposit/subAddress', True, data=params) + return await self._request_margin_api( + "get", "capital/deposit/subAddress", True, data=params + ) async def get_subaccount_deposit_history(self, **params): - return await self._request_margin_api('get', 'capital/deposit/subHisrec', True, data=params) + return await self._request_margin_api( + "get", "capital/deposit/subHisrec", True, data=params + ) async def get_subaccount_futures_margin_status(self, **params): - return await self._request_margin_api('get', 'sub-account/status', True, data=params) + return await self._request_margin_api( + "get", "sub-account/status", True, data=params + ) async def enable_subaccount_margin(self, **params): - return await self._request_margin_api('post', 'sub-account/margin/enable', True, data=params) + return await self._request_margin_api( + "post", "sub-account/margin/enable", True, data=params + ) async def get_subaccount_margin_details(self, **params): - return await self._request_margin_api('get', 'sub-account/margin/account', True, data=params) + return await self._request_margin_api( + "get", "sub-account/margin/account", True, data=params + ) async def get_subaccount_margin_summary(self, **params): - return await self._request_margin_api('get', 'sub-account/margin/accountSummary', True, data=params) + return await self._request_margin_api( + "get", "sub-account/margin/accountSummary", True, data=params + ) async def enable_subaccount_futures(self, **params): - return await self._request_margin_api('post', 'sub-account/futures/enable', True, data=params) + return await self._request_margin_api( + "post", "sub-account/futures/enable", True, data=params + ) async def get_subaccount_futures_details(self, **params): - return await self._request_margin_api('get', 'sub-account/futures/account', True, data=params, version=2) + return await self._request_margin_api( + "get", "sub-account/futures/account", True, data=params, version=2 + ) async def get_subaccount_futures_summary(self, **params): - return await self._request_margin_api('get', 'sub-account/futures/accountSummary', True, data=params, version=2) + return await self._request_margin_api( + "get", "sub-account/futures/accountSummary", True, data=params, version=2 + ) async def get_subaccount_futures_positionrisk(self, **params): - return await self._request_margin_api('get', 'sub-account/futures/positionRisk', True, data=params, version=2) + return await self._request_margin_api( + "get", "sub-account/futures/positionRisk", True, data=params, version=2 + ) async def make_subaccount_futures_transfer(self, **params): - return await self._request_margin_api('post', 'sub-account/futures/transfer', True, data=params) + return await self._request_margin_api( + "post", "sub-account/futures/transfer", True, data=params + ) async def make_subaccount_margin_transfer(self, **params): - return await self._request_margin_api('post', 'sub-account/margin/transfer', True, data=params) + return await self._request_margin_api( + "post", "sub-account/margin/transfer", True, data=params + ) async def make_subaccount_to_subaccount_transfer(self, **params): - return await self._request_margin_api('post', 'sub-account/transfer/subToSub', True, data=params) + return await self._request_margin_api( + "post", "sub-account/transfer/subToSub", True, data=params + ) async def make_subaccount_to_master_transfer(self, **params): - return await self._request_margin_api('post', 'sub-account/transfer/subToMaster', True, data=params) + return await self._request_margin_api( + "post", "sub-account/transfer/subToMaster", True, data=params + ) async def get_subaccount_transfer_history(self, **params): - return await self._request_margin_api('get', 'sub-account/transfer/subUserHistory', True, data=params) + return await self._request_margin_api( + "get", "sub-account/transfer/subUserHistory", True, data=params + ) async def make_subaccount_universal_transfer(self, **params): - return await self._request_margin_api('post', 'sub-account/universalTransfer', True, data=params) + return await self._request_margin_api( + "post", "sub-account/universalTransfer", True, data=params + ) async def get_universal_transfer_history(self, **params): - return await self._request_margin_api('get', 'sub-account/universalTransfer', True, data=params) + return await self._request_margin_api( + "get", "sub-account/universalTransfer", True, data=params + ) # Futures API async def futures_ping(self): - return await self._request_futures_api('get', 'ping') + return await self._request_futures_api("get", "ping") async def futures_time(self): - return await self._request_futures_api('get', 'time') + return await self._request_futures_api("get", "time") async def futures_exchange_info(self): - return await self._request_futures_api('get', 'exchangeInfo') + return await self._request_futures_api("get", "exchangeInfo") async def futures_order_book(self, **params): - return await self._request_futures_api('get', 'depth', data=params) + return await self._request_futures_api("get", "depth", data=params) async def futures_recent_trades(self, **params): - return await self._request_futures_api('get', 'trades', data=params) + return await self._request_futures_api("get", "trades", data=params) async def futures_historical_trades(self, **params): - return await self._request_futures_api('get', 'historicalTrades', data=params) + return await self._request_futures_api("get", "historicalTrades", data=params) async def futures_aggregate_trades(self, **params): - return await self._request_futures_api('get', 'aggTrades', data=params) + return await self._request_futures_api("get", "aggTrades", data=params) async def futures_klines(self, **params): - return await self._request_futures_api('get', 'klines', data=params) + return await self._request_futures_api("get", "klines", data=params) async def futures_continous_klines(self, **params): - return await self._request_futures_api('get', 'continuousKlines', data=params) + return await self._request_futures_api("get", "continuousKlines", data=params) - async def futures_historical_klines(self, symbol, interval, start_str, end_str=None, limit=500): - return await self._historical_klines(symbol, interval, start_str, end_str=end_str, limit=limit, klines_type=HistoricalKlinesType.FUTURES) + async def futures_historical_klines( + self, symbol, interval, start_str, end_str=None, limit=500 + ): + return await self._historical_klines( + symbol, + interval, + start_str, + end_str=end_str, + limit=limit, + klines_type=HistoricalKlinesType.FUTURES, + ) - async def futures_historical_klines_generator(self, symbol, interval, start_str, end_str=None): - return self._historical_klines_generator(symbol, interval, start_str, end_str=end_str, klines_type=HistoricalKlinesType.FUTURES) + async def futures_historical_klines_generator( + self, symbol, interval, start_str, end_str=None + ): + return self._historical_klines_generator( + symbol, + interval, + start_str, + end_str=end_str, + klines_type=HistoricalKlinesType.FUTURES, + ) async def futures_mark_price(self, **params): - return await self._request_futures_api('get', 'premiumIndex', data=params) + return await self._request_futures_api("get", "premiumIndex", data=params) async def futures_funding_rate(self, **params): - return await self._request_futures_api('get', 'fundingRate', data=params) + return await self._request_futures_api("get", "fundingRate", data=params) async def futures_top_longshort_account_ratio(self, **params): - return await self._request_futures_data_api('get', 'topLongShortAccountRatio', data=params) + return await self._request_futures_data_api( + "get", "topLongShortAccountRatio", data=params + ) async def futures_top_longshort_position_ratio(self, **params): - return await self._request_futures_data_api('get', 'topLongShortPositionRatio', data=params) + return await self._request_futures_data_api( + "get", "topLongShortPositionRatio", data=params + ) async def futures_global_longshort_ratio(self, **params): - return await self._request_futures_data_api('get', 'globalLongShortAccountRatio', data=params) + return await self._request_futures_data_api( + "get", "globalLongShortAccountRatio", data=params + ) async def futures_ticker(self, **params): - return await self._request_futures_api('get', 'ticker/24hr', data=params) + return await self._request_futures_api("get", "ticker/24hr", data=params) async def futures_symbol_ticker(self, **params): - return await self._request_futures_api('get', 'ticker/price', data=params) + return await self._request_futures_api("get", "ticker/price", data=params) async def futures_orderbook_ticker(self, **params): - return await self._request_futures_api('get', 'ticker/bookTicker', data=params) + return await self._request_futures_api("get", "ticker/bookTicker", data=params) async def futures_liquidation_orders(self, **params): - return await self._request_futures_api('get', 'forceOrders', signed=True, data=params) + return await self._request_futures_api( + "get", "forceOrders", signed=True, data=params + ) async def futures_api_trading_status(self, **params): - return await self._request_futures_api('get', 'apiTradingStatus', signed=True, data=params) + return await self._request_futures_api( + "get", "apiTradingStatus", signed=True, data=params + ) async def futures_commission_rate(self, **params): - return await self._request_futures_api('get', 'commissionRate', signed=True, data=params) + return await self._request_futures_api( + "get", "commissionRate", signed=True, data=params + ) async def futures_adl_quantile_estimate(self, **params): - return await self._request_futures_api('get', 'adlQuantile', signed=True, data=params) + return await self._request_futures_api( + "get", "adlQuantile", signed=True, data=params + ) async def futures_open_interest(self, **params): - return await self._request_futures_api('get', 'openInterest', data=params) + return await self._request_futures_api("get", "openInterest", data=params) async def futures_index_info(self, **params): - return await self._request_futures_api('get', 'indexInfo', data=params) + return await self._request_futures_api("get", "indexInfo", data=params) async def futures_open_interest_hist(self, **params): - return await self._request_futures_data_api('get', 'openInterestHist', data=params) + return await self._request_futures_data_api( + "get", "openInterestHist", data=params + ) async def futures_leverage_bracket(self, **params): - return await self._request_futures_api('get', 'leverageBracket', True, data=params) + return await self._request_futures_api( + "get", "leverageBracket", True, data=params + ) async def futures_account_transfer(self, **params): - return await self._request_margin_api('post', 'futures/transfer', True, data=params) + return await self._request_margin_api( + "post", "futures/transfer", True, data=params + ) async def transfer_history(self, **params): - return await self._request_margin_api('get', 'futures/transfer', True, data=params) + return await self._request_margin_api( + "get", "futures/transfer", True, data=params + ) async def futures_loan_borrow_history(self, **params): - return await self._request_margin_api('get', 'futures/loan/borrow/history', True, data=params) + return await self._request_margin_api( + "get", "futures/loan/borrow/history", True, data=params + ) async def futures_loan_repay_history(self, **params): - return await self._request_margin_api('get', 'futures/loan/repay/history', True, data=params) + return await self._request_margin_api( + "get", "futures/loan/repay/history", True, data=params + ) async def futures_loan_wallet(self, **params): - return await self._request_margin_api('get', 'futures/loan/wallet', True, data=params, version=2) + return await self._request_margin_api( + "get", "futures/loan/wallet", True, data=params, version=2 + ) async def futures_cross_collateral_adjust_history(self, **params): - return await self._request_margin_api('get', 'futures/loan/adjustCollateral/history', True, data=params) + return await self._request_margin_api( + "get", "futures/loan/adjustCollateral/history", True, data=params + ) async def futures_cross_collateral_liquidation_history(self, **params): - return await self._request_margin_api('get', 'futures/loan/liquidationHistory', True, data=params) + return await self._request_margin_api( + "get", "futures/loan/liquidationHistory", True, data=params + ) async def futures_loan_interest_history(self, **params): - return await self._request_margin_api('get', 'futures/loan/interestHistory', True, data=params) + return await self._request_margin_api( + "get", "futures/loan/interestHistory", True, data=params + ) async def futures_create_order(self, **params): - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return await self._request_futures_api('post', 'order', True, data=params) + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return await self._request_futures_api("post", "order", True, data=params) async def futures_create_test_order(self, **params): - return await self._request_futures_api('post', 'order/test', True, data=params) + return await self._request_futures_api("post", "order/test", True, data=params) async def futures_place_batch_order(self, **params): - for order in params['batchOrders']: - if 'newClientOrderId' not in order: - order['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + for order in params["batchOrders"]: + if "newClientOrderId" not in order: + order["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() query_string = urlencode(params) - query_string = query_string.replace('%27', '%22') - params['batchOrders'] = query_string[12:] - return await self._request_futures_api('post', 'batchOrders', True, data=params) + query_string = query_string.replace("%27", "%22") + params["batchOrders"] = query_string[12:] + return await self._request_futures_api("post", "batchOrders", True, data=params) async def futures_get_order(self, **params): - return await self._request_futures_api('get', 'order', True, data=params) + return await self._request_futures_api("get", "order", True, data=params) async def futures_get_open_orders(self, **params): - return await self._request_futures_api('get', 'openOrders', True, data=params) + return await self._request_futures_api("get", "openOrders", True, data=params) async def futures_get_all_orders(self, **params): - return await self._request_futures_api('get', 'allOrders', True, data=params) + return await self._request_futures_api("get", "allOrders", True, data=params) async def futures_cancel_order(self, **params): - return await self._request_futures_api('delete', 'order', True, data=params) + return await self._request_futures_api("delete", "order", True, data=params) async def futures_cancel_all_open_orders(self, **params): - return await self._request_futures_api('delete', 'allOpenOrders', True, data=params) + return await self._request_futures_api( + "delete", "allOpenOrders", True, data=params + ) async def futures_cancel_orders(self, **params): - return await self._request_futures_api('delete', 'batchOrders', True, data=params) + return await self._request_futures_api( + "delete", "batchOrders", True, data=params + ) async def futures_countdown_cancel_all(self, **params): - return await self._request_futures_api('post', 'countdownCancelAll', True, data=params) + return await self._request_futures_api( + "post", "countdownCancelAll", True, data=params + ) async def futures_account_balance(self, **params): - return await self._request_futures_api('get', 'balance', True, version=3, data=params) + return await self._request_futures_api( + "get", "balance", True, version=3, data=params + ) async def futures_account(self, **params): - return await self._request_futures_api('get', 'account', True, version=2, data=params) + return await self._request_futures_api( + "get", "account", True, version=2, data=params + ) async def futures_change_leverage(self, **params): - return await self._request_futures_api('post', 'leverage', True, data=params) + return await self._request_futures_api("post", "leverage", True, data=params) async def futures_change_margin_type(self, **params): - return await self._request_futures_api('post', 'marginType', True, data=params) + return await self._request_futures_api("post", "marginType", True, data=params) async def futures_change_position_margin(self, **params): - return await self._request_futures_api('post', 'positionMargin', True, data=params) + return await self._request_futures_api( + "post", "positionMargin", True, data=params + ) async def futures_position_margin_history(self, **params): - return await self._request_futures_api('get', 'positionMargin/history', True, data=params) + return await self._request_futures_api( + "get", "positionMargin/history", True, data=params + ) async def futures_position_information(self, **params): - return await self._request_futures_api('get', 'positionRisk', True, version=3, data=params) + return await self._request_futures_api( + "get", "positionRisk", True, version=3, data=params + ) async def futures_account_trades(self, **params): - return await self._request_futures_api('get', 'userTrades', True, data=params) + return await self._request_futures_api("get", "userTrades", True, data=params) async def futures_income_history(self, **params): - return await self._request_futures_api('get', 'income', True, data=params) + return await self._request_futures_api("get", "income", True, data=params) async def futures_change_position_mode(self, **params): - return await self._request_futures_api('post', 'positionSide/dual', True, data=params) + return await self._request_futures_api( + "post", "positionSide/dual", True, data=params + ) async def futures_get_position_mode(self, **params): - return await self._request_futures_api('get', 'positionSide/dual', True, data=params) + return await self._request_futures_api( + "get", "positionSide/dual", True, data=params + ) async def futures_change_multi_assets_mode(self, multiAssetsMargin: bool): - params = { - 'multiAssetsMargin': 'true' if multiAssetsMargin else 'false' - } - return await self._request_futures_api('post', 'multiAssetsMargin', True, data=params) + params = {"multiAssetsMargin": "true" if multiAssetsMargin else "false"} + return await self._request_futures_api( + "post", "multiAssetsMargin", True, data=params + ) async def futures_get_multi_assets_mode(self): - return await self._request_futures_api('get', 'multiAssetsMargin', True, data={}) + return await self._request_futures_api( + "get", "multiAssetsMargin", True, data={} + ) async def futures_stream_get_listen_key(self): - res = await self._request_futures_api('post', 'listenKey', signed=False, data={}) - return res['listenKey'] + res = await self._request_futures_api( + "post", "listenKey", signed=False, data={} + ) + return res["listenKey"] async def futures_stream_keepalive(self, listenKey): - params = { - 'listenKey': listenKey - } - return await self._request_futures_api('put', 'listenKey', signed=False, data=params) + params = {"listenKey": listenKey} + return await self._request_futures_api( + "put", "listenKey", signed=False, data=params + ) async def futures_stream_close(self, listenKey): - params = { - 'listenKey': listenKey - } - return await self._request_futures_api('delete', 'listenKey', signed=False, data=params) + params = {"listenKey": listenKey} + return await self._request_futures_api( + "delete", "listenKey", signed=False, data=params + ) # new methods async def futures_account_config(self, **params): - return await self._request_futures_api('get', 'accountConfig', signed=True, version=1, data=params) + return await self._request_futures_api( + "get", "accountConfig", signed=True, version=1, data=params + ) async def futures_symbol_config(self, **params): - return await self._request_futures_api('get', 'symbolConfig', signed=True, version=1, data=params) + return await self._request_futures_api( + "get", "symbolConfig", signed=True, version=1, data=params + ) # COIN Futures API @@ -11324,7 +12281,9 @@ async def futures_coin_recent_trades(self, **params): return await self._request_futures_coin_api("get", "trades", data=params) async def futures_coin_historical_trades(self, **params): - return await self._request_futures_coin_api("get", "historicalTrades", data=params) + return await self._request_futures_coin_api( + "get", "historicalTrades", data=params + ) async def futures_coin_aggregate_trades(self, **params): return await self._request_futures_coin_api("get", "aggTrades", data=params) @@ -11333,13 +12292,19 @@ async def futures_coin_klines(self, **params): return await self._request_futures_coin_api("get", "klines", data=params) async def futures_coin_continous_klines(self, **params): - return await self._request_futures_coin_api("get", "continuousKlines", data=params) + return await self._request_futures_coin_api( + "get", "continuousKlines", data=params + ) async def futures_coin_index_price_klines(self, **params): - return await self._request_futures_coin_api("get", "indexPriceKlines", data=params) + return await self._request_futures_coin_api( + "get", "indexPriceKlines", data=params + ) async def futures_coin_mark_price_klines(self, **params): - return await self._request_futures_coin_api("get", "markPriceKlines", data=params) + return await self._request_futures_coin_api( + "get", "markPriceKlines", data=params + ) async def futures_coin_mark_price(self, **params): return await self._request_futures_coin_api("get", "premiumIndex", data=params) @@ -11354,16 +12319,22 @@ async def futures_coin_symbol_ticker(self, **params): return await self._request_futures_coin_api("get", "ticker/price", data=params) async def futures_coin_orderbook_ticker(self, **params): - return await self._request_futures_coin_api("get", "ticker/bookTicker", data=params) + return await self._request_futures_coin_api( + "get", "ticker/bookTicker", data=params + ) async def futures_coin_liquidation_orders(self, **params): - return await self._request_futures_coin_api("get", "forceOrders", signed=True, data=params) + return await self._request_futures_coin_api( + "get", "forceOrders", signed=True, data=params + ) async def futures_coin_open_interest(self, **params): return await self._request_futures_coin_api("get", "openInterest", data=params) async def futures_coin_open_interest_hist(self, **params): - return await self._request_futures_coin_data_api("get", "openInterestHist", data=params) + return await self._request_futures_coin_data_api( + "get", "openInterestHist", data=params + ) async def futures_coin_leverage_bracket(self, **params): return await self._request_futures_coin_api( @@ -11371,13 +12342,19 @@ async def futures_coin_leverage_bracket(self, **params): ) async def new_transfer_history(self, **params): - return await self._request_margin_api("get", "asset/transfer", True, data=params) + return await self._request_margin_api( + "get", "asset/transfer", True, data=params + ) async def funding_wallet(self, **params): - return await self._request_margin_api("post", "asset/get-funding-asset", True, data=params) + return await self._request_margin_api( + "post", "asset/get-funding-asset", True, data=params + ) async def get_user_asset(self, **params): - return await self._request_margin_api("post", "asset/getUserAsset", True, data=params, version=3) + return await self._request_margin_api( + "post", "asset/getUserAsset", True, data=params, version=3 + ) async def universal_transfer(self, **params): return await self._request_margin_api( @@ -11385,25 +12362,29 @@ async def universal_transfer(self, **params): ) async def futures_coin_create_order(self, **params): - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() return await self._request_futures_coin_api("post", "order", True, data=params) async def futures_coin_place_batch_order(self, **params): - for order in params['batchOrders']: - if 'newClientOrderId' not in order: - order['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + for order in params["batchOrders"]: + if "newClientOrderId" not in order: + order["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() query_string = urlencode(params) - query_string = query_string.replace('%27', '%22') - params['batchOrders'] = query_string[12:] + query_string = query_string.replace("%27", "%22") + params["batchOrders"] = query_string[12:] - return await self._request_futures_coin_api('post', 'batchOrders', True, data=params) + return await self._request_futures_coin_api( + "post", "batchOrders", True, data=params + ) async def futures_coin_get_order(self, **params): return await self._request_futures_coin_api("get", "order", True, data=params) async def futures_coin_get_open_orders(self, **params): - return await self._request_futures_coin_api("get", "openOrders", True, data=params) + return await self._request_futures_coin_api( + "get", "openOrders", True, data=params + ) async def futures_coin_get_all_orders(self, **params): return await self._request_futures_coin_api( @@ -11456,47 +12437,65 @@ async def futures_coin_position_margin_history(self, **params): ) async def futures_coin_position_information(self, **params): - return await self._request_futures_coin_api("get", "positionRisk", True, data=params) + return await self._request_futures_coin_api( + "get", "positionRisk", True, data=params + ) async def futures_coin_account_trades(self, **params): - return await self._request_futures_coin_api("get", "userTrades", True, data=params) + return await self._request_futures_coin_api( + "get", "userTrades", True, data=params + ) async def futures_coin_income_history(self, **params): return await self._request_futures_coin_api("get", "income", True, data=params) async def futures_coin_change_position_mode(self, **params): - return await self._request_futures_coin_api("post", "positionSide/dual", True, data=params) + return await self._request_futures_coin_api( + "post", "positionSide/dual", True, data=params + ) async def futures_coin_get_position_mode(self, **params): - return await self._request_futures_coin_api("get", "positionSide/dual", True, data=params) + return await self._request_futures_coin_api( + "get", "positionSide/dual", True, data=params + ) async def futures_coin_stream_get_listen_key(self): - res = await self._request_futures_coin_api('post', 'listenKey', signed=False, data={}) - return res['listenKey'] + res = await self._request_futures_coin_api( + "post", "listenKey", signed=False, data={} + ) + return res["listenKey"] async def futures_coin_stream_keepalive(self, listenKey): - params = { - 'listenKey': listenKey - } - return await self._request_futures_coin_api('put', 'listenKey', signed=False, data=params) + params = {"listenKey": listenKey} + return await self._request_futures_coin_api( + "put", "listenKey", signed=False, data=params + ) async def futures_coin_stream_close(self, listenKey): - params = { - 'listenKey': listenKey - } - return await self._request_futures_coin_api('delete', 'listenKey', signed=False, data=params) + params = {"listenKey": listenKey} + return await self._request_futures_coin_api( + "delete", "listenKey", signed=False, data=params + ) async def get_all_coins_info(self, **params): - return await self._request_margin_api('get', 'capital/config/getall', True, data=params) + return await self._request_margin_api( + "get", "capital/config/getall", True, data=params + ) async def get_account_snapshot(self, **params): - return await self._request_margin_api('get', 'accountSnapshot', True, data=params) + return await self._request_margin_api( + "get", "accountSnapshot", True, data=params + ) async def disable_fast_withdraw_switch(self, **params): - return await self._request_margin_api('post', 'disableFastWithdrawSwitch', True, data=params) + return await self._request_margin_api( + "post", "disableFastWithdrawSwitch", True, data=params + ) async def enable_fast_withdraw_switch(self, **params): - return await self._request_margin_api('post', 'enableFastWithdrawSwitch', True, data=params) + return await self._request_margin_api( + "post", "enableFastWithdrawSwitch", True, data=params + ) """ ==================================================================================================================== @@ -11507,115 +12506,155 @@ async def enable_fast_withdraw_switch(self, **params): # Quoting interface endpoints async def options_ping(self): - return await self._request_options_api('get', 'ping') + return await self._request_options_api("get", "ping") async def options_time(self): - return await self._request_options_api('get', 'time') + return await self._request_options_api("get", "time") async def options_info(self): - return await self._request_options_api('get', 'optionInfo') + return await self._request_options_api("get", "optionInfo") async def options_exchange_info(self): - return await self._request_options_api('get', 'exchangeInfo') + return await self._request_options_api("get", "exchangeInfo") async def options_index_price(self, **params): - return await self._request_options_api('get', 'index', data=params) + return await self._request_options_api("get", "index", data=params) async def options_price(self, **params): - return await self._request_options_api('get', 'ticker', data=params) + return await self._request_options_api("get", "ticker", data=params) async def options_mark_price(self, **params): - return await self._request_options_api('get', 'mark', data=params) + return await self._request_options_api("get", "mark", data=params) async def options_order_book(self, **params): - return await self._request_options_api('get', 'depth', data=params) + return await self._request_options_api("get", "depth", data=params) async def options_klines(self, **params): - return await self._request_options_api('get', 'klines', data=params) + return await self._request_options_api("get", "klines", data=params) async def options_recent_trades(self, **params): - return await self._request_options_api('get', 'trades', data=params) + return await self._request_options_api("get", "trades", data=params) async def options_historical_trades(self, **params): - return await self._request_options_api('get', 'historicalTrades', data=params) + return await self._request_options_api("get", "historicalTrades", data=params) # Account and trading interface endpoints async def options_account_info(self, **params): - return await self._request_options_api('get', 'account', signed=True, data=params) + return await self._request_options_api( + "get", "account", signed=True, data=params + ) async def options_funds_transfer(self, **params): - return await self._request_options_api('post', 'transfer', signed=True, data=params) + return await self._request_options_api( + "post", "transfer", signed=True, data=params + ) async def options_positions(self, **params): - return await self._request_options_api('get', 'position', signed=True, data=params) + return await self._request_options_api( + "get", "position", signed=True, data=params + ) async def options_bill(self, **params): - return await self._request_options_api('post', 'bill', signed=True, data=params) + return await self._request_options_api("post", "bill", signed=True, data=params) async def options_place_order(self, **params): - if 'clientOrderId' not in params: - params['clientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return await self._request_options_api('post', 'order', signed=True, data=params) + if "clientOrderId" not in params: + params["clientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return await self._request_options_api( + "post", "order", signed=True, data=params + ) async def options_place_batch_order(self, **params): - for order in params['batchOrders']: - if 'newClientOrderId' not in order: - order['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return await self._request_options_api('post', 'batchOrders', signed=True, data=params) + for order in params["batchOrders"]: + if "newClientOrderId" not in order: + order["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return await self._request_options_api( + "post", "batchOrders", signed=True, data=params + ) async def options_cancel_order(self, **params): - return await self._request_options_api('delete', 'order', signed=True, data=params) + return await self._request_options_api( + "delete", "order", signed=True, data=params + ) async def options_cancel_batch_order(self, **params): - return await self._request_options_api('delete', 'batchOrders', signed=True, data=params) + return await self._request_options_api( + "delete", "batchOrders", signed=True, data=params + ) async def options_cancel_all_orders(self, **params): - return await self._request_options_api('delete', 'allOpenOrders', signed=True, data=params) + return await self._request_options_api( + "delete", "allOpenOrders", signed=True, data=params + ) async def options_query_order(self, **params): - return await self._request_options_api('get', 'order', signed=True, data=params) + return await self._request_options_api("get", "order", signed=True, data=params) async def options_query_pending_orders(self, **params): - return await self._request_options_api('get', 'openOrders', signed=True, data=params) + return await self._request_options_api( + "get", "openOrders", signed=True, data=params + ) async def options_query_order_history(self, **params): - return await self._request_options_api('get', 'historyOrders', signed=True, data=params) + return await self._request_options_api( + "get", "historyOrders", signed=True, data=params + ) async def options_user_trades(self, **params): - return await self._request_options_api('get', 'userTrades', signed=True, data=params) + return await self._request_options_api( + "get", "userTrades", signed=True, data=params + ) # Fiat Endpoints async def get_fiat_deposit_withdraw_history(self, **params): - return await self._request_margin_api('get', 'fiat/orders', signed=True, data=params) + return await self._request_margin_api( + "get", "fiat/orders", signed=True, data=params + ) async def get_fiat_payments_history(self, **params): - return await self._request_margin_api('get', 'fiat/payments', signed=True, data=params) + return await self._request_margin_api( + "get", "fiat/payments", signed=True, data=params + ) # C2C Endpoints async def get_c2c_trade_history(self, **params): - return await self._request_margin_api('get', 'c2c/orderMatch/listUserOrderHistory', signed=True, data=params) + return await self._request_margin_api( + "get", "c2c/orderMatch/listUserOrderHistory", signed=True, data=params + ) # Pay Endpoints async def get_pay_trade_history(self, **params): - return await self._request_margin_api('get', 'pay/transactions', signed=True, data=params) + return await self._request_margin_api( + "get", "pay/transactions", signed=True, data=params + ) + get_pay_trade_history.__doc__ = Client.get_pay_trade_history.__doc__ # Convert Endpoints async def get_convert_trade_history(self, **params): - return await self._request_margin_api('get', 'convert/tradeFlow', signed=True, data=params) + return await self._request_margin_api( + "get", "convert/tradeFlow", signed=True, data=params + ) + get_convert_trade_history.__doc__ = Client.get_convert_trade_history.__doc__ async def convert_request_quote(self, **params): - return await self._request_margin_api('post', 'convert/getQuote', signed=True, data=params) + return await self._request_margin_api( + "post", "convert/getQuote", signed=True, data=params + ) + convert_request_quote.__doc__ = Client.convert_request_quote.__doc__ async def convert_accept_quote(self, **params): - return await self._request_margin_api('post', 'convert/acceptQuote', signed=True, data=params) + return await self._request_margin_api( + "post", "convert/acceptQuote", signed=True, data=params + ) + convert_accept_quote.__doc__ = Client.convert_accept_quote.__doc__ """ @@ -11625,152 +12664,198 @@ async def convert_accept_quote(self, **params): """ async def papi_get_balance(self, **params): - return await self._request_papi_api('get', 'balance', signed=True, data=params) + return await self._request_papi_api("get", "balance", signed=True, data=params) async def papi_get_account(self, **params): - return await self._request_papi_api('get', 'account', signed=True, data=params) + return await self._request_papi_api("get", "account", signed=True, data=params) async def papi_get_margin_max_borrowable(self, **params): - return await self._request_papi_api('get', 'margin/maxBorrowable', signed=True, data=params) + return await self._request_papi_api( + "get", "margin/maxBorrowable", signed=True, data=params + ) async def papi_get_margin_max_withdraw(self, **params): - return await self._request_papi_api('get', 'margin/maxWithdraw', signed=True, data=params) + return await self._request_papi_api( + "get", "margin/maxWithdraw", signed=True, data=params + ) async def papi_get_um_position_risk(self, **params): - return await self._request_papi_api('get', 'um/positionRisk', signed=True, data=params) + return await self._request_papi_api( + "get", "um/positionRisk", signed=True, data=params + ) async def papi_get_cm_position_risk(self, **params): - return await self._request_papi_api('get', 'cm/positionRisk', signed=True, data=params) + return await self._request_papi_api( + "get", "cm/positionRisk", signed=True, data=params + ) async def papi_set_um_leverage(self, **params): - return await self._request_papi_api('post', 'um/leverage', signed=True, data=params) - + return await self._request_papi_api( + "post", "um/leverage", signed=True, data=params + ) async def papi_set_cm_leverage(self, **params): - return await self._request_papi_api('post', 'cm/leverage', signed=True, data=params) - + return await self._request_papi_api( + "post", "cm/leverage", signed=True, data=params + ) async def papi_change_um_position_side_dual(self, **params): - return await self._request_papi_api('post', 'um/positionSide/dual', signed=True, data=params) - + return await self._request_papi_api( + "post", "um/positionSide/dual", signed=True, data=params + ) async def papi_get_um_position_side_dual(self, **params): - return await self._request_papi_api('get', 'um/positionSide/dual', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/positionSide/dual", signed=True, data=params + ) async def papi_get_cm_position_side_dual(self, **params): - return await self._request_papi_api('get', 'cm/positionSide/dual', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/positionSide/dual", signed=True, data=params + ) async def papi_get_um_leverage_bracket(self, **params): - return await self._request_papi_api('get', 'um/leverageBracket', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/leverageBracket", signed=True, data=params + ) async def papi_get_cm_leverage_bracket(self, **params): - return await self._request_papi_api('get', 'cm/leverageBracket', signed=True, data=params) + return await self._request_papi_api( + "get", "cm/leverageBracket", signed=True, data=params + ) async def papi_get_um_api_trading_status(self, **params): - return await self._request_papi_api('get', 'um/apiTradingStatus', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/apiTradingStatus", signed=True, data=params + ) async def papi_get_um_comission_rate(self, **params): - return await self._request_papi_api('get', 'um/commissionRate', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/commissionRate", signed=True, data=params + ) async def papi_get_cm_comission_rate(self, **params): - return await self._request_papi_api('get', 'cm/commissionRate', signed=True, data=params) + return await self._request_papi_api( + "get", "cm/commissionRate", signed=True, data=params + ) async def papi_get_margin_margin_loan(self, **params): - return await self._request_papi_api('get', 'margin/marginLoan', signed=True, data=params) + return await self._request_papi_api( + "get", "margin/marginLoan", signed=True, data=params + ) async def papi_get_margin_repay_loan(self, **params): - return await self._request_papi_api('get', 'margin/repayLoan', signed=True, data=params) - + return await self._request_papi_api( + "get", "margin/repayLoan", signed=True, data=params + ) async def papi_get_repay_futures_switch(self, **params): - return await self._request_papi_api('get', 'repay-futures-switch', signed=True, data=params) - + return await self._request_papi_api( + "get", "repay-futures-switch", signed=True, data=params + ) async def papi_repay_futures_switch(self, **params): - return await self._request_papi_api('post', 'repay-futures-switch', signed=True, data=params) - + return await self._request_papi_api( + "post", "repay-futures-switch", signed=True, data=params + ) async def papi_get_margin_interest_history(self, **params): - return await self._request_papi_api('get', 'margin/marginInterestHistory', signed=True, data=params) - + return await self._request_papi_api( + "get", "margin/marginInterestHistory", signed=True, data=params + ) async def papi_repay_futures_negative_balance(self, **params): - return await self._request_papi_api('post', 'repay-futures-negative-balance', signed=True, data=params) - + return await self._request_papi_api( + "post", "repay-futures-negative-balance", signed=True, data=params + ) async def papi_get_portfolio_interest_history(self, **params): - return await self._request_papi_api('get', 'portfolio/interest-history', signed=True, data=params) - + return await self._request_papi_api( + "get", "portfolio/interest-history", signed=True, data=params + ) async def papi_fund_auto_collection(self, **params): - return await self._request_papi_api('post', 'auto-collection', signed=True, data=params) - + return await self._request_papi_api( + "post", "auto-collection", signed=True, data=params + ) async def papi_fund_asset_collection(self, **params): - return await self._request_papi_api('post', 'asset-collection', signed=True, data=params) - + return await self._request_papi_api( + "post", "asset-collection", signed=True, data=params + ) async def papi_bnb_transfer(self, **params): - return await self._request_papi_api('post', 'bnb-transfer', signed=True, data=params) - + return await self._request_papi_api( + "post", "bnb-transfer", signed=True, data=params + ) async def papi_get_um_income_history(self, **params): - return await self._request_papi_api('get', 'um/income', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/income", signed=True, data=params + ) async def papi_get_cm_income_history(self, **params): - return await self._request_papi_api('get', 'cm/income', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/income", signed=True, data=params + ) async def papi_get_um_account(self, **params): - return await self._request_papi_api('get', 'um/account', signed=True, data=params) + return await self._request_papi_api( + "get", "um/account", signed=True, data=params + ) async def papi_get_um_account_v2(self, **params): - return await self._request_papi_api('get', 'um/account', version=2, signed=True, data=params) - + return await self._request_papi_api( + "get", "um/account", version=2, signed=True, data=params + ) async def papi_get_cm_account(self, **params): - return await self._request_papi_api('get', 'cm/account', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/account", signed=True, data=params + ) async def papi_get_um_account_config(self, **params): - return await self._request_papi_api('get', 'um/accountConfig', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/accountConfig", signed=True, data=params + ) async def papi_get_um_symbol_config(self, **params): - return await self._request_papi_api('get', 'um/symbolConfig', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/symbolConfig", signed=True, data=params + ) async def papi_get_um_trade_asyn(self, **params): - return await self._request_papi_api('get', 'um/trade/asyn', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/trade/asyn", signed=True, data=params + ) async def papi_get_um_trade_asyn_id(self, **params): - return await self._request_papi_api('get', 'um/trade/asyn/id', signed=True, data=params) + return await self._request_papi_api( + "get", "um/trade/asyn/id", signed=True, data=params + ) async def papi_get_um_order_asyn(self, **params): - return await self._request_papi_api('get', 'um/order/asyn', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/order/asyn", signed=True, data=params + ) async def papi_get_um_order_asyn_id(self, **params): - return await self._request_papi_api('get', 'um/order/asyn/id', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/order/asyn/id", signed=True, data=params + ) async def papi_get_um_income_asyn(self, **params): - return await self._request_papi_api('get', 'um/income/asyn', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/income/asyn", signed=True, data=params + ) async def papi_get_um_income_asyn_id(self, **params): - return await self._request_papi_api('get', 'um/income/asyn/id', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/income/asyn/id", signed=True, data=params + ) async def papi_ping(self, **params): - return await self._request_papi_api('get', 'ping', signed=False, data=params) + return await self._request_papi_api("get", "ping", signed=False, data=params) # papi trading endpoints @@ -11782,10 +12867,11 @@ async def papi_create_um_order(self, **params): :returns: API response """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return await self._request_papi_api('post', 'um/order', signed=True, data=params) - + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return await self._request_papi_api( + "post", "um/order", signed=True, data=params + ) async def papi_create_um_conditional_order(self, **params): """Place new UM Conditional order. @@ -11795,10 +12881,11 @@ async def papi_create_um_conditional_order(self, **params): :returns: API response """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return await self._request_papi_api('post', 'um/conditional/order', signed=True, data=params) - + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return await self._request_papi_api( + "post", "um/conditional/order", signed=True, data=params + ) async def papi_create_cm_order(self, **params): """Place new CM order. @@ -11808,10 +12895,11 @@ async def papi_create_cm_order(self, **params): :returns: API response """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return await self._request_papi_api('post', 'cm/order', signed=True, data=params) - + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return await self._request_papi_api( + "post", "cm/order", signed=True, data=params + ) async def papi_create_cm_conditional_order(self, **params): """Place new CM Conditional order. @@ -11821,10 +12909,11 @@ async def papi_create_cm_conditional_order(self, **params): :returns: API response """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return await self._request_papi_api('post', 'cm/conditional/order', signed=True, data=params) - + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return await self._request_papi_api( + "post", "cm/conditional/order", signed=True, data=params + ) async def papi_create_margin_order(self, **params): """New Margin Order. @@ -11834,10 +12923,11 @@ async def papi_create_margin_order(self, **params): :returns: API response """ - if 'newClientOrderId' not in params: - params['newClientOrderId'] = self.CONTRACT_ORDER_PREFIX + self.uuid22() - return await self._request_papi_api('post', 'margin/order', signed=True, data=params) - + if "newClientOrderId" not in params: + params["newClientOrderId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22() + return await self._request_papi_api( + "post", "margin/order", signed=True, data=params + ) async def papi_margin_loan(self, **params): """Apply for a margin loan. @@ -11847,8 +12937,9 @@ async def papi_margin_loan(self, **params): :returns: API response """ - return await self._request_papi_api('post', 'marginLoan', signed=True, data=params) - + return await self._request_papi_api( + "post", "marginLoan", signed=True, data=params + ) async def papi_repay_loan(self, **params): """Repay for a margin loan. @@ -11858,8 +12949,9 @@ async def papi_repay_loan(self, **params): :returns: API response """ - return await self._request_papi_api('post', 'repayLoan', signed=True, data=params) - + return await self._request_papi_api( + "post", "repayLoan", signed=True, data=params + ) async def papi_margin_order_oco(self, **params): """Send in a new OCO for a margin account. @@ -11869,8 +12961,9 @@ async def papi_margin_order_oco(self, **params): :returns: API response """ - return await self._request_papi_api('post', 'margin/order/oco', signed=True, data=params) - + return await self._request_papi_api( + "post", "margin/order/oco", signed=True, data=params + ) async def papi_cancel_um_order(self, **params): """Cancel an active UM LIMIT order. @@ -11880,7 +12973,9 @@ async def papi_cancel_um_order(self, **params): :returns: API response """ - return await self._request_papi_api('delete', 'um/order', signed=True, data=params) + return await self._request_papi_api( + "delete", "um/order", signed=True, data=params + ) async def papi_cancel_um_all_open_orders(self, **params): """Cancel an active UM LIMIT order. @@ -11890,8 +12985,9 @@ async def papi_cancel_um_all_open_orders(self, **params): :returns: API response """ - return await self._request_papi_api('delete', 'um/allOpenOrders', signed=True, data=params) - + return await self._request_papi_api( + "delete", "um/allOpenOrders", signed=True, data=params + ) async def papi_cancel_um_conditional_order(self, **params): """Cancel UM Conditional Order. @@ -11901,8 +12997,9 @@ async def papi_cancel_um_conditional_order(self, **params): :returns: API response """ - return await self._request_papi_api('delete', 'um/conditional/order', signed=True, data=params) - + return await self._request_papi_api( + "delete", "um/conditional/order", signed=True, data=params + ) async def papi_cancel_um_conditional_all_open_orders(self, **params): """Cancel All UM Open Conditional Orders. @@ -11912,8 +13009,9 @@ async def papi_cancel_um_conditional_all_open_orders(self, **params): :returns: API response """ - return await self._request_papi_api('delete', 'um/conditional/allOpenOrders', signed=True, data=params) - + return await self._request_papi_api( + "delete", "um/conditional/allOpenOrders", signed=True, data=params + ) async def papi_cancel_cm_order(self, **params): """Cancel an active CM LIMIT order. @@ -11923,7 +13021,9 @@ async def papi_cancel_cm_order(self, **params): :returns: API response """ - return await self._request_papi_api('delete', 'cm/order', signed=True, data=params) + return await self._request_papi_api( + "delete", "cm/order", signed=True, data=params + ) async def papi_cancel_cm_all_open_orders(self, **params): """Cancel an active CM LIMIT order. @@ -11933,7 +13033,9 @@ async def papi_cancel_cm_all_open_orders(self, **params): :returns: API response """ - return await self._request_papi_api('delete', 'cm/allOpenOrders', signed=True, data=params) + return await self._request_papi_api( + "delete", "cm/allOpenOrders", signed=True, data=params + ) async def papi_cancel_cm_conditional_order(self, **params): """Cancel CM Conditional Order. @@ -11943,8 +13045,9 @@ async def papi_cancel_cm_conditional_order(self, **params): :returns: API response """ - return await self._request_papi_api('delete', 'cm/conditional/order', signed=True, data=params) - + return await self._request_papi_api( + "delete", "cm/conditional/order", signed=True, data=params + ) async def papi_cancel_cm_conditional_all_open_orders(self, **params): """Cancel All CM Open Conditional Orders. @@ -11954,8 +13057,9 @@ async def papi_cancel_cm_conditional_all_open_orders(self, **params): :returns: API response """ - return await self._request_papi_api('delete', 'cm/conditional/allOpenOrders', signed=True, data=params) - + return await self._request_papi_api( + "delete", "cm/conditional/allOpenOrders", signed=True, data=params + ) async def papi_cancel_margin_order(self, **params): """Cancel Margin Account Order. @@ -11965,8 +13069,9 @@ async def papi_cancel_margin_order(self, **params): :returns: API response """ - return await self._request_papi_api('delete', 'margin/order', signed=True, data=params) - + return await self._request_papi_api( + "delete", "margin/order", signed=True, data=params + ) async def papi_cancel_margin_order_list(self, **params): """Cancel Margin Account OCO Orders. @@ -11976,8 +13081,9 @@ async def papi_cancel_margin_order_list(self, **params): :returns: API response """ - return await self._request_papi_api('delete', 'margin/orderList', signed=True, data=params) - + return await self._request_papi_api( + "delete", "margin/orderList", signed=True, data=params + ) async def papi_cancel_margin_all_open_orders(self, **params): """Cancel Margin Account All Open Orders on a Symbol. @@ -11987,8 +13093,9 @@ async def papi_cancel_margin_all_open_orders(self, **params): :returns: API response """ - return await self._request_papi_api('delete', 'margin/allOpenOrders', signed=True, data=params) - + return await self._request_papi_api( + "delete", "margin/allOpenOrders", signed=True, data=params + ) async def papi_modify_um_order(self, **params): """Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue. @@ -11998,8 +13105,7 @@ async def papi_modify_um_order(self, **params): :returns: API response """ - return await self._request_papi_api('put', 'um/order', signed=True, data=params) - + return await self._request_papi_api("put", "um/order", signed=True, data=params) async def papi_modify_cm_order(self, **params): """Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue. @@ -12009,7 +13115,7 @@ async def papi_modify_cm_order(self, **params): :returns: API response """ - return await self._request_papi_api('put', 'cm/order', signed=True, data=params) + return await self._request_papi_api("put", "cm/order", signed=True, data=params) async def papi_get_um_order(self, **params): """Check an UM order's status. @@ -12019,8 +13125,7 @@ async def papi_get_um_order(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/order', signed=True, data=params) - + return await self._request_papi_api("get", "um/order", signed=True, data=params) async def papi_get_um_all_orders(self, **params): """Get all account UM orders; active, canceled, or filled. @@ -12030,8 +13135,9 @@ async def papi_get_um_all_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/allOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/allOrders", signed=True, data=params + ) async def papi_get_um_open_order(self, **params): """Query current UM open order. @@ -12041,8 +13147,9 @@ async def papi_get_um_open_order(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/openOrder', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/openOrder", signed=True, data=params + ) async def papi_get_um_open_orders(self, **params): """Get all open orders on a symbol. @@ -12052,8 +13159,9 @@ async def papi_get_um_open_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/openOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/openOrders", signed=True, data=params + ) async def papi_get_um_conditional_all_orders(self, **params): """Query All UM Conditional Orders. @@ -12063,8 +13171,9 @@ async def papi_get_um_conditional_all_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/conditional/allOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/conditional/allOrders", signed=True, data=params + ) async def papi_get_um_conditional_open_orders(self, **params): """Get all open conditional orders on a symbol. @@ -12074,8 +13183,9 @@ async def papi_get_um_conditional_open_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/conditional/openOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/conditional/openOrders", signed=True, data=params + ) async def papi_get_um_conditional_open_order(self, **params): """Query Current UM Open Conditional Order. @@ -12085,8 +13195,9 @@ async def papi_get_um_conditional_open_order(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/conditional/openOrder', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/conditional/openOrder", signed=True, data=params + ) async def papi_get_um_conditional_order_history(self, **params): """Get all open conditional orders on a symbol. @@ -12096,9 +13207,9 @@ async def papi_get_um_conditional_order_history(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/conditional/orderHistory', signed=True, data=params) - - + return await self._request_papi_api( + "get", "um/conditional/orderHistory", signed=True, data=params + ) async def papi_get_cm_order(self, **params): """Check an CM order's status. @@ -12108,8 +13219,7 @@ async def papi_get_cm_order(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/order', signed=True, data=params) - + return await self._request_papi_api("get", "cm/order", signed=True, data=params) async def papi_get_cm_all_orders(self, **params): """Get all account CM orders; active, canceled, or filled. @@ -12119,8 +13229,9 @@ async def papi_get_cm_all_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/allOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/allOrders", signed=True, data=params + ) async def papi_get_cm_open_order(self, **params): """Query current CM open order. @@ -12130,8 +13241,9 @@ async def papi_get_cm_open_order(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/openOrder', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/openOrder", signed=True, data=params + ) async def papi_get_cm_open_orders(self, **params): """Get all open orders on a symbol. @@ -12141,8 +13253,9 @@ async def papi_get_cm_open_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/openOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/openOrders", signed=True, data=params + ) async def papi_get_cm_conditional_all_orders(self, **params): """Query All CM Conditional Orders. @@ -12152,8 +13265,9 @@ async def papi_get_cm_conditional_all_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/conditional/allOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/conditional/allOrders", signed=True, data=params + ) async def papi_get_cm_conditional_open_orders(self, **params): """Get all open conditional orders on a symbol. @@ -12163,8 +13277,9 @@ async def papi_get_cm_conditional_open_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/conditional/openOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/conditional/openOrders", signed=True, data=params + ) async def papi_get_cm_conditional_open_order(self, **params): """Query Current UM Open Conditional Order. @@ -12174,8 +13289,9 @@ async def papi_get_cm_conditional_open_order(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/conditional/openOrder', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/conditional/openOrder", signed=True, data=params + ) async def papi_get_cm_conditional_order_history(self, **params): """Get all open conditional orders on a symbol. @@ -12185,8 +13301,9 @@ async def papi_get_cm_conditional_order_history(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/conditional/orderHistory', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/conditional/orderHistory", signed=True, data=params + ) async def papi_get_um_force_orders(self, **params): """Query User's UM Force Orders. @@ -12196,8 +13313,9 @@ async def papi_get_um_force_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/forceOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/forceOrders", signed=True, data=params + ) async def papi_get_cm_force_orders(self, **params): """Query User's CM Force Orders. @@ -12207,8 +13325,9 @@ async def papi_get_cm_force_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/forceOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/forceOrders", signed=True, data=params + ) async def papi_get_um_order_amendment(self, **params): """Get order modification history. @@ -12218,8 +13337,9 @@ async def papi_get_um_order_amendment(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/orderAmendment', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/orderAmendment", signed=True, data=params + ) async def papi_get_cm_order_amendment(self, **params): """Get order modification history. @@ -12229,8 +13349,9 @@ async def papi_get_cm_order_amendment(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/orderAmendment', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/orderAmendment", signed=True, data=params + ) async def papi_get_margin_force_orders(self, **params): """Query user's margin force orders. @@ -12240,7 +13361,9 @@ async def papi_get_margin_force_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'margin/forceOrders', signed=True, data=params) + return await self._request_papi_api( + "get", "margin/forceOrders", signed=True, data=params + ) async def papi_get_um_user_trades(self, **params): """Get trades for a specific account and UM symbol. @@ -12250,8 +13373,9 @@ async def papi_get_um_user_trades(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/userTrades', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/userTrades", signed=True, data=params + ) async def papi_get_cm_user_trades(self, **params): """Get trades for a specific account and CM symbol. @@ -12261,8 +13385,9 @@ async def papi_get_cm_user_trades(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/userTrades', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/userTrades", signed=True, data=params + ) async def papi_get_um_adl_quantile(self, **params): """Query UM Position ADL Quantile Estimation. @@ -12272,8 +13397,9 @@ async def papi_get_um_adl_quantile(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/adlQuantile', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/adlQuantile", signed=True, data=params + ) async def papi_get_cm_adl_quantile(self, **params): """Query CM Position ADL Quantile Estimation. @@ -12283,8 +13409,9 @@ async def papi_get_cm_adl_quantile(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'cm/adlQuantile', signed=True, data=params) - + return await self._request_papi_api( + "get", "cm/adlQuantile", signed=True, data=params + ) async def papi_set_um_fee_burn(self, **params): """Change user's BNB Fee Discount for UM Futures (Fee Discount On or Fee Discount Off ) on EVERY symbol. @@ -12294,8 +13421,9 @@ async def papi_set_um_fee_burn(self, **params): :returns: API response """ - return await self._request_papi_api('post', 'um/feeBurn', signed=True, data=params) - + return await self._request_papi_api( + "post", "um/feeBurn", signed=True, data=params + ) async def papi_get_um_fee_burn(self, **params): """Get user's BNB Fee Discount for UM Futures (Fee Discount On or Fee Discount Off). @@ -12305,8 +13433,9 @@ async def papi_get_um_fee_burn(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'um/feeBurn', signed=True, data=params) - + return await self._request_papi_api( + "get", "um/feeBurn", signed=True, data=params + ) async def papi_get_margin_order(self, **params): """Query Margin Account Order. @@ -12316,8 +13445,9 @@ async def papi_get_margin_order(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'margin/order', signed=True, data=params) - + return await self._request_papi_api( + "get", "margin/order", signed=True, data=params + ) async def papi_get_margin_open_orders(self, **params): """Query Current Margin Open Order. @@ -12327,8 +13457,9 @@ async def papi_get_margin_open_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'margin/openOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "margin/openOrders", signed=True, data=params + ) async def papi_get_margin_all_orders(self, **params): """Query All Margin Account Orders. @@ -12338,8 +13469,9 @@ async def papi_get_margin_all_orders(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'margin/allOrders', signed=True, data=params) - + return await self._request_papi_api( + "get", "margin/allOrders", signed=True, data=params + ) async def papi_get_margin_order_list(self, **params): """Retrieves a specific OCO based on provided optional parameters. @@ -12349,8 +13481,9 @@ async def papi_get_margin_order_list(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'margin/orderList', signed=True, data=params) - + return await self._request_papi_api( + "get", "margin/orderList", signed=True, data=params + ) async def papi_get_margin_all_order_list(self, **params): """Query all OCO for a specific margin account based on provided optional parameters. @@ -12360,8 +13493,9 @@ async def papi_get_margin_all_order_list(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'margin/allOrderList', signed=True, data=params) - + return await self._request_papi_api( + "get", "margin/allOrderList", signed=True, data=params + ) async def papi_get_margin_open_order_list(self, **params): """Query Margin Account's Open OCO. @@ -12371,8 +13505,9 @@ async def papi_get_margin_open_order_list(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'margin/openOrderList', signed=True, data=params) - + return await self._request_papi_api( + "get", "margin/openOrderList", signed=True, data=params + ) async def papi_get_margin_my_trades(self, **params): """Margin Account Trade List. @@ -12382,8 +13517,9 @@ async def papi_get_margin_my_trades(self, **params): :returns: API response """ - return await self._request_papi_api('get', 'margin/myTrades', signed=True, data=params) - + return await self._request_papi_api( + "get", "margin/myTrades", signed=True, data=params + ) async def papi_get_margin_repay_debt(self, **params): """Repay debt for a margin loan. @@ -12393,4 +13529,6 @@ async def papi_get_margin_repay_debt(self, **params): :returns: API response """ - return await self._request_papi_api('post', 'margin/repay-debt', signed=True, data=params) + return await self._request_papi_api( + "post", "margin/repay-debt", signed=True, data=params + ) diff --git a/binance/depthcache.py b/binance/depthcache.py index 0139bead..bb9b0b3d 100644 --- a/binance/depthcache.py +++ b/binance/depthcache.py @@ -10,7 +10,6 @@ class DepthCache(object): - def __init__(self, symbol, conv_type: Callable = float): """Initialise the DepthCache @@ -113,27 +112,42 @@ def get_asks(self): ] """ - return DepthCache.sort_depth(self._asks, reverse=False, conv_type=self.conv_type) + return DepthCache.sort_depth( + self._asks, reverse=False, conv_type=self.conv_type + ) @staticmethod def sort_depth(vals, reverse=False, conv_type: Callable = float): - """Sort bids or asks by price - """ + """Sort bids or asks by price""" if isinstance(vals, dict): - lst = [[conv_type(price), conv_type(quantity)] for price, quantity in vals.items()] + lst = [ + [conv_type(price), conv_type(quantity)] + for price, quantity in vals.items() + ] elif isinstance(vals, list): lst = [[conv_type(price), conv_type(quantity)] for price, quantity in vals] else: - raise ValueError(f'Unknown order book depth data type: {type(vals)}') + raise ValueError(f"Unknown order book depth data type: {type(vals)}") lst = sorted(lst, key=itemgetter(0), reverse=reverse) return lst + DEFAULT_REFRESH = 60 * 30 # 30 minutes + class BaseDepthCacheManager: TIMEOUT = 60 - def __init__(self, client, symbol, loop=None, refresh_interval: Optional[int] = DEFAULT_REFRESH, bm=None, limit=10, conv_type=float): + def __init__( + self, + client, + symbol, + loop=None, + refresh_interval: Optional[int] = DEFAULT_REFRESH, + bm=None, + limit=10, + conv_type=float, + ): """Create a DepthCacheManager instance :param client: Binance API client @@ -166,10 +180,7 @@ def __init__(self, client, symbol, loop=None, refresh_interval: Optional[int] = self._log = logging.getLogger(__name__) async def __aenter__(self): - await asyncio.gather( - self._init_cache(), - self._start_socket() - ) + await asyncio.gather(self._init_cache(), self._start_socket()) await self._socket.__aenter__() return self @@ -221,7 +232,7 @@ async def _depth_event(self, msg): if not msg: return None - if 'e' in msg and msg['e'] == 'error': + if "e" in msg and msg["e"] == "error": # close the socket await self.close() @@ -252,13 +263,13 @@ async def _process_depth_message(self, msg): def _apply_orders(self, msg): assert self._depth_cache - for bid in msg.get('b', []) + msg.get('bids', []): + for bid in msg.get("b", []) + msg.get("bids", []): self._depth_cache.add_bid(bid) - for ask in msg.get('a', []) + msg.get('asks', []): + for ask in msg.get("a", []) + msg.get("asks", []): self._depth_cache.add_ask(ask) # keeping update time - self._depth_cache.update_time = msg.get('E') or msg.get('lastUpdateId') + self._depth_cache.update_time = msg.get("E") or msg.get("lastUpdateId") def get_depth_cache(self): """Get the current depth cache @@ -284,9 +295,16 @@ def get_symbol(self): class DepthCacheManager(BaseDepthCacheManager): - def __init__( - self, client, symbol, loop=None, refresh_interval: Optional[int] = None, bm=None, limit=500, conv_type=float, ws_interval=None + self, + client, + symbol, + loop=None, + refresh_interval: Optional[int] = None, + bm=None, + limit=500, + conv_type=float, + ws_interval=None, ): """Initialise the DepthCacheManager @@ -324,13 +342,13 @@ async def _init_cache(self): # process bid and asks from the order book self._apply_orders(res) assert self._depth_cache - for bid in res['bids']: + for bid in res["bids"]: self._depth_cache.add_bid(bid) - for ask in res['asks']: + for ask in res["asks"]: self._depth_cache.add_ask(ask) # set first update id - self._last_update_id = res['lastUpdateId'] + self._last_update_id = res["lastUpdateId"] # Apply any updates from the websocket for msg in self._depth_message_buffer: @@ -344,7 +362,7 @@ async def _start_socket(self): :return: """ - if not getattr(self, '_depth_message_buffer', None): + if not getattr(self, "_depth_message_buffer", None): self._depth_message_buffer = [] await super()._start_socket() @@ -365,10 +383,10 @@ async def _process_depth_message(self, msg): self._depth_message_buffer.append(msg) return - if msg['u'] <= self._last_update_id: + if msg["u"] <= self._last_update_id: # ignore any updates before the initial update id return - elif msg['U'] != self._last_update_id + 1: + elif msg["U"] != self._last_update_id + 1: # if not buffered check we get sequential updates # otherwise init cache again await self._init_cache() @@ -379,7 +397,7 @@ async def _process_depth_message(self, msg): # call the callback with the updated depth cache res = self._depth_cache - self._last_update_id = msg['u'] + self._last_update_id = msg["u"] # after processing event see if we need to refresh the depth cache if self._refresh_interval and int(time.time()) > self._refresh_time: @@ -396,16 +414,16 @@ async def _process_depth_message(self, msg): :return: """ - msg = msg.get('data') + msg = msg.get("data") return await super()._process_depth_message(msg) def _apply_orders(self, msg): assert self._depth_cache - self._depth_cache._bids = msg.get('b', []) - self._depth_cache._asks = msg.get('a', []) + self._depth_cache._bids = msg.get("b", []) + self._depth_cache._asks = msg.get("a", []) # keeping update time - self._depth_cache.update_time = msg.get('E') or msg.get('lastUpdateId') + self._depth_cache.update_time = msg.get("E") or msg.get("lastUpdateId") def _get_socket(self): sock = self._bm.futures_depth_socket(self._symbol) @@ -413,25 +431,32 @@ def _get_socket(self): class OptionsDepthCacheManager(BaseDepthCacheManager): - def _get_socket(self): return self._bm.options_depth_socket(self._symbol) class ThreadedDepthCacheManager(ThreadedApiManager): - def __init__( - self, api_key: Optional[str] = None, api_secret: Optional[str] = None, - requests_params: Optional[Dict[str, str]] = None, tld: str = 'com', - testnet: bool = False + self, + api_key: Optional[str] = None, + api_secret: Optional[str] = None, + requests_params: Optional[Dict[str, str]] = None, + tld: str = "com", + testnet: bool = False, ): super().__init__(api_key, api_secret, requests_params, tld, testnet) def _start_depth_cache( - self, dcm_class, callback: Callable, symbol: str, - refresh_interval=None, bm=None, limit=10, conv_type=float, **kwargs + self, + dcm_class, + callback: Callable, + symbol: str, + refresh_interval=None, + bm=None, + limit=10, + conv_type=float, + **kwargs, ) -> str: - while not self._client: time.sleep(0.01) @@ -443,15 +468,24 @@ def _start_depth_cache( bm=bm, limit=limit, conv_type=conv_type, - **kwargs + **kwargs, ) - path = symbol.lower() + '@depth' + str(limit) + path = symbol.lower() + "@depth" + str(limit) self._socket_running[path] = True - self._loop.call_soon(asyncio.create_task, self.start_listener(dcm, path, callback)) + self._loop.call_soon( + asyncio.create_task, self.start_listener(dcm, path, callback) + ) return path def start_depth_cache( - self, callback: Callable, symbol: str, refresh_interval=None, bm=None, limit=10, conv_type=float, ws_interval=0 + self, + callback: Callable, + symbol: str, + refresh_interval=None, + bm=None, + limit=10, + conv_type=float, + ws_interval=0, ) -> str: return self._start_depth_cache( dcm_class=DepthCacheManager, @@ -461,11 +495,17 @@ def start_depth_cache( bm=bm, limit=limit, conv_type=conv_type, - ws_interval=ws_interval + ws_interval=ws_interval, ) def start_futures_depth_socket( - self, callback: Callable, symbol: str, refresh_interval=None, bm=None, limit=10, conv_type=float + self, + callback: Callable, + symbol: str, + refresh_interval=None, + bm=None, + limit=10, + conv_type=float, ) -> str: return self._start_depth_cache( dcm_class=FuturesDepthCacheManager, @@ -474,11 +514,17 @@ def start_futures_depth_socket( refresh_interval=refresh_interval, bm=bm, limit=limit, - conv_type=conv_type + conv_type=conv_type, ) def start_options_depth_socket( - self, callback: Callable, symbol: str, refresh_interval=None, bm=None, limit=10, conv_type=float + self, + callback: Callable, + symbol: str, + refresh_interval=None, + bm=None, + limit=10, + conv_type=float, ) -> str: return self._start_depth_cache( dcm_class=OptionsDepthCacheManager, @@ -487,5 +533,5 @@ def start_options_depth_socket( refresh_interval=refresh_interval, bm=bm, limit=limit, - conv_type=conv_type + conv_type=conv_type, ) diff --git a/binance/enums.py b/binance/enums.py index 18981b8e..164e94a0 100644 --- a/binance/enums.py +++ b/binance/enums.py @@ -1,68 +1,68 @@ from enum import Enum -SYMBOL_TYPE_SPOT = 'SPOT' - -ORDER_STATUS_NEW = 'NEW' -ORDER_STATUS_PARTIALLY_FILLED = 'PARTIALLY_FILLED' -ORDER_STATUS_FILLED = 'FILLED' -ORDER_STATUS_CANCELED = 'CANCELED' -ORDER_STATUS_PENDING_CANCEL = 'PENDING_CANCEL' -ORDER_STATUS_REJECTED = 'REJECTED' -ORDER_STATUS_EXPIRED = 'EXPIRED' - -KLINE_INTERVAL_1SECOND = '1s' -KLINE_INTERVAL_1MINUTE = '1m' -KLINE_INTERVAL_3MINUTE = '3m' -KLINE_INTERVAL_5MINUTE = '5m' -KLINE_INTERVAL_15MINUTE = '15m' -KLINE_INTERVAL_30MINUTE = '30m' -KLINE_INTERVAL_1HOUR = '1h' -KLINE_INTERVAL_2HOUR = '2h' -KLINE_INTERVAL_4HOUR = '4h' -KLINE_INTERVAL_6HOUR = '6h' -KLINE_INTERVAL_8HOUR = '8h' -KLINE_INTERVAL_12HOUR = '12h' -KLINE_INTERVAL_1DAY = '1d' -KLINE_INTERVAL_3DAY = '3d' -KLINE_INTERVAL_1WEEK = '1w' -KLINE_INTERVAL_1MONTH = '1M' - -SIDE_BUY = 'BUY' -SIDE_SELL = 'SELL' - -ORDER_TYPE_LIMIT = 'LIMIT' -ORDER_TYPE_MARKET = 'MARKET' -ORDER_TYPE_STOP_LOSS = 'STOP_LOSS' -ORDER_TYPE_STOP_LOSS_LIMIT = 'STOP_LOSS_LIMIT' -ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT' -ORDER_TYPE_TAKE_PROFIT_LIMIT = 'TAKE_PROFIT_LIMIT' -ORDER_TYPE_LIMIT_MAKER = 'LIMIT_MAKER' - -FUTURE_ORDER_TYPE_LIMIT = 'LIMIT' -FUTURE_ORDER_TYPE_MARKET = 'MARKET' -FUTURE_ORDER_TYPE_STOP = 'STOP' -FUTURE_ORDER_TYPE_STOP_MARKET = 'STOP_MARKET' -FUTURE_ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT' -FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET = 'TAKE_PROFIT_MARKET' -FUTURE_ORDER_TYPE_LIMIT_MAKER = 'LIMIT_MAKER' -FUTURE_ORDER_TYPE_TRAILING_STOP_MARKET = 'TRAILING_STOP_MARKET' - -TIME_IN_FORCE_GTC = 'GTC' # Good till cancelled -TIME_IN_FORCE_IOC = 'IOC' # Immediate or cancel -TIME_IN_FORCE_FOK = 'FOK' # Fill or kill -TIME_IN_FORCE_GTX = 'GTX' # Post only order - -ORDER_RESP_TYPE_ACK = 'ACK' -ORDER_RESP_TYPE_RESULT = 'RESULT' -ORDER_RESP_TYPE_FULL = 'FULL' - -WEBSOCKET_DEPTH_5 = '5' -WEBSOCKET_DEPTH_10 = '10' -WEBSOCKET_DEPTH_20 = '20' - -NO_SIDE_EFFECT_TYPE = 'NO_SIDE_EFFECT' -MARGIN_BUY_TYPE = 'MARGIN_BUY' -AUTO_REPAY_TYPE = 'AUTO_REPAY' +SYMBOL_TYPE_SPOT = "SPOT" + +ORDER_STATUS_NEW = "NEW" +ORDER_STATUS_PARTIALLY_FILLED = "PARTIALLY_FILLED" +ORDER_STATUS_FILLED = "FILLED" +ORDER_STATUS_CANCELED = "CANCELED" +ORDER_STATUS_PENDING_CANCEL = "PENDING_CANCEL" +ORDER_STATUS_REJECTED = "REJECTED" +ORDER_STATUS_EXPIRED = "EXPIRED" + +KLINE_INTERVAL_1SECOND = "1s" +KLINE_INTERVAL_1MINUTE = "1m" +KLINE_INTERVAL_3MINUTE = "3m" +KLINE_INTERVAL_5MINUTE = "5m" +KLINE_INTERVAL_15MINUTE = "15m" +KLINE_INTERVAL_30MINUTE = "30m" +KLINE_INTERVAL_1HOUR = "1h" +KLINE_INTERVAL_2HOUR = "2h" +KLINE_INTERVAL_4HOUR = "4h" +KLINE_INTERVAL_6HOUR = "6h" +KLINE_INTERVAL_8HOUR = "8h" +KLINE_INTERVAL_12HOUR = "12h" +KLINE_INTERVAL_1DAY = "1d" +KLINE_INTERVAL_3DAY = "3d" +KLINE_INTERVAL_1WEEK = "1w" +KLINE_INTERVAL_1MONTH = "1M" + +SIDE_BUY = "BUY" +SIDE_SELL = "SELL" + +ORDER_TYPE_LIMIT = "LIMIT" +ORDER_TYPE_MARKET = "MARKET" +ORDER_TYPE_STOP_LOSS = "STOP_LOSS" +ORDER_TYPE_STOP_LOSS_LIMIT = "STOP_LOSS_LIMIT" +ORDER_TYPE_TAKE_PROFIT = "TAKE_PROFIT" +ORDER_TYPE_TAKE_PROFIT_LIMIT = "TAKE_PROFIT_LIMIT" +ORDER_TYPE_LIMIT_MAKER = "LIMIT_MAKER" + +FUTURE_ORDER_TYPE_LIMIT = "LIMIT" +FUTURE_ORDER_TYPE_MARKET = "MARKET" +FUTURE_ORDER_TYPE_STOP = "STOP" +FUTURE_ORDER_TYPE_STOP_MARKET = "STOP_MARKET" +FUTURE_ORDER_TYPE_TAKE_PROFIT = "TAKE_PROFIT" +FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET = "TAKE_PROFIT_MARKET" +FUTURE_ORDER_TYPE_LIMIT_MAKER = "LIMIT_MAKER" +FUTURE_ORDER_TYPE_TRAILING_STOP_MARKET = "TRAILING_STOP_MARKET" + +TIME_IN_FORCE_GTC = "GTC" # Good till cancelled +TIME_IN_FORCE_IOC = "IOC" # Immediate or cancel +TIME_IN_FORCE_FOK = "FOK" # Fill or kill +TIME_IN_FORCE_GTX = "GTX" # Post only order + +ORDER_RESP_TYPE_ACK = "ACK" +ORDER_RESP_TYPE_RESULT = "RESULT" +ORDER_RESP_TYPE_FULL = "FULL" + +WEBSOCKET_DEPTH_5 = "5" +WEBSOCKET_DEPTH_10 = "10" +WEBSOCKET_DEPTH_20 = "20" + +NO_SIDE_EFFECT_TYPE = "NO_SIDE_EFFECT" +MARGIN_BUY_TYPE = "MARGIN_BUY" +AUTO_REPAY_TYPE = "AUTO_REPAY" class HistoricalKlinesType(Enum): diff --git a/binance/exceptions.py b/binance/exceptions.py index 9a3fd313..62fcefb9 100644 --- a/binance/exceptions.py +++ b/binance/exceptions.py @@ -3,22 +3,23 @@ class BinanceAPIException(Exception): - def __init__(self, response, status_code, text): self.code = 0 try: json_res = json.loads(text) except ValueError: - self.message = 'Invalid JSON error message from Binance: {}'.format(response.text) + self.message = "Invalid JSON error message from Binance: {}".format( + response.text + ) else: - self.code = json_res.get('code') - self.message = json_res.get('msg') + self.code = json_res.get("code") + self.message = json_res.get("msg") self.status_code = status_code self.response = response - self.request = getattr(response, 'request', None) + self.request = getattr(response, "request", None) def __str__(self): # pragma: no cover - return 'APIError(code=%s): %s' % (self.code, self.message) + return "APIError(code=%s): %s" % (self.code, self.message) class BinanceRequestException(Exception): @@ -26,49 +27,43 @@ def __init__(self, message): self.message = message def __str__(self): - return 'BinanceRequestException: %s' % self.message + return "BinanceRequestException: %s" % self.message class BinanceOrderException(Exception): - def __init__(self, code, message): self.code = code self.message = message def __str__(self): - return 'BinanceOrderException(code=%s): %s' % (self.code, self.message) + return "BinanceOrderException(code=%s): %s" % (self.code, self.message) class BinanceOrderMinAmountException(BinanceOrderException): - def __init__(self, value): message = "Amount must be a multiple of %s" % value super().__init__(-1013, message) class BinanceOrderMinPriceException(BinanceOrderException): - def __init__(self, value): message = "Price must be at least %s" % value super().__init__(-1013, message) class BinanceOrderMinTotalException(BinanceOrderException): - def __init__(self, value): message = "Total must be at least %s" % value super().__init__(-1013, message) class BinanceOrderUnknownSymbolException(BinanceOrderException): - def __init__(self, value): message = "Unknown symbol %s" % value super().__init__(-1013, message) class BinanceOrderInactiveSymbolException(BinanceOrderException): - def __init__(self, value): message = "Attempting to trade an inactive symbol %s" % value super().__init__(-1013, message) @@ -80,7 +75,7 @@ class BinanceWebsocketUnableToConnect(Exception): class NotImplementedException(Exception): def __init__(self, value): - message = f'Not implemented: {value}' + message = f"Not implemented: {value}" super().__init__(message) diff --git a/binance/helpers.py b/binance/helpers.py index 5c6515ea..4fc7676e 100644 --- a/binance/helpers.py +++ b/binance/helpers.py @@ -58,7 +58,9 @@ def interval_to_milliseconds(interval: str) -> Optional[int]: return None -def round_step_size(quantity: Union[float, Decimal], step_size: Union[float, Decimal]) -> float: +def round_step_size( + quantity: Union[float, Decimal], step_size: Union[float, Decimal] +) -> float: """Rounds a given quantity to a specific step size :param quantity: required diff --git a/binance/streams.py b/binance/streams.py index e8947d50..404b4fa4 100755 --- a/binance/streams.py +++ b/binance/streams.py @@ -23,18 +23,18 @@ class WSListenerState(Enum): - INITIALISING = 'Initialising' - STREAMING = 'Streaming' - RECONNECTING = 'Reconnecting' - EXITING = 'Exiting' + INITIALISING = "Initialising" + STREAMING = "Streaming" + RECONNECTING = "Reconnecting" + EXITING = "Exiting" class BinanceSocketType(str, Enum): - SPOT = 'Spot' - USD_M_FUTURES = 'USD_M_Futures' - COIN_M_FUTURES = 'Coin_M_Futures' - OPTIONS = 'Vanilla_Options' - ACCOUNT = 'Account' + SPOT = "Spot" + USD_M_FUTURES = "USD_M_Futures" + COIN_M_FUTURES = "Coin_M_Futures" + OPTIONS = "Vanilla_Options" + ACCOUNT = "Account" class ReconnectingWebsocket: @@ -46,7 +46,13 @@ class ReconnectingWebsocket: MAX_QUEUE_SIZE = 100 def __init__( - self, url: str, path: Optional[str] = None, prefix: str = 'ws/', is_binary: bool = False, exit_coro=None, **kwargs + self, + url: str, + path: Optional[str] = None, + prefix: str = "ws/", + is_binary: bool = False, + exit_coro=None, + **kwargs, ): self._loop = get_loop() self._log = logging.getLogger(__name__) @@ -74,7 +80,7 @@ async def __aexit__(self, exc_type, exc_val, exc_tb): self.ws_state = WSListenerState.EXITING if self.ws: self.ws.fail_connection() - if self._conn and hasattr(self._conn, 'protocol'): + if self._conn and hasattr(self._conn, "protocol"): await self._conn.__aexit__(exc_type, exc_val, exc_tb) self.ws = None if not self._handle_read_loop: @@ -96,7 +102,9 @@ async def connect(self): await self._after_connect() # To manage the "cannot call recv while another coroutine is already waiting for the next message" if not self._handle_read_loop: - self._handle_read_loop = self._loop.call_soon_threadsafe(asyncio.create_task, self._read_loop()) + self._handle_read_loop = self._loop.call_soon_threadsafe( + asyncio.create_task, self._read_loop() + ) async def _kill_read_loop(self): self.ws_state = WSListenerState.EXITING @@ -118,7 +126,7 @@ def _handle_message(self, evt): try: return json.loads(evt) except ValueError: - self._log.debug(f'error parsing evt json:{evt}') + self._log.debug(f"error parsing evt json:{evt}") return None async def _read_loop(self): @@ -129,7 +137,9 @@ async def _read_loop(self): await self._run_reconnect() if self.ws_state == WSListenerState.EXITING: - self._log.debug(f"_read_loop {self._path} break for {self.ws_state}") + self._log.debug( + f"_read_loop {self._path} break for {self.ws_state}" + ) break elif self.ws.state == ws.protocol.State.CLOSING: # type: ignore await asyncio.sleep(0.1) @@ -138,17 +148,23 @@ async def _read_loop(self): await self._reconnect() elif self.ws_state == WSListenerState.STREAMING: assert self.ws - res = await asyncio.wait_for(self.ws.recv(), timeout=self.TIMEOUT) + res = await asyncio.wait_for( + self.ws.recv(), timeout=self.TIMEOUT + ) res = self._handle_message(res) if res: if self._queue.qsize() < self.MAX_QUEUE_SIZE: await self._queue.put(res) else: - self._log.debug(f"Queue overflow {self.MAX_QUEUE_SIZE}. Message not filled") - await self._queue.put({ - 'e': 'error', - 'm': 'Queue overflow. Message not filled' - }) + self._log.debug( + f"Queue overflow {self.MAX_QUEUE_SIZE}. Message not filled" + ) + await self._queue.put( + { + "e": "error", + "m": "Queue overflow. Message not filled", + } + ) raise BinanceWebsocketUnableToConnect except asyncio.TimeoutError: self._log.debug(f"no message in {self.TIMEOUT} seconds") @@ -183,12 +199,9 @@ async def _run_reconnect(self): await asyncio.sleep(reconnect_wait) await self.connect() else: - self._log.error(f'Max reconnections {self.MAX_RECONNECTS} reached:') + self._log.error(f"Max reconnections {self.MAX_RECONNECTS} reached:") # Signal the error - await self._queue.put({ - 'e': 'error', - 'm': 'Max reconnect retries reached' - }) + await self._queue.put({"e": "error", "m": "Max reconnect retries reached"}) raise BinanceWebsocketUnableToConnect async def recv(self): @@ -201,24 +214,27 @@ async def recv(self): return res async def _wait_for_reconnect(self): - while self.ws_state != WSListenerState.STREAMING and self.ws_state != WSListenerState.EXITING: + while ( + self.ws_state != WSListenerState.STREAMING + and self.ws_state != WSListenerState.EXITING + ): await sleep(0.1) def _get_reconnect_wait(self, attempts: int) -> int: - expo = 2 ** attempts + expo = 2**attempts return round(random() * min(self.MAX_RECONNECT_SECONDS, expo - 1) + 1) async def before_reconnect(self): if self.ws: self.ws = None - if self._conn and hasattr(self._conn, 'protocol'): + if self._conn and hasattr(self._conn, "protocol"): await self._conn.__aexit__(None, None, None) self._reconnects += 1 def _no_message_received_reconnect(self): - self._log.debug('No message received, reconnecting') + self._log.debug("No message received, reconnecting") self.ws_state = WSListenerState.RECONNECTING async def _reconnect(self): @@ -226,12 +242,25 @@ async def _reconnect(self): class KeepAliveWebsocket(ReconnectingWebsocket): - def __init__( - self, client: AsyncClient, url, keepalive_type, prefix='ws/', is_binary=False, exit_coro=None, - user_timeout=None, **kwargs + self, + client: AsyncClient, + url, + keepalive_type, + prefix="ws/", + is_binary=False, + exit_coro=None, + user_timeout=None, + **kwargs, ): - super().__init__(path=None, url=url, prefix=prefix, is_binary=is_binary, exit_coro=exit_coro, **kwargs) + super().__init__( + path=None, + url=url, + prefix=prefix, + is_binary=is_binary, + exit_coro=exit_coro, + **kwargs, + ) self._keepalive_type = keepalive_type self._client = client self._user_timeout = user_timeout or KEEPALIVE_TIMEOUT @@ -254,22 +283,23 @@ async def _after_connect(self): def _start_socket_timer(self): self._timer = self._loop.call_later( - self._user_timeout, - lambda: asyncio.create_task(self._keepalive_socket()) + self._user_timeout, lambda: asyncio.create_task(self._keepalive_socket()) ) async def _get_listen_key(self): - if self._keepalive_type == 'user': + if self._keepalive_type == "user": listen_key = await self._client.stream_get_listen_key() - elif self._keepalive_type == 'margin': # cross-margin + elif self._keepalive_type == "margin": # cross-margin listen_key = await self._client.margin_stream_get_listen_key() - elif self._keepalive_type == 'futures': + elif self._keepalive_type == "futures": listen_key = await self._client.futures_stream_get_listen_key() - elif self._keepalive_type == 'coin_futures': + elif self._keepalive_type == "coin_futures": listen_key = await self._client.futures_coin_stream_get_listen_key() else: # isolated margin # Passing symbol for isolated margin - listen_key = await self._client.isolated_margin_stream_get_listen_key(self._keepalive_type) + listen_key = await self._client.isolated_margin_stream_get_listen_key( + self._keepalive_type + ) return listen_key async def _keepalive_socket(self): @@ -281,17 +311,19 @@ async def _keepalive_socket(self): await self._reconnect() else: self._log.debug("listen key same: keepalive") - if self._keepalive_type == 'user': + if self._keepalive_type == "user": await self._client.stream_keepalive(self._path) - elif self._keepalive_type == 'margin': # cross-margin + elif self._keepalive_type == "margin": # cross-margin await self._client.margin_stream_keepalive(self._path) - elif self._keepalive_type == 'futures': + elif self._keepalive_type == "futures": await self._client.futures_stream_keepalive(self._path) - elif self._keepalive_type == 'coin_futures': + elif self._keepalive_type == "coin_futures": await self._client.futures_coin_stream_keepalive(self._path) else: # isolated margin # Passing symbol for isolated margin - await self._client.isolated_margin_stream_keepalive(self._keepalive_type, self._path) + await self._client.isolated_margin_stream_keepalive( + self._keepalive_type, self._path + ) except Exception: pass # Ignore finally: @@ -299,18 +331,18 @@ async def _keepalive_socket(self): class BinanceSocketManager: - STREAM_URL = 'wss://stream.binance.{}:9443/' - STREAM_TESTNET_URL = 'wss://testnet.binance.vision/' - FSTREAM_URL = 'wss://fstream.binance.{}/' - FSTREAM_TESTNET_URL = 'wss://stream.binancefuture.com/' - DSTREAM_URL = 'wss://dstream.binance.{}/' - DSTREAM_TESTNET_URL = 'wss://dstream.binancefuture.com/' - VSTREAM_URL = 'wss://vstream.binance.{}/' - VSTREAM_TESTNET_URL = 'wss://testnetws.binanceops.{}/' - - WEBSOCKET_DEPTH_5 = '5' - WEBSOCKET_DEPTH_10 = '10' - WEBSOCKET_DEPTH_20 = '20' + STREAM_URL = "wss://stream.binance.{}:9443/" + STREAM_TESTNET_URL = "wss://testnet.binance.vision/" + FSTREAM_URL = "wss://fstream.binance.{}/" + FSTREAM_TESTNET_URL = "wss://stream.binancefuture.com/" + DSTREAM_URL = "wss://dstream.binance.{}/" + DSTREAM_TESTNET_URL = "wss://dstream.binancefuture.com/" + VSTREAM_URL = "wss://vstream.binance.{}/" + VSTREAM_TESTNET_URL = "wss://testnetws.binanceops.{}/" + + WEBSOCKET_DEPTH_5 = "5" + WEBSOCKET_DEPTH_10 = "10" + WEBSOCKET_DEPTH_20 = "20" def __init__(self, client: AsyncClient, user_timeout=KEEPALIVE_TIMEOUT): """Initialise the BinanceSocketManager @@ -342,26 +374,34 @@ def _get_stream_url(self, stream_url: Optional[str] = None): return stream_url def _get_socket( - self, path: str, stream_url: Optional[str] = None, prefix: str = 'ws/', is_binary: bool = False, - socket_type: BinanceSocketType = BinanceSocketType.SPOT + self, + path: str, + stream_url: Optional[str] = None, + prefix: str = "ws/", + is_binary: bool = False, + socket_type: BinanceSocketType = BinanceSocketType.SPOT, ) -> ReconnectingWebsocket: - conn_id = f'{socket_type}_{path}' + conn_id = f"{socket_type}_{path}" if conn_id not in self._conns: self._conns[conn_id] = ReconnectingWebsocket( path=path, url=self._get_stream_url(stream_url), prefix=prefix, - exit_coro=lambda p: self._exit_socket(f'{socket_type}_{p}'), + exit_coro=lambda p: self._exit_socket(f"{socket_type}_{p}"), is_binary=is_binary, - **self.ws_kwargs + **self.ws_kwargs, ) return self._conns[conn_id] def _get_account_socket( - self, path: str, stream_url: Optional[str] = None, prefix: str = 'ws/', is_binary: bool = False + self, + path: str, + stream_url: Optional[str] = None, + prefix: str = "ws/", + is_binary: bool = False, ): - conn_id = f'{BinanceSocketType.ACCOUNT}_{path}' + conn_id = f"{BinanceSocketType.ACCOUNT}_{path}" if conn_id not in self._conns: self._conns[conn_id] = KeepAliveWebsocket( client=self._client, @@ -371,12 +411,14 @@ def _get_account_socket( exit_coro=self._exit_socket, is_binary=is_binary, user_timeout=self._user_timeout, - **self.ws_kwargs + **self.ws_kwargs, ) return self._conns[conn_id] - def _get_futures_socket(self, path: str, futures_type: FuturesType, prefix: str = 'stream?streams='): + def _get_futures_socket( + self, path: str, futures_type: FuturesType, prefix: str = "stream?streams=" + ): socket_type: BinanceSocketType = BinanceSocketType.USD_M_FUTURES if futures_type == FuturesType.USD_M: stream_url = self.FSTREAM_URL @@ -388,16 +430,24 @@ def _get_futures_socket(self, path: str, futures_type: FuturesType, prefix: str stream_url = self.DSTREAM_TESTNET_URL return self._get_socket(path, stream_url, prefix, socket_type=socket_type) - def _get_options_socket(self, path: str, prefix: str = 'ws/'): + def _get_options_socket(self, path: str, prefix: str = "ws/"): stream_url = self.VSTREAM_URL if self.testnet: stream_url = self.VSTREAM_TESTNET_URL - return self._get_socket(path, stream_url, prefix, is_binary=True, socket_type=BinanceSocketType.OPTIONS) + return self._get_socket( + path, + stream_url, + prefix, + is_binary=True, + socket_type=BinanceSocketType.OPTIONS, + ) async def _exit_socket(self, path: str): await self._stop_socket(path) - def depth_socket(self, symbol: str, depth: Optional[str] = None, interval: Optional[int] = None): + def depth_socket( + self, symbol: str, depth: Optional[str] = None, interval: Optional[int] = None + ): """Start a websocket for symbol market depth returning either a diff or a partial book https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#partial-book-depth-streams @@ -461,14 +511,16 @@ def depth_socket(self, symbol: str, depth: Optional[str] = None, interval: Optio } """ - socket_name = symbol.lower() + '@depth' - if depth and depth != '1': - socket_name = f'{socket_name}{depth}' + socket_name = symbol.lower() + "@depth" + if depth and depth != "1": + socket_name = f"{socket_name}{depth}" if interval: if interval in [0, 100]: - socket_name = f'{socket_name}@{interval}ms' + socket_name = f"{socket_name}@{interval}ms" else: - raise ValueError("Websocket interval value not allowed. Allowed values are [0, 100]") + raise ValueError( + "Websocket interval value not allowed. Allowed values are [0, 100]" + ) return self._get_socket(socket_name) def kline_socket(self, symbol: str, interval=AsyncClient.KLINE_INTERVAL_1MINUTE): @@ -512,12 +564,16 @@ def kline_socket(self, symbol: str, interval=AsyncClient.KLINE_INTERVAL_1MINUTE) } } """ - path = f'{symbol.lower()}@kline_{interval}' + path = f"{symbol.lower()}@kline_{interval}" return self._get_socket(path) - def kline_futures_socket(self, symbol: str, interval=AsyncClient.KLINE_INTERVAL_1MINUTE, - futures_type: FuturesType = FuturesType.USD_M, - contract_type: ContractType = ContractType.PERPETUAL): + def kline_futures_socket( + self, + symbol: str, + interval=AsyncClient.KLINE_INTERVAL_1MINUTE, + futures_type: FuturesType = FuturesType.USD_M, + contract_type: ContractType = ContractType.PERPETUAL, + ): """Start a websocket for symbol kline data for the perpeual futures stream https://binance-docs.github.io/apidocs/futures/en/#continuous-contract-kline-candlestick-streams @@ -562,8 +618,8 @@ def kline_futures_socket(self, symbol: str, interval=AsyncClient.KLINE_INTERVAL_ _@continuousKline_ """ - path = f'{symbol.lower()}_{contract_type.value}@continuousKline_{interval}' - return self._get_futures_socket(path, prefix='ws/', futures_type=futures_type) + path = f"{symbol.lower()}_{contract_type.value}@continuousKline_{interval}" + return self._get_futures_socket(path, prefix="ws/", futures_type=futures_type) def miniticker_socket(self, update_time: int = 1000): """Start a miniticker websocket for all trades @@ -595,7 +651,7 @@ def miniticker_socket(self, update_time: int = 1000): ] """ - return self._get_socket(f'!miniTicker@arr@{update_time}ms') + return self._get_socket(f"!miniTicker@arr@{update_time}ms") def trade_socket(self, symbol: str): """Start a websocket for symbol trade data @@ -627,7 +683,7 @@ def trade_socket(self, symbol: str): """ - return self._get_socket(symbol.lower() + '@trade') + return self._get_socket(symbol.lower() + "@trade") def aggtrade_socket(self, symbol: str): """Start a websocket for symbol trade data @@ -658,9 +714,11 @@ def aggtrade_socket(self, symbol: str): } """ - return self._get_socket(symbol.lower() + '@aggTrade') + return self._get_socket(symbol.lower() + "@aggTrade") - def aggtrade_futures_socket(self, symbol: str, futures_type: FuturesType = FuturesType.USD_M): + def aggtrade_futures_socket( + self, symbol: str, futures_type: FuturesType = FuturesType.USD_M + ): """Start a websocket for aggregate symbol trade data for the futures stream :param symbol: required @@ -686,36 +744,38 @@ def aggtrade_futures_socket(self, symbol: str, futures_type: FuturesType = Futur } """ - return self._get_futures_socket(symbol.lower() + '@aggTrade', futures_type=futures_type) + return self._get_futures_socket( + symbol.lower() + "@aggTrade", futures_type=futures_type + ) def symbol_miniticker_socket(self, symbol: str): """Start a websocket for a symbol's miniTicker data - https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-mini-ticker-stream + https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-mini-ticker-stream - :param symbol: required - :type symbol: str + :param symbol: required + :type symbol: str - :returns: connection key string if successful, False otherwise + :returns: connection key string if successful, False otherwise - Message Format + Message Format - .. code-block:: python + .. code-block:: python - { - "e": "24hrMiniTicker", // Event type - "E": 123456789, // Event time - "s": "BNBBTC", // Symbol - "c": "0.0025", // Close price - "o": "0.0010", // Open price - "h": "0.0025", // High price - "l": "0.0010", // Low price - "v": "10000", // Total traded base asset volume - "q": "18" // Total traded quote asset volume - } + { + "e": "24hrMiniTicker", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "c": "0.0025", // Close price + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18" // Total traded quote asset volume + } - """ - return self._get_socket(symbol.lower() + '@miniTicker') + """ + return self._get_socket(symbol.lower() + "@miniTicker") def symbol_ticker_socket(self, symbol: str): """Start a websocket for a symbol's ticker data @@ -758,7 +818,7 @@ def symbol_ticker_socket(self, symbol: str): } """ - return self._get_socket(symbol.lower() + '@ticker') + return self._get_socket(symbol.lower() + "@ticker") def ticker_socket(self): """Start a websocket for all ticker data @@ -802,8 +862,7 @@ def ticker_socket(self): } ] """ - return self._get_socket('!ticker@arr') - + return self._get_socket("!ticker@arr") def futures_ticker_socket(self): """Start a websocket for all ticker data @@ -841,8 +900,7 @@ def futures_ticker_socket(self): } ] """ - return self._get_futures_socket('!ticker@arr', FuturesType.USD_M) - + return self._get_futures_socket("!ticker@arr", FuturesType.USD_M) def futures_coin_ticker_socket(self): """Start a websocket for all ticker data @@ -880,7 +938,7 @@ def futures_coin_ticker_socket(self): } ] """ - return self._get_futures_socket('!ticker@arr', FuturesType.COIN_M) + return self._get_futures_socket("!ticker@arr", FuturesType.COIN_M) def index_price_socket(self, symbol: str, fast: bool = True): """Start a websocket for a symbol's futures mark price @@ -898,10 +956,14 @@ def index_price_socket(self, symbol: str, fast: bool = True): "p": "9636.57860000", // Index Price } """ - stream_name = '@indexPrice@1s' if fast else '@indexPrice' - return self._get_futures_socket(symbol.lower() + stream_name, futures_type=FuturesType.COIN_M) + stream_name = "@indexPrice@1s" if fast else "@indexPrice" + return self._get_futures_socket( + symbol.lower() + stream_name, futures_type=FuturesType.COIN_M + ) - def futures_depth_socket(self, symbol: str, depth: str = '10', futures_type=FuturesType.USD_M): + def futures_depth_socket( + self, symbol: str, depth: str = "10", futures_type=FuturesType.USD_M + ): """Subscribe to a futures depth data stream https://binance-docs.github.io/apidocs/futures/en/#partial-book-depth-streams @@ -912,9 +974,16 @@ def futures_depth_socket(self, symbol: str, depth: str = '10', futures_type=Futu :type depth: str :param futures_type: use USD-M or COIN-M futures default USD-M """ - return self._get_futures_socket(symbol.lower() + '@depth' + str(depth), futures_type=futures_type) + return self._get_futures_socket( + symbol.lower() + "@depth" + str(depth), futures_type=futures_type + ) - def symbol_mark_price_socket(self, symbol: str, fast: bool = True, futures_type: FuturesType = FuturesType.USD_M): + def symbol_mark_price_socket( + self, + symbol: str, + fast: bool = True, + futures_type: FuturesType = FuturesType.USD_M, + ): """Start a websocket for a symbol's futures mark price https://binance-docs.github.io/apidocs/futures/en/#mark-price-stream :param symbol: required @@ -932,10 +1001,14 @@ def symbol_mark_price_socket(self, symbol: str, fast: bool = True, futures_type: "T": 1562306400000 // Next funding time } """ - stream_name = '@markPrice@1s' if fast else '@markPrice' - return self._get_futures_socket(symbol.lower() + stream_name, futures_type=futures_type) + stream_name = "@markPrice@1s" if fast else "@markPrice" + return self._get_futures_socket( + symbol.lower() + stream_name, futures_type=futures_type + ) - def all_mark_price_socket(self, fast: bool = True, futures_type: FuturesType = FuturesType.USD_M): + def all_mark_price_socket( + self, fast: bool = True, futures_type: FuturesType = FuturesType.USD_M + ): """Start a websocket for all futures mark price data By default all symbols are included in an array. https://binance-docs.github.io/apidocs/futures/en/#mark-price-stream-for-all-market @@ -956,10 +1029,12 @@ def all_mark_price_socket(self, fast: bool = True, futures_type: FuturesType = F } ] """ - stream_name = '!markPrice@arr@1s' if fast else '!markPrice@arr' + stream_name = "!markPrice@arr@1s" if fast else "!markPrice@arr" return self._get_futures_socket(stream_name, futures_type=futures_type) - def symbol_ticker_futures_socket(self, symbol: str, futures_type: FuturesType = FuturesType.USD_M): + def symbol_ticker_futures_socket( + self, symbol: str, futures_type: FuturesType = FuturesType.USD_M + ): """Start a websocket for a symbol's ticker data By default all markets are included in an array. https://binance-docs.github.io/apidocs/futures/en/#individual-symbol-book-ticker-streams @@ -978,9 +1053,13 @@ def symbol_ticker_futures_socket(self, symbol: str, futures_type: FuturesType = } ] """ - return self._get_futures_socket(symbol.lower() + '@bookTicker', futures_type=futures_type) + return self._get_futures_socket( + symbol.lower() + "@bookTicker", futures_type=futures_type + ) - def individual_symbol_ticker_futures_socket(self, symbol: str, futures_type: FuturesType = FuturesType.USD_M): + def individual_symbol_ticker_futures_socket( + self, symbol: str, futures_type: FuturesType = FuturesType.USD_M + ): """Start a futures websocket for a single symbol's ticker data https://binance-docs.github.io/apidocs/futures/en/#individual-symbol-ticker-streams :param symbol: required @@ -995,9 +1074,15 @@ def individual_symbol_ticker_futures_socket(self, symbol: str, futures_type: Fut "p": "0.0015", // Price change } """ - return self._get_futures_socket(symbol.lower() + '@ticker', futures_type=futures_type) + return self._get_futures_socket( + symbol.lower() + "@ticker", futures_type=futures_type + ) - def all_ticker_futures_socket(self, channel: str = '!bookTicker', futures_type: FuturesType = FuturesType.USD_M): + def all_ticker_futures_socket( + self, + channel: str = "!bookTicker", + futures_type: FuturesType = FuturesType.USD_M, + ): """Start a websocket for all ticker data By default all markets are included in an array. @@ -1048,7 +1133,7 @@ def symbol_book_ticker_socket(self, symbol: str): } """ - return self._get_socket(symbol.lower() + '@bookTicker') + return self._get_socket(symbol.lower() + "@bookTicker") def book_ticker_socket(self): """Start a websocket for the best bid or ask's price or quantity for all symbols. @@ -1066,7 +1151,7 @@ def book_ticker_socket(self): } """ - return self._get_socket('!bookTicker') + return self._get_socket("!bookTicker") def multiplex_socket(self, streams: List[str]): """Start a multiplexed socket using a list of socket names. @@ -1087,7 +1172,7 @@ def multiplex_socket(self, streams: List[str]): """ path = f'streams={"/".join(streams)}' - return self._get_socket(path, prefix='stream?') + return self._get_socket(path, prefix="stream?") def options_multiplex_socket(self, streams: List[str]): """Start a multiplexed socket using a list of socket names. @@ -1107,11 +1192,13 @@ def options_multiplex_socket(self, streams: List[str]): Message Format - see Binance API docs for all types """ - stream_name = '/'.join([s.lower() for s in streams]) - stream_path = f'streams={stream_name}' - return self._get_options_socket(stream_path, prefix='stream?') + stream_name = "/".join([s.lower() for s in streams]) + stream_path = f"streams={stream_name}" + return self._get_options_socket(stream_path, prefix="stream?") - def futures_multiplex_socket(self, streams: List[str], futures_type: FuturesType = FuturesType.USD_M): + def futures_multiplex_socket( + self, streams: List[str], futures_type: FuturesType = FuturesType.USD_M + ): """Start a multiplexed socket using a list of socket names. User stream sockets can not be included. @@ -1130,7 +1217,9 @@ def futures_multiplex_socket(self, streams: List[str], futures_type: FuturesType """ path = f'streams={"/".join(streams)}' - return self._get_futures_socket(path, prefix='stream?', futures_type=futures_type) + return self._get_futures_socket( + path, prefix="stream?", futures_type=futures_type + ) def user_socket(self): """Start a websocket for user data @@ -1145,7 +1234,7 @@ def user_socket(self): stream_url = self.STREAM_URL if self.testnet: stream_url = self.STREAM_TESTNET_URL - return self._get_account_socket('user', stream_url=stream_url) + return self._get_account_socket("user", stream_url=stream_url) def futures_user_socket(self): """Start a websocket for futures user data @@ -1160,7 +1249,7 @@ def futures_user_socket(self): stream_url = self.FSTREAM_URL if self.testnet: stream_url = self.FSTREAM_TESTNET_URL - return self._get_account_socket('futures', stream_url=stream_url) + return self._get_account_socket("futures", stream_url=stream_url) def coin_futures_user_socket(self): """Start a websocket for coin futures user data @@ -1172,7 +1261,7 @@ def coin_futures_user_socket(self): Message Format - see Binanace API docs for all types """ - return self._get_account_socket('coin_futures', stream_url=self.DSTREAM_URL) + return self._get_account_socket("coin_futures", stream_url=self.DSTREAM_URL) def margin_socket(self): """Start a websocket for cross-margin data @@ -1186,7 +1275,7 @@ def margin_socket(self): stream_url = self.STREAM_URL if self.testnet: stream_url = self.STREAM_TESTNET_URL - return self._get_account_socket('margin', stream_url=stream_url) + return self._get_account_socket("margin", stream_url=stream_url) def futures_socket(self): """Start a websocket for futures data @@ -1200,7 +1289,7 @@ def futures_socket(self): stream_url = self.FSTREAM_URL if self.testnet: stream_url = self.FSTREAM_TESTNET_URL - return self._get_account_socket('futures', stream_url=stream_url) + return self._get_account_socket("futures", stream_url=stream_url) def coin_futures_socket(self): """Start a websocket for coin futures data @@ -1214,7 +1303,7 @@ def coin_futures_socket(self): stream_url = self.DSTREAM_URL if self.testnet: stream_url = self.DSTREAM_TESTNET_URL - return self._get_account_socket('coin_futures', stream_url=stream_url) + return self._get_account_socket("coin_futures", stream_url=stream_url) def isolated_margin_socket(self, symbol: str): """Start a websocket for isolated margin data @@ -1241,7 +1330,7 @@ def options_ticker_socket(self, symbol: str): :param symbol: required :type symbol: str """ - return self._get_options_socket(symbol.lower() + '@ticker') + return self._get_options_socket(symbol.lower() + "@ticker") def options_ticker_by_expiration_socket(self, symbol: str, expiration_date: str): """Subscribe to a 24 hour ticker info stream @@ -1251,7 +1340,7 @@ def options_ticker_by_expiration_socket(self, symbol: str, expiration_date: str) :param expiration_date : required :type expiration_date: str """ - return self._get_options_socket(symbol.lower() + '@ticker@' + expiration_date) + return self._get_options_socket(symbol.lower() + "@ticker@" + expiration_date) def options_recent_trades_socket(self, symbol: str): """Subscribe to a latest completed trades stream @@ -1261,9 +1350,11 @@ def options_recent_trades_socket(self, symbol: str): :param symbol: required :type symbol: str """ - return self._get_options_socket(symbol.lower() + '@trade') + return self._get_options_socket(symbol.lower() + "@trade") - def options_kline_socket(self, symbol: str, interval=AsyncClient.KLINE_INTERVAL_1MINUTE): + def options_kline_socket( + self, symbol: str, interval=AsyncClient.KLINE_INTERVAL_1MINUTE + ): """Subscribe to a candlestick data stream https://binance-docs.github.io/apidocs/voptions/en/#market-streams-payload-candle @@ -1273,9 +1364,9 @@ def options_kline_socket(self, symbol: str, interval=AsyncClient.KLINE_INTERVAL_ :param interval: Kline interval, default KLINE_INTERVAL_1MINUTE :type interval: str """ - return self._get_options_socket(symbol.lower() + '@kline_' + interval) + return self._get_options_socket(symbol.lower() + "@kline_" + interval) - def options_depth_socket(self, symbol: str, depth: str = '10'): + def options_depth_socket(self, symbol: str, depth: str = "10"): """Subscribe to a depth data stream https://binance-docs.github.io/apidocs/voptions/en/#market-streams-payload-depth @@ -1285,7 +1376,7 @@ def options_depth_socket(self, symbol: str, depth: str = '10'): :param depth: optional Number of depth entries to return, default 10. :type depth: str """ - return self._get_options_socket(symbol.lower() + '@depth' + str(depth)) + return self._get_options_socket(symbol.lower() + "@depth" + str(depth)) async def _stop_socket(self, conn_key): """Stop a websocket given the connection key @@ -1298,18 +1389,23 @@ async def _stop_socket(self, conn_key): if conn_key not in self._conns: return - del (self._conns[conn_key]) + del self._conns[conn_key] class ThreadedWebsocketManager(ThreadedApiManager): - def __init__( - self, api_key: Optional[str] = None, api_secret: Optional[str] = None, - requests_params: Optional[Dict[str, Any]] = None, tld: str = 'com', - testnet: bool = False, session_params: Optional[Dict[str, Any]] = None, - loop: Optional[asyncio.AbstractEventLoop] = None + self, + api_key: Optional[str] = None, + api_secret: Optional[str] = None, + requests_params: Optional[Dict[str, Any]] = None, + tld: str = "com", + testnet: bool = False, + session_params: Optional[Dict[str, Any]] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, ): - super().__init__(api_key, api_secret, requests_params, tld, testnet, session_params, loop) + super().__init__( + api_key, api_secret, requests_params, tld, testnet, session_params, loop + ) self._bsm: Optional[BinanceSocketManager] = None async def _before_socket_listener_start(self): @@ -1317,340 +1413,339 @@ async def _before_socket_listener_start(self): self._bsm = BinanceSocketManager(client=self._client) def _start_async_socket( - self, callback: Callable, socket_name: str, params: Dict[str, Any], path: Optional[str] = None + self, + callback: Callable, + socket_name: str, + params: Dict[str, Any], + path: Optional[str] = None, ) -> str: while not self._bsm: time.sleep(0.1) socket = getattr(self._bsm, socket_name)(**params) socket_path: str = path or socket._path # noqa self._socket_running[socket_path] = True - self._loop.call_soon_threadsafe(asyncio.create_task, self.start_listener(socket, socket_path, callback)) + self._loop.call_soon_threadsafe( + asyncio.create_task, self.start_listener(socket, socket_path, callback) + ) return socket_path def start_depth_socket( - self, callback: Callable, symbol: str, depth: Optional[str] = None, interval: Optional[int] = None + self, + callback: Callable, + symbol: str, + depth: Optional[str] = None, + interval: Optional[int] = None, ) -> str: return self._start_async_socket( callback=callback, - socket_name='depth_socket', + socket_name="depth_socket", params={ - 'symbol': symbol, - 'depth': depth, - 'interval': interval, - } + "symbol": symbol, + "depth": depth, + "interval": interval, + }, ) - def start_kline_socket(self, callback: Callable, symbol: str, interval=AsyncClient.KLINE_INTERVAL_1MINUTE) -> str: + def start_kline_socket( + self, + callback: Callable, + symbol: str, + interval=AsyncClient.KLINE_INTERVAL_1MINUTE, + ) -> str: return self._start_async_socket( callback=callback, - socket_name='kline_socket', + socket_name="kline_socket", params={ - 'symbol': symbol, - 'interval': interval, - } + "symbol": symbol, + "interval": interval, + }, ) - def start_kline_futures_socket(self, callback: Callable, symbol: str, - interval=AsyncClient.KLINE_INTERVAL_1MINUTE, - futures_type: FuturesType = FuturesType.USD_M, - contract_type: ContractType = ContractType.PERPETUAL) -> str: + def start_kline_futures_socket( + self, + callback: Callable, + symbol: str, + interval=AsyncClient.KLINE_INTERVAL_1MINUTE, + futures_type: FuturesType = FuturesType.USD_M, + contract_type: ContractType = ContractType.PERPETUAL, + ) -> str: return self._start_async_socket( callback=callback, - socket_name='kline_futures_socket', + socket_name="kline_futures_socket", params={ - 'symbol': symbol, - 'interval': interval, - 'futures_type': futures_type, - 'contract_type': contract_type - } + "symbol": symbol, + "interval": interval, + "futures_type": futures_type, + "contract_type": contract_type, + }, ) - def start_miniticker_socket(self, callback: Callable, update_time: int = 1000) -> str: + def start_miniticker_socket( + self, callback: Callable, update_time: int = 1000 + ) -> str: return self._start_async_socket( callback=callback, - socket_name='miniticker_socket', + socket_name="miniticker_socket", params={ - 'update_time': update_time, - } + "update_time": update_time, + }, ) def start_trade_socket(self, callback: Callable, symbol: str) -> str: return self._start_async_socket( callback=callback, - socket_name='trade_socket', + socket_name="trade_socket", params={ - 'symbol': symbol, - } + "symbol": symbol, + }, ) def start_aggtrade_socket(self, callback: Callable, symbol: str) -> str: return self._start_async_socket( callback=callback, - socket_name='aggtrade_socket', + socket_name="aggtrade_socket", params={ - 'symbol': symbol, - } + "symbol": symbol, + }, ) def start_aggtrade_futures_socket( - self, callback: Callable, symbol: str, futures_type: FuturesType = FuturesType.USD_M + self, + callback: Callable, + symbol: str, + futures_type: FuturesType = FuturesType.USD_M, ) -> str: return self._start_async_socket( callback=callback, - socket_name='aggtrade_futures_socket', + socket_name="aggtrade_futures_socket", params={ - 'symbol': symbol, - 'futures_type': futures_type, - } + "symbol": symbol, + "futures_type": futures_type, + }, ) def start_symbol_miniticker_socket(self, callback: Callable, symbol: str) -> str: return self._start_async_socket( callback=callback, - socket_name='symbol_miniticker_socket', + socket_name="symbol_miniticker_socket", params={ - 'symbol': symbol, - } + "symbol": symbol, + }, ) def start_symbol_ticker_socket(self, callback: Callable, symbol: str) -> str: return self._start_async_socket( callback=callback, - socket_name='symbol_ticker_socket', + socket_name="symbol_ticker_socket", params={ - 'symbol': symbol, - } + "symbol": symbol, + }, ) def start_ticker_socket(self, callback: Callable) -> str: return self._start_async_socket( - callback=callback, - socket_name='ticker_socket', - params={} + callback=callback, socket_name="ticker_socket", params={} ) - def start_index_price_socket(self, callback: Callable, symbol: str, fast: bool = True) -> str: + def start_index_price_socket( + self, callback: Callable, symbol: str, fast: bool = True + ) -> str: return self._start_async_socket( callback=callback, - socket_name='index_price_socket', - params={ - 'symbol': symbol, - 'fast': fast - } + socket_name="index_price_socket", + params={"symbol": symbol, "fast": fast}, ) def start_symbol_mark_price_socket( - self, callback: Callable, symbol: str, fast: bool = True, futures_type: FuturesType = FuturesType.USD_M + self, + callback: Callable, + symbol: str, + fast: bool = True, + futures_type: FuturesType = FuturesType.USD_M, ) -> str: return self._start_async_socket( callback=callback, - socket_name='symbol_mark_price_socket', - params={ - 'symbol': symbol, - 'fast': fast, - 'futures_type': futures_type - } + socket_name="symbol_mark_price_socket", + params={"symbol": symbol, "fast": fast, "futures_type": futures_type}, ) def start_all_mark_price_socket( - self, callback: Callable, fast: bool = True, futures_type: FuturesType = FuturesType.USD_M + self, + callback: Callable, + fast: bool = True, + futures_type: FuturesType = FuturesType.USD_M, ) -> str: return self._start_async_socket( callback=callback, - socket_name='all_mark_price_socket', - params={ - 'fast': fast, - 'futures_type': futures_type - } + socket_name="all_mark_price_socket", + params={"fast": fast, "futures_type": futures_type}, ) def start_symbol_ticker_futures_socket( - self, callback: Callable, symbol: str, futures_type: FuturesType = FuturesType.USD_M + self, + callback: Callable, + symbol: str, + futures_type: FuturesType = FuturesType.USD_M, ) -> str: return self._start_async_socket( callback=callback, - socket_name='symbol_ticker_futures_socket', - params={ - 'symbol': symbol, - 'futures_type': futures_type - } + socket_name="symbol_ticker_futures_socket", + params={"symbol": symbol, "futures_type": futures_type}, ) def start_individual_symbol_ticker_futures_socket( - self, callback: Callable, symbol: str, futures_type: FuturesType = FuturesType.USD_M + self, + callback: Callable, + symbol: str, + futures_type: FuturesType = FuturesType.USD_M, ) -> str: return self._start_async_socket( callback=callback, - socket_name='individual_symbol_ticker_futures_socket', - params={ - 'symbol': symbol, - 'futures_type': futures_type - } + socket_name="individual_symbol_ticker_futures_socket", + params={"symbol": symbol, "futures_type": futures_type}, ) - def start_all_ticker_futures_socket(self, callback: Callable, futures_type: FuturesType = FuturesType.USD_M) -> str: + def start_all_ticker_futures_socket( + self, callback: Callable, futures_type: FuturesType = FuturesType.USD_M + ) -> str: return self._start_async_socket( callback=callback, - socket_name='all_ticker_futures_socket', - params={ - 'futures_type': futures_type - } + socket_name="all_ticker_futures_socket", + params={"futures_type": futures_type}, ) def start_symbol_book_ticker_socket(self, callback: Callable, symbol: str) -> str: return self._start_async_socket( callback=callback, - socket_name='symbol_book_ticker_socket', - params={ - 'symbol': symbol - } + socket_name="symbol_book_ticker_socket", + params={"symbol": symbol}, ) def start_book_ticker_socket(self, callback: Callable) -> str: return self._start_async_socket( - callback=callback, - socket_name='book_ticker_socket', - params={} + callback=callback, socket_name="book_ticker_socket", params={} ) def start_multiplex_socket(self, callback: Callable, streams: List[str]) -> str: return self._start_async_socket( callback=callback, - socket_name='multiplex_socket', - params={ - 'streams': streams - } + socket_name="multiplex_socket", + params={"streams": streams}, ) - def start_options_multiplex_socket(self, callback: Callable, streams: List[str]) -> str: + def start_options_multiplex_socket( + self, callback: Callable, streams: List[str] + ) -> str: return self._start_async_socket( callback=callback, - socket_name='options_multiplex_socket', - params={ - 'streams': streams - } + socket_name="options_multiplex_socket", + params={"streams": streams}, ) def start_futures_multiplex_socket( - self, callback: Callable, streams: List[str], futures_type: FuturesType = FuturesType.USD_M + self, + callback: Callable, + streams: List[str], + futures_type: FuturesType = FuturesType.USD_M, ) -> str: return self._start_async_socket( callback=callback, - socket_name='futures_multiplex_socket', - params={ - 'streams': streams, - 'futures_type': futures_type - } + socket_name="futures_multiplex_socket", + params={"streams": streams, "futures_type": futures_type}, ) def start_user_socket(self, callback: Callable) -> str: return self._start_async_socket( - callback=callback, - socket_name='user_socket', - params={} + callback=callback, socket_name="user_socket", params={} ) def start_futures_user_socket(self, callback: Callable) -> str: return self._start_async_socket( - callback=callback, - socket_name='futures_user_socket', - params={} + callback=callback, socket_name="futures_user_socket", params={} ) def start_coin_futures_user_socket(self, callback: Callable) -> str: return self._start_async_socket( - callback=callback, - socket_name='coin_futures_user_socket', - params={} + callback=callback, socket_name="coin_futures_user_socket", params={} ) def start_margin_socket(self, callback: Callable) -> str: return self._start_async_socket( - callback=callback, - socket_name='margin_socket', - params={} + callback=callback, socket_name="margin_socket", params={} ) def start_futures_socket(self, callback: Callable) -> str: return self._start_async_socket( - callback=callback, - socket_name='futures_socket', - params={} + callback=callback, socket_name="futures_socket", params={} ) def start_coin_futures_socket(self, callback: Callable) -> str: return self._start_async_socket( - callback=callback, - socket_name='coin_futures_socket', - params={} + callback=callback, socket_name="coin_futures_socket", params={} ) def start_isolated_margin_socket(self, callback: Callable, symbol: str) -> str: return self._start_async_socket( callback=callback, - socket_name='isolated_margin_socket', - params={ - 'symbol': symbol - } + socket_name="isolated_margin_socket", + params={"symbol": symbol}, ) def start_options_ticker_socket(self, callback: Callable, symbol: str) -> str: return self._start_async_socket( callback=callback, - socket_name='options_ticker_socket', - params={ - 'symbol': symbol - } + socket_name="options_ticker_socket", + params={"symbol": symbol}, ) - def start_options_ticker_by_expiration_socket(self, callback: Callable, symbol: str, expiration_date: str) -> str: + def start_options_ticker_by_expiration_socket( + self, callback: Callable, symbol: str, expiration_date: str + ) -> str: return self._start_async_socket( callback=callback, - socket_name='options_ticker_by_expiration_socket', - params={ - 'symbol': symbol, - 'expiration_date': expiration_date - } + socket_name="options_ticker_by_expiration_socket", + params={"symbol": symbol, "expiration_date": expiration_date}, ) - def start_options_recent_trades_socket(self, callback: Callable, symbol: str) -> str: + def start_options_recent_trades_socket( + self, callback: Callable, symbol: str + ) -> str: return self._start_async_socket( callback=callback, - socket_name='options_recent_trades_socket', - params={ - 'symbol': symbol - } + socket_name="options_recent_trades_socket", + params={"symbol": symbol}, ) def start_options_kline_socket( - self, callback: Callable, symbol: str, interval=AsyncClient.KLINE_INTERVAL_1MINUTE + self, + callback: Callable, + symbol: str, + interval=AsyncClient.KLINE_INTERVAL_1MINUTE, ) -> str: return self._start_async_socket( callback=callback, - socket_name='options_kline_socket', - params={ - 'symbol': symbol, - 'interval': interval - } + socket_name="options_kline_socket", + params={"symbol": symbol, "interval": interval}, ) - def start_options_depth_socket(self, callback: Callable, symbol: str, depth: str = '10') -> str: + def start_options_depth_socket( + self, callback: Callable, symbol: str, depth: str = "10" + ) -> str: return self._start_async_socket( callback=callback, - socket_name='options_depth_socket', - params={ - 'symbol': symbol, - 'depth': depth - } + socket_name="options_depth_socket", + params={"symbol": symbol, "depth": depth}, ) - def start_futures_depth_socket(self, callback: Callable, symbol: str, depth: str = '10', futures_type=FuturesType.USD_M) -> str: + def start_futures_depth_socket( + self, + callback: Callable, + symbol: str, + depth: str = "10", + futures_type=FuturesType.USD_M, + ) -> str: return self._start_async_socket( callback=callback, - socket_name='futures_depth_socket', - params={ - 'symbol': symbol, - 'depth': depth, - 'futures_type': futures_type - } + socket_name="futures_depth_socket", + params={"symbol": symbol, "depth": depth, "futures_type": futures_type}, ) diff --git a/binance/threaded_stream.py b/binance/threaded_stream.py index 82d66454..e53d7dcc 100755 --- a/binance/threaded_stream.py +++ b/binance/threaded_stream.py @@ -7,28 +7,29 @@ class ThreadedApiManager(threading.Thread): - def __init__( - self, api_key: Optional[str] = None, api_secret: Optional[str] = None, - requests_params: Optional[Dict[str, Any]] = None, tld: str = 'com', - testnet: bool = False, session_params: Optional[Dict[str, Any]] = None, - _loop: Optional[asyncio.AbstractEventLoop] = None + self, + api_key: Optional[str] = None, + api_secret: Optional[str] = None, + requests_params: Optional[Dict[str, Any]] = None, + tld: str = "com", + testnet: bool = False, + session_params: Optional[Dict[str, Any]] = None, + _loop: Optional[asyncio.AbstractEventLoop] = None, ): - """Initialise the BinanceSocketManager - - """ + """Initialise the BinanceSocketManager""" super().__init__() self._loop: asyncio.AbstractEventLoop = get_loop() if _loop is None else _loop self._client: Optional[AsyncClient] = None self._running: bool = True self._socket_running: Dict[str, bool] = {} self._client_params = { - 'api_key': api_key, - 'api_secret': api_secret, - 'requests_params': requests_params, - 'tld': tld, - 'testnet': testnet, - 'session_params': session_params, + "api_key": api_key, + "api_secret": api_secret, + "requests_params": requests_params, + "tld": tld, + "testnet": testnet, + "session_params": session_params, } async def _before_socket_listener_start(self): diff --git a/examples/binace_socket_manager.py b/examples/binace_socket_manager.py index dcae2da6..0f2d4184 100644 --- a/examples/binace_socket_manager.py +++ b/examples/binace_socket_manager.py @@ -13,7 +13,7 @@ async def main(): client = await AsyncClient.create() bm = BinanceSocketManager(client) # start any sockets here, i.e a trade socket - ts = bm.trade_socket('BTCUSDT') + ts = bm.trade_socket("BTCUSDT") # then start receiving messages async with ts as tscm: start_time = time.time() @@ -28,6 +28,7 @@ async def main(): await client.close_connection() print("WebSocket connection closed after 10 seconds.") + if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) diff --git a/examples/create_order.py b/examples/create_order.py index 8d9dbd90..ce9c9bfa 100644 --- a/examples/create_order.py +++ b/examples/create_order.py @@ -7,10 +7,11 @@ from binance.client import Client -api_key = "" # your api_key here +api_key = "" # your api_key here secret = "" # your secret here client = Client(api_key, secret, testnet=True) + # create futures order def create_futures_order(): order = client.futures_create_order( @@ -18,17 +19,14 @@ def create_futures_order(): side="BUY", type="MARKET", quantity=0.1, - positionSide="LONG" # BOTH for One-way Mode ; LONG or SHORT for Hedge Mode + positionSide="LONG", # BOTH for One-way Mode ; LONG or SHORT for Hedge Mode ) print(order) + def create_spot_order(): order = client.create_order( - symbol="LTCUSDT", - side="BUY", - type="LIMIT", - price=60, - quantity=0.1 + symbol="LTCUSDT", side="BUY", type="LIMIT", price=60, quantity=0.1 ) print(order) @@ -37,4 +35,5 @@ def main(): create_futures_order() create_spot_order() -main() \ No newline at end of file + +main() diff --git a/examples/create_order_async.py b/examples/create_order_async.py index bcb244fc..1c3d1d24 100644 --- a/examples/create_order_async.py +++ b/examples/create_order_async.py @@ -7,9 +7,10 @@ from binance.client import AsyncClient + # create futures order async def main(): - api_key = "" # your api_key here + api_key = "" # your api_key here secret = "" # your secret here client = AsyncClient(api_key, secret, testnet=True) order = await client.futures_create_order( @@ -17,9 +18,10 @@ async def main(): side="BUY", type="MARKET", quantity=0.1, - positionSide="LONG" # BOTH for One-way Mode ; LONG or SHORT for Hedge Mode + positionSide="LONG", # BOTH for One-way Mode ; LONG or SHORT for Hedge Mode ) print(order) await client.close_connection() -asyncio.run(main()) \ No newline at end of file + +asyncio.run(main()) diff --git a/tests/conftest.py b/tests/conftest.py index a6e7dbb3..e80b6375 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -7,17 +7,23 @@ proxy = os.getenv("PROXY") if proxy: - proxies = {"http": proxy, 'https': proxy} # tmp: improve this in the future + proxies = {"http": proxy, "https": proxy} # tmp: improve this in the future else: print("No proxy set") @pytest.fixture(scope="module") def client(): - return Client("test_api_key", "test_api_secret", {'proxies': proxies}) + return Client("test_api_key", "test_api_secret", {"proxies": proxies}) + @pytest.fixture(scope="module") async def clientAsync(): # for now this is not working inside the tests - res = await AsyncClient().create(api_key="api_key", api_secret="api_secret", https_proxy=proxy, loop=asyncio.new_event_loop()) - return res \ No newline at end of file + res = await AsyncClient().create( + api_key="api_key", + api_secret="api_secret", + https_proxy=proxy, + loop=asyncio.new_event_loop(), + ) + return res diff --git a/tests/test_api_request.py b/tests/test_api_request.py index c372ca7d..bb7a3b01 100755 --- a/tests/test_api_request.py +++ b/tests/test_api_request.py @@ -7,11 +7,12 @@ proxies = {} proxy = os.getenv("PROXY") if proxy: - proxies = {"http": proxy, 'https': proxy} # tmp: improve this in the future + proxies = {"http": proxy, "https": proxy} # tmp: improve this in the future else: print("No proxy set") -client = Client("api_key", "api_secret", {'proxies': proxies}) +client = Client("api_key", "api_secret", {"proxies": proxies}) + def test_invalid_json(): """Test Invalid response Exception""" @@ -45,5 +46,9 @@ def test_api_exception_invalid_json(): with pytest.raises(BinanceAPIException): with requests_mock.mock() as m: not_json_str = "Error" - m.get("https://api.binance.com/api/v3/time", text=not_json_str, status_code=400) + m.get( + "https://api.binance.com/api/v3/time", + text=not_json_str, + status_code=400, + ) client.get_server_time() diff --git a/tests/test_client.py b/tests/test_client.py index d85ce196..0c46e7f6 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,6 +1,4 @@ - - def test_client_initialization(client): - assert client.API_KEY == 'test_api_key' - assert client.API_SECRET == 'test_api_secret' + assert client.API_KEY == "test_api_key" + assert client.API_SECRET == "test_api_secret" assert client.testnet is False diff --git a/tests/test_cryptography.py b/tests/test_cryptography.py index 2edd5b42..04240262 100644 --- a/tests/test_cryptography.py +++ b/tests/test_cryptography.py @@ -5,28 +5,29 @@ "description": "Unencrypted PKCS8 ed22519 private key", "private_key": "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIPQmzwVKJETqVd7L9E/DFbkvrOigy1tLL+9QF0mSn6dV\n-----END PRIVATE KEY-----\n", "password": None, - "expected_signature": "a4Pm3p02D2HXtNfo3DBaVCe9Ov7kledewgYtGjekotFmZ5wXa3mC5AtLB7CpAphyNjeyovIuDP+9fyjYmsojCw==" + "expected_signature": "a4Pm3p02D2HXtNfo3DBaVCe9Ov7kledewgYtGjekotFmZ5wXa3mC5AtLB7CpAphyNjeyovIuDP+9fyjYmsojCw==", }, { "description": "Unencrypted PKCS8 ed22519 private key in bytes", - "private_key": b'-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIPQmzwVKJETqVd7L9E/DFbkvrOigy1tLL+9QF0mSn6dV\n-----END PRIVATE KEY-----\n', + "private_key": b"-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIPQmzwVKJETqVd7L9E/DFbkvrOigy1tLL+9QF0mSn6dV\n-----END PRIVATE KEY-----\n", "password": None, - "expected_signature": "a4Pm3p02D2HXtNfo3DBaVCe9Ov7kledewgYtGjekotFmZ5wXa3mC5AtLB7CpAphyNjeyovIuDP+9fyjYmsojCw==" + "expected_signature": "a4Pm3p02D2HXtNfo3DBaVCe9Ov7kledewgYtGjekotFmZ5wXa3mC5AtLB7CpAphyNjeyovIuDP+9fyjYmsojCw==", }, { "description": "Encrypted PKCS8 RSA private key", "private_key": "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQWW+iEMYYCPUntrPq\nZ2RCMAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEIw3ViSuTp8JeN43\n5VGlHt0EggTQBvEzd2w2F561CzU+MDouZDOPj4RTIStC471z0/bxTgYqH3gYchoe\nOfi2lsLuD8B+ivIRuXB8GT66BIseIOMV8t/tiMe97rFI/cV4h6DrBO1xlmSrBG97\nvFF9qPA5yPRlrHtWKkGxhXteNVsT3w/7Y7KsulO/gA2KpsOElMElOhUP462Yd0Wl\nOxAIV3+knl2niozws2Kq3EdzTF3N6hlavUPryiU/w4RRsPN5qgjchVVLq/sYRYhx\nN8uWJbkjhCcHsULkD5KkdgddR0VOhpQPXIdY+gPkSBJq1ltRWy/TYdXiU2fEBNZW\nhFUVrxnS76+u2R3vukY2IAX8zTC6h2AbCBG+r4XXzgk/l/4peySKHsPQRzQ0in39\na9o5sctOmUNeD4uJ6cClXDdqyEwXhnPmRKZjJ8qeH4D9wl7HOG7iQsYiyfJe/igi\nFEXVRZOtLBdbwX45rU6wiWWjxzY+mDnw4BXE31ZBPwgtoh+CLTyK8NI8LnCV/CgO\nzOY4sm/KDWmbfTTZjLSdYRFj7wEpOdUWjZ13viDFZqnmy/o1auvLmBcqbRrCyW+B\nOMI7aHE0mZ/52vEFQYU1tH0BxMmRfWXUCJj0TjwxDY6BQmmW4YlhsrgGNekLFDo1\n6phFd0pA4UPqGXfNLzHp1dtLhUEb4YzcpDn+HMzMf1gfez7qeqU28nNFg/AwwqHZ\nTWdGclCFjiah7SfvOslob4vdLGwkUhgCBKQUQoU1DltX2GOgIv9SNY3q6X0NwdZG\nL5gqk225WVUwIRzmi5nfUEXlbaTvyHg3BuGedUKJ91IhRCW1ZjvU8GQcfVsu8bse\nTCKMdr7wi/zEZXSldCza6vL4m3tmBLtWkHVOW8bcDWvoVwRswbFHfleHzckl7EeC\n9C4TRa66gA5UOv14SrpC8noQUNpSegg+1KI4BSNvwaheiSUqjQbisb0qYCxML0ZP\nmQodwVsXG6LYo+Y6y6CpHbT7UYkfa59q/CGOZByL1bEzzgd98ZHwjihOjHVaV6sY\nBW018AvGxr7kjEU4LNqIteydTp0o31ZJN/qK78w5EQFfJxfImrx/E4nYKtg4higj\nKOQCgJALKIveidqQEFsbGWsulYrMXwnu0nPThofR1D8eCJZpdTxvOh2nIrNrAeY8\nZMAwG1uQos5A0yEZ1auHxz+rb4errnk92OnVlWnElf1TwwlkFFNLdNDl8VpiMP40\n6en9VtlOfgH8AwB03WsoeuEQsxYTIcRKWZZPRsLx3hd0BsOw0FcYDSX2XIGPkVVW\niYf9hzFSQsWV3d6utloIm4nG8XONfNaRimGECbUSZyHZimrO1m4Gga5pE3LKuDri\nJKR2lR7b6XPR7+FS+lG1zq5KY7onAVQY1oABfTjpJRju6pQGWt70hairo6EaVC3u\nrBy8UkLwBbfDuigSvsVk+sF2+Ic0IzX6IniU0F5kMe+MKqGB4aicXP6FFGBpPFTe\nv6yHD+DYAu1rnlXrqmFL50CfutTF78uPPJ9D2Sm0DcGPFj+6IrCigj48uxoHR9Qb\nFeNzfsmVwoFAWWq/MpkPbX6Aql8ddCbpMxDUUkybwVV9rJmEMTLil44FrxKAKFhP\n0Av7JeFvdz15pfnf/IQ3IOvVhHGFChFS13sbYSvFHMQF3P0BiyvjhBI=\n-----END ENCRYPTED PRIVATE KEY-----\n", "password": "testpwd", - "expected_signature": "S4l9IONXGHIdt4NjwmpCIhawDTitjUQls73d+mi0HJTSbTGyn95NabX5hC9+n6HsTqLcWPvxKgTvLFMnTaf6Jxl+xwQMbu9/6mw88KF7i1pEQizerKcr91rPUPVBQ4OY10Q018QEamIAymRgo/eoRYSm7CqCdeibGyO0XfXZBaJnVGFJ9hgrPIwSKHgeUnfK8qMenULvL0qKMEJ6ziYPiqh7k9xX3xIV7lGIpokk+ekqlFd01f/Lov45osJCFuccJO4xuUUZewZnVGF7Uw6Rim3UsKhXKZUN9WZWa5RT+dpBIJ5DTBIXBSvowwj3GZC3j+XvWw8Sn0Ls9836l89BXw==" + "expected_signature": "S4l9IONXGHIdt4NjwmpCIhawDTitjUQls73d+mi0HJTSbTGyn95NabX5hC9+n6HsTqLcWPvxKgTvLFMnTaf6Jxl+xwQMbu9/6mw88KF7i1pEQizerKcr91rPUPVBQ4OY10Q018QEamIAymRgo/eoRYSm7CqCdeibGyO0XfXZBaJnVGFJ9hgrPIwSKHgeUnfK8qMenULvL0qKMEJ6ziYPiqh7k9xX3xIV7lGIpokk+ekqlFd01f/Lov45osJCFuccJO4xuUUZewZnVGF7Uw6Rim3UsKhXKZUN9WZWa5RT+dpBIJ5DTBIXBSvowwj3GZC3j+XvWw8Sn0Ls9836l89BXw==", }, { "description": "Encrypted PKCS8 RSA private key in bytes", - "private_key": b'-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQWW+iEMYYCPUntrPq\nZ2RCMAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEIw3ViSuTp8JeN43\n5VGlHt0EggTQBvEzd2w2F561CzU+MDouZDOPj4RTIStC471z0/bxTgYqH3gYchoe\nOfi2lsLuD8B+ivIRuXB8GT66BIseIOMV8t/tiMe97rFI/cV4h6DrBO1xlmSrBG97\nvFF9qPA5yPRlrHtWKkGxhXteNVsT3w/7Y7KsulO/gA2KpsOElMElOhUP462Yd0Wl\nOxAIV3+knl2niozws2Kq3EdzTF3N6hlavUPryiU/w4RRsPN5qgjchVVLq/sYRYhx\nN8uWJbkjhCcHsULkD5KkdgddR0VOhpQPXIdY+gPkSBJq1ltRWy/TYdXiU2fEBNZW\nhFUVrxnS76+u2R3vukY2IAX8zTC6h2AbCBG+r4XXzgk/l/4peySKHsPQRzQ0in39\na9o5sctOmUNeD4uJ6cClXDdqyEwXhnPmRKZjJ8qeH4D9wl7HOG7iQsYiyfJe/igi\nFEXVRZOtLBdbwX45rU6wiWWjxzY+mDnw4BXE31ZBPwgtoh+CLTyK8NI8LnCV/CgO\nzOY4sm/KDWmbfTTZjLSdYRFj7wEpOdUWjZ13viDFZqnmy/o1auvLmBcqbRrCyW+B\nOMI7aHE0mZ/52vEFQYU1tH0BxMmRfWXUCJj0TjwxDY6BQmmW4YlhsrgGNekLFDo1\n6phFd0pA4UPqGXfNLzHp1dtLhUEb4YzcpDn+HMzMf1gfez7qeqU28nNFg/AwwqHZ\nTWdGclCFjiah7SfvOslob4vdLGwkUhgCBKQUQoU1DltX2GOgIv9SNY3q6X0NwdZG\nL5gqk225WVUwIRzmi5nfUEXlbaTvyHg3BuGedUKJ91IhRCW1ZjvU8GQcfVsu8bse\nTCKMdr7wi/zEZXSldCza6vL4m3tmBLtWkHVOW8bcDWvoVwRswbFHfleHzckl7EeC\n9C4TRa66gA5UOv14SrpC8noQUNpSegg+1KI4BSNvwaheiSUqjQbisb0qYCxML0ZP\nmQodwVsXG6LYo+Y6y6CpHbT7UYkfa59q/CGOZByL1bEzzgd98ZHwjihOjHVaV6sY\nBW018AvGxr7kjEU4LNqIteydTp0o31ZJN/qK78w5EQFfJxfImrx/E4nYKtg4higj\nKOQCgJALKIveidqQEFsbGWsulYrMXwnu0nPThofR1D8eCJZpdTxvOh2nIrNrAeY8\nZMAwG1uQos5A0yEZ1auHxz+rb4errnk92OnVlWnElf1TwwlkFFNLdNDl8VpiMP40\n6en9VtlOfgH8AwB03WsoeuEQsxYTIcRKWZZPRsLx3hd0BsOw0FcYDSX2XIGPkVVW\niYf9hzFSQsWV3d6utloIm4nG8XONfNaRimGECbUSZyHZimrO1m4Gga5pE3LKuDri\nJKR2lR7b6XPR7+FS+lG1zq5KY7onAVQY1oABfTjpJRju6pQGWt70hairo6EaVC3u\nrBy8UkLwBbfDuigSvsVk+sF2+Ic0IzX6IniU0F5kMe+MKqGB4aicXP6FFGBpPFTe\nv6yHD+DYAu1rnlXrqmFL50CfutTF78uPPJ9D2Sm0DcGPFj+6IrCigj48uxoHR9Qb\nFeNzfsmVwoFAWWq/MpkPbX6Aql8ddCbpMxDUUkybwVV9rJmEMTLil44FrxKAKFhP\n0Av7JeFvdz15pfnf/IQ3IOvVhHGFChFS13sbYSvFHMQF3P0BiyvjhBI=\n-----END ENCRYPTED PRIVATE KEY-----\n', + "private_key": b"-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQWW+iEMYYCPUntrPq\nZ2RCMAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEIw3ViSuTp8JeN43\n5VGlHt0EggTQBvEzd2w2F561CzU+MDouZDOPj4RTIStC471z0/bxTgYqH3gYchoe\nOfi2lsLuD8B+ivIRuXB8GT66BIseIOMV8t/tiMe97rFI/cV4h6DrBO1xlmSrBG97\nvFF9qPA5yPRlrHtWKkGxhXteNVsT3w/7Y7KsulO/gA2KpsOElMElOhUP462Yd0Wl\nOxAIV3+knl2niozws2Kq3EdzTF3N6hlavUPryiU/w4RRsPN5qgjchVVLq/sYRYhx\nN8uWJbkjhCcHsULkD5KkdgddR0VOhpQPXIdY+gPkSBJq1ltRWy/TYdXiU2fEBNZW\nhFUVrxnS76+u2R3vukY2IAX8zTC6h2AbCBG+r4XXzgk/l/4peySKHsPQRzQ0in39\na9o5sctOmUNeD4uJ6cClXDdqyEwXhnPmRKZjJ8qeH4D9wl7HOG7iQsYiyfJe/igi\nFEXVRZOtLBdbwX45rU6wiWWjxzY+mDnw4BXE31ZBPwgtoh+CLTyK8NI8LnCV/CgO\nzOY4sm/KDWmbfTTZjLSdYRFj7wEpOdUWjZ13viDFZqnmy/o1auvLmBcqbRrCyW+B\nOMI7aHE0mZ/52vEFQYU1tH0BxMmRfWXUCJj0TjwxDY6BQmmW4YlhsrgGNekLFDo1\n6phFd0pA4UPqGXfNLzHp1dtLhUEb4YzcpDn+HMzMf1gfez7qeqU28nNFg/AwwqHZ\nTWdGclCFjiah7SfvOslob4vdLGwkUhgCBKQUQoU1DltX2GOgIv9SNY3q6X0NwdZG\nL5gqk225WVUwIRzmi5nfUEXlbaTvyHg3BuGedUKJ91IhRCW1ZjvU8GQcfVsu8bse\nTCKMdr7wi/zEZXSldCza6vL4m3tmBLtWkHVOW8bcDWvoVwRswbFHfleHzckl7EeC\n9C4TRa66gA5UOv14SrpC8noQUNpSegg+1KI4BSNvwaheiSUqjQbisb0qYCxML0ZP\nmQodwVsXG6LYo+Y6y6CpHbT7UYkfa59q/CGOZByL1bEzzgd98ZHwjihOjHVaV6sY\nBW018AvGxr7kjEU4LNqIteydTp0o31ZJN/qK78w5EQFfJxfImrx/E4nYKtg4higj\nKOQCgJALKIveidqQEFsbGWsulYrMXwnu0nPThofR1D8eCJZpdTxvOh2nIrNrAeY8\nZMAwG1uQos5A0yEZ1auHxz+rb4errnk92OnVlWnElf1TwwlkFFNLdNDl8VpiMP40\n6en9VtlOfgH8AwB03WsoeuEQsxYTIcRKWZZPRsLx3hd0BsOw0FcYDSX2XIGPkVVW\niYf9hzFSQsWV3d6utloIm4nG8XONfNaRimGECbUSZyHZimrO1m4Gga5pE3LKuDri\nJKR2lR7b6XPR7+FS+lG1zq5KY7onAVQY1oABfTjpJRju6pQGWt70hairo6EaVC3u\nrBy8UkLwBbfDuigSvsVk+sF2+Ic0IzX6IniU0F5kMe+MKqGB4aicXP6FFGBpPFTe\nv6yHD+DYAu1rnlXrqmFL50CfutTF78uPPJ9D2Sm0DcGPFj+6IrCigj48uxoHR9Qb\nFeNzfsmVwoFAWWq/MpkPbX6Aql8ddCbpMxDUUkybwVV9rJmEMTLil44FrxKAKFhP\n0Av7JeFvdz15pfnf/IQ3IOvVhHGFChFS13sbYSvFHMQF3P0BiyvjhBI=\n-----END ENCRYPTED PRIVATE KEY-----\n", "password": "testpwd", - "expected_signature": "S4l9IONXGHIdt4NjwmpCIhawDTitjUQls73d+mi0HJTSbTGyn95NabX5hC9+n6HsTqLcWPvxKgTvLFMnTaf6Jxl+xwQMbu9/6mw88KF7i1pEQizerKcr91rPUPVBQ4OY10Q018QEamIAymRgo/eoRYSm7CqCdeibGyO0XfXZBaJnVGFJ9hgrPIwSKHgeUnfK8qMenULvL0qKMEJ6ziYPiqh7k9xX3xIV7lGIpokk+ekqlFd01f/Lov45osJCFuccJO4xuUUZewZnVGF7Uw6Rim3UsKhXKZUN9WZWa5RT+dpBIJ5DTBIXBSvowwj3GZC3j+XvWw8Sn0Ls9836l89BXw==" - } + "expected_signature": "S4l9IONXGHIdt4NjwmpCIhawDTitjUQls73d+mi0HJTSbTGyn95NabX5hC9+n6HsTqLcWPvxKgTvLFMnTaf6Jxl+xwQMbu9/6mw88KF7i1pEQizerKcr91rPUPVBQ4OY10Q018QEamIAymRgo/eoRYSm7CqCdeibGyO0XfXZBaJnVGFJ9hgrPIwSKHgeUnfK8qMenULvL0qKMEJ6ziYPiqh7k9xX3xIV7lGIpokk+ekqlFd01f/Lov45osJCFuccJO4xuUUZewZnVGF7Uw6Rim3UsKhXKZUN9WZWa5RT+dpBIJ5DTBIXBSvowwj3GZC3j+XvWw8Sn0Ls9836l89BXw==", + }, ] + def test_encryption(): data = { "symbol": "BTCUSDT", @@ -43,7 +44,9 @@ def test_encryption(): api_secret="api_secret", private_key=case["private_key"], private_key_pass=case["password"], - ping=False + ping=False, ) signature = client._generate_signature(data) - assert signature == case["expected_signature"], f"Test failed: {case['description']}" + assert ( + signature == case["expected_signature"] + ), f"Test failed: {case['description']}" diff --git a/tests/test_futures.py b/tests/test_futures.py index 066c261a..8f20c3a6 100644 --- a/tests/test_futures.py +++ b/tests/test_futures.py @@ -1,4 +1,3 @@ - import requests_mock import json from binance.client import Client @@ -6,34 +5,90 @@ client = Client(api_key="api_key", api_secret="api_secret", ping=False) + def test_futures_position_information(): with requests_mock.mock() as m: - url_matcher = re.compile(r"https:\/\/fapi.binance.com\/fapi\/v3\/positionRisk\?.+") - response = [{'symbol': 'LTCUSDT', 'positionSide': 'LONG', 'positionAmt': '0.700', 'entryPrice': '75.6', 'breakEvenPrice': '75.63024', 'markPrice': '73.18000000', 'unRealizedProfit': '-1.69400000', 'liquidationPrice': '0', 'isolatedMargin': '0', 'notional': '51.22600000', 'marginAsset': 'USDT', 'isolatedWallet': '0', 'initialMargin': '10.24520000', 'maintMargin': '0.33296900', 'positionInitialMargin': '10.24520000', 'openOrderInitialMargin': '0', 'adl': 0, 'bidNotional': '0', 'askNotional': '0', 'updateTime': 1729436057076}] + url_matcher = re.compile( + r"https:\/\/fapi.binance.com\/fapi\/v3\/positionRisk\?.+" + ) + response = [ + { + "symbol": "LTCUSDT", + "positionSide": "LONG", + "positionAmt": "0.700", + "entryPrice": "75.6", + "breakEvenPrice": "75.63024", + "markPrice": "73.18000000", + "unRealizedProfit": "-1.69400000", + "liquidationPrice": "0", + "isolatedMargin": "0", + "notional": "51.22600000", + "marginAsset": "USDT", + "isolatedWallet": "0", + "initialMargin": "10.24520000", + "maintMargin": "0.33296900", + "positionInitialMargin": "10.24520000", + "openOrderInitialMargin": "0", + "adl": 0, + "bidNotional": "0", + "askNotional": "0", + "updateTime": 1729436057076, + } + ] m.register_uri("GET", url_matcher, json=json.dumps(response), status_code=200) pos = client.futures_position_information(symbol="LTCUSDT") - assert m.last_request.qs['symbol'][0] == 'LTCUSDT'.lower() - assert m.last_request.path == '/fapi/v3/positionrisk' + assert m.last_request.qs["symbol"][0] == "LTCUSDT".lower() + assert m.last_request.path == "/fapi/v3/positionrisk" + def test_futures_position_information_version_override(): with requests_mock.mock() as m: - url_matcher = re.compile(r"https:\/\/fapi.binance.com\/fapi\/v2\/positionRisk\?.+") - response = [{'symbol': 'LTCUSDT', 'positionSide': 'LONG', 'positionAmt': '0.700', 'entryPrice': '75.6', 'breakEvenPrice': '75.63024', 'markPrice': '73.18000000', 'unRealizedProfit': '-1.69400000', 'liquidationPrice': '0', 'isolatedMargin': '0', 'notional': '51.22600000', 'marginAsset': 'USDT', 'isolatedWallet': '0', 'initialMargin': '10.24520000', 'maintMargin': '0.33296900', 'positionInitialMargin': '10.24520000', 'openOrderInitialMargin': '0', 'adl': 0, 'bidNotional': '0', 'askNotional': '0', 'updateTime': 1729436057076}] + url_matcher = re.compile( + r"https:\/\/fapi.binance.com\/fapi\/v2\/positionRisk\?.+" + ) + response = [ + { + "symbol": "LTCUSDT", + "positionSide": "LONG", + "positionAmt": "0.700", + "entryPrice": "75.6", + "breakEvenPrice": "75.63024", + "markPrice": "73.18000000", + "unRealizedProfit": "-1.69400000", + "liquidationPrice": "0", + "isolatedMargin": "0", + "notional": "51.22600000", + "marginAsset": "USDT", + "isolatedWallet": "0", + "initialMargin": "10.24520000", + "maintMargin": "0.33296900", + "positionInitialMargin": "10.24520000", + "openOrderInitialMargin": "0", + "adl": 0, + "bidNotional": "0", + "askNotional": "0", + "updateTime": 1729436057076, + } + ] m.register_uri("GET", url_matcher, json=json.dumps(response), status_code=200) pos = client.futures_position_information(symbol="LTCUSDT", version=2) - assert m.last_request.qs['symbol'][0] == 'LTCUSDT'.lower() - assert m.last_request.path == '/fapi/v2/positionrisk' + assert m.last_request.qs["symbol"][0] == "LTCUSDT".lower() + assert m.last_request.path == "/fapi/v2/positionrisk" + def test_futures_account_balance(): with requests_mock.mock() as m: url_matcher = re.compile(r"https:\/\/fapi.binance.com\/fapi\/v3\/balance\?.+") m.register_uri("GET", url_matcher, json={}, status_code=200) client.futures_account_balance() - assert m.last_request.path == '/fapi/v3/balance' + assert m.last_request.path == "/fapi/v3/balance" + def test_futures_account_config(): with requests_mock.mock() as m: - url_matcher = re.compile(r"https:\/\/fapi.binance.com\/fapi\/v1\/accountConfig\?.+") + url_matcher = re.compile( + r"https:\/\/fapi.binance.com\/fapi\/v1\/accountConfig\?.+" + ) m.register_uri("GET", url_matcher, json={}, status_code=200) client.futures_account_config() - assert m.last_request.path == '/fapi/v1/accountconfig' \ No newline at end of file + assert m.last_request.path == "/fapi/v1/accountconfig" diff --git a/tests/test_get_order_book.py b/tests/test_get_order_book.py index dd2b823a..19cb8a53 100644 --- a/tests/test_get_order_book.py +++ b/tests/test_get_order_book.py @@ -9,38 +9,40 @@ def assert_ob(order_book): assert isinstance(order_book, dict) - assert 'lastUpdateId' in order_book - assert 'bids' in order_book - assert 'asks' in order_book + assert "lastUpdateId" in order_book + assert "bids" in order_book + assert "asks" in order_book - assert isinstance(order_book['bids'], list) - assert isinstance(order_book['asks'], list) + assert isinstance(order_book["bids"], list) + assert isinstance(order_book["asks"], list) - if order_book['bids']: - bid = order_book['bids'][0] + if order_book["bids"]: + bid = order_book["bids"][0] assert len(bid) == 2 assert all(isinstance(item, str) for item in bid[:2]) - if order_book['asks']: - ask = order_book['asks'][0] + if order_book["asks"]: + ask = order_book["asks"][0] assert len(ask) == 2 assert all(isinstance(item, str) for item in ask[:2]) + def test_get_order_book(client): try: - order_book = client.get_order_book(symbol='BTCUSDT') + order_book = client.get_order_book(symbol="BTCUSDT") assert_ob(order_book) except BinanceAPIException as e: pytest.fail(f"API request failed: {str(e)}") + def test_get_order_book_with_limit(client): try: - order_book = client.get_order_book(symbol='BTCUSDT', limit=5) + order_book = client.get_order_book(symbol="BTCUSDT", limit=5) assert_ob(order_book) - assert len(order_book['bids']) <= 5 - assert len(order_book['asks']) <= 5 + assert len(order_book["bids"]) <= 5 + assert len(order_book["asks"]) <= 5 except BinanceAPIException as e: pytest.fail(f"API request failed: {str(e)}") @@ -48,8 +50,10 @@ def test_get_order_book_with_limit(client): async def test_get_order_book_async(): try: - client = AsyncClient(api_key="api_key", api_secret="api_secret", https_proxy=proxy) - order_book = await client.get_order_book(symbol='BTCUSDT') + client = AsyncClient( + api_key="api_key", api_secret="api_secret", https_proxy=proxy + ) + order_book = await client.get_order_book(symbol="BTCUSDT") assert_ob(order_book) except BinanceAPIException as e: diff --git a/tests/test_historical_klines.py b/tests/test_historical_klines.py index 43161404..b775ee8f 100644 --- a/tests/test_historical_klines.py +++ b/tests/test_historical_klines.py @@ -63,7 +63,9 @@ def test_exact_amount(): json=second_res, ) klines = client.get_historical_klines( - symbol="BNBBTC", interval=Client.KLINE_INTERVAL_1MINUTE, start_str="1st March 2018" + symbol="BNBBTC", + interval=Client.KLINE_INTERVAL_1MINUTE, + start_str="1st March 2018", ) assert len(klines) == 500 @@ -280,6 +282,7 @@ def test_historical_kline_generator_empty_response(): with pytest.raises(StopIteration): next(klines) + def test_start_and_limit(): """Test start_str and limit work correctly with integer timestamp""" diff --git a/tests/test_ids.py b/tests/test_ids.py index 674eb5c3..27ade3cc 100644 --- a/tests/test_ids.py +++ b/tests/test_ids.py @@ -6,42 +6,53 @@ client = Client(api_key="api_key", api_secret="api_secret", ping=False) + def test_spot_id(): with requests_mock.mock() as m: m.post("https://api.binance.com/api/v3/order", json={}, status_code=200) client.create_order(symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1) - url_dict = dict(pair.split('=') for pair in m.last_request.text.split('&')) - assert url_dict['symbol'] == 'LTCUSDT' - assert url_dict['side'] == 'BUY' - assert url_dict['type'] == 'MARKET' - assert url_dict['quantity'] == '0.1' - assert url_dict['newClientOrderId'].startswith('x-HNA2TXFJ') + url_dict = dict(pair.split("=") for pair in m.last_request.text.split("&")) + assert url_dict["symbol"] == "LTCUSDT" + assert url_dict["side"] == "BUY" + assert url_dict["type"] == "MARKET" + assert url_dict["quantity"] == "0.1" + assert url_dict["newClientOrderId"].startswith("x-HNA2TXFJ") + def test_spot_limit_id(): with requests_mock.mock() as m: m.post("https://api.binance.com/api/v3/order", json={}, status_code=200) - client.order_limit_buy(symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1) - url_dict = dict(pair.split('=') for pair in m.last_request.text.split('&')) - assert url_dict['newClientOrderId'].startswith('x-HNA2TXFJ') + client.order_limit_buy( + symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1 + ) + url_dict = dict(pair.split("=") for pair in m.last_request.text.split("&")) + assert url_dict["newClientOrderId"].startswith("x-HNA2TXFJ") + def test_spot_market_id(): with requests_mock.mock() as m: m.post("https://api.binance.com/api/v3/order", json={}, status_code=200) - client.order_market_buy(symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1) - url_dict = dict(pair.split('=') for pair in m.last_request.text.split('&')) - assert url_dict['newClientOrderId'].startswith('x-HNA2TXFJ') + client.order_market_buy( + symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1 + ) + url_dict = dict(pair.split("=") for pair in m.last_request.text.split("&")) + assert url_dict["newClientOrderId"].startswith("x-HNA2TXFJ") + def test_swap_id(): with requests_mock.mock() as m: m.post("https://fapi.binance.com/fapi/v1/order", json={}, status_code=200) - client.futures_create_order(symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1) - url_dict = dict(pair.split('=') for pair in m.last_request.query.split('&')) + client.futures_create_order( + symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1 + ) + url_dict = dict(pair.split("=") for pair in m.last_request.query.split("&")) # why lowercase? check this later - assert url_dict['symbol'] == 'ltcusdt' - assert url_dict['side'] == 'buy' - assert url_dict['type'] == 'market' - assert url_dict['quantity'] == '0.1' - assert url_dict['newClientOrderId'.lower()].startswith('x-Cb7ytekJ'.lower()) + assert url_dict["symbol"] == "ltcusdt" + assert url_dict["side"] == "buy" + assert url_dict["type"] == "market" + assert url_dict["quantity"] == "0.1" + assert url_dict["newClientOrderId".lower()].startswith("x-Cb7ytekJ".lower()) + def test_swap_batch_id(): with requests_mock.mock() as m: @@ -50,66 +61,89 @@ def test_swap_batch_id(): orders = [order, order] client.futures_place_batch_order(batchOrders=orders) text = m.last_request.text - assert 'x-Cb7ytekJ' in text + assert "x-Cb7ytekJ" in text + def test_coin_id(): with requests_mock.mock() as m: m.post("https://dapi.binance.com/dapi/v1/order", json={}, status_code=200) - client.futures_coin_create_order(symbol="LTCUSD_PERP", side="BUY", type="MARKET", quantity=0.1) - url_dict = dict(pair.split('=') for pair in m.last_request.text.split('&')) + client.futures_coin_create_order( + symbol="LTCUSD_PERP", side="BUY", type="MARKET", quantity=0.1 + ) + url_dict = dict(pair.split("=") for pair in m.last_request.text.split("&")) # why lowercase? check this later - assert url_dict['symbol'] == 'LTCUSD_PERP' - assert url_dict['side'] == 'BUY' - assert url_dict['type'] == 'MARKET' - assert url_dict['quantity'] == '0.1' - assert url_dict['newClientOrderId'].startswith('x-Cb7ytekJ') + assert url_dict["symbol"] == "LTCUSD_PERP" + assert url_dict["side"] == "BUY" + assert url_dict["type"] == "MARKET" + assert url_dict["quantity"] == "0.1" + assert url_dict["newClientOrderId"].startswith("x-Cb7ytekJ") def test_coin_batch_id(): with requests_mock.mock() as m: m.post("https://dapi.binance.com/dapi/v1/batchOrders", json={}, status_code=200) - order = {"symbol": "BTCUSD_PERP", "side": "BUY", "type": "MARKET", "quantity": 0.1} + order = { + "symbol": "BTCUSD_PERP", + "side": "BUY", + "type": "MARKET", + "quantity": 0.1, + } orders = [order, order] client.futures_coin_place_batch_order(batchOrders=orders) text = m.last_request.text - assert 'x-Cb7ytekJ' in text + assert "x-Cb7ytekJ" in text def test_papi_um_id(): with requests_mock.mock() as m: m.post("https://papi.binance.com/papi/v1/um/order", json={}, status_code=200) - client.papi_create_um_order(symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1) - url_dict = dict(pair.split('=') for pair in m.last_request.text.split('&')) + client.papi_create_um_order( + symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1 + ) + url_dict = dict(pair.split("=") for pair in m.last_request.text.split("&")) # why lowercase? check this later - assert url_dict['symbol'] == 'LTCUSDT' - assert url_dict['side'] == 'BUY' - assert url_dict['type'] == 'MARKET' - assert url_dict['quantity'] == '0.1' - assert url_dict['newClientOrderId'].startswith('x-Cb7ytekJ') + assert url_dict["symbol"] == "LTCUSDT" + assert url_dict["side"] == "BUY" + assert url_dict["type"] == "MARKET" + assert url_dict["quantity"] == "0.1" + assert url_dict["newClientOrderId"].startswith("x-Cb7ytekJ") def test_papi_cm_id(): with requests_mock.mock() as m: m.post("https://papi.binance.com/papi/v1/cm/order", json={}, status_code=200) - client.papi_create_cm_order(symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1) - url_dict = dict(pair.split('=') for pair in m.last_request.text.split('&')) + client.papi_create_cm_order( + symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1 + ) + url_dict = dict(pair.split("=") for pair in m.last_request.text.split("&")) # why lowercase? check this later - assert url_dict['symbol'] == 'LTCUSDT' - assert url_dict['side'] == 'BUY' - assert url_dict['type'] == 'MARKET' - assert url_dict['quantity'] == '0.1' - assert url_dict['newClientOrderId'].startswith('x-Cb7ytekJ') + assert url_dict["symbol"] == "LTCUSDT" + assert url_dict["side"] == "BUY" + assert url_dict["type"] == "MARKET" + assert url_dict["quantity"] == "0.1" + assert url_dict["newClientOrderId"].startswith("x-Cb7ytekJ") @pytest.mark.asyncio() async def test_spot_id_async(): - clientAsync = AsyncClient(api_key="api_key", api_secret="api_secret") # reuse client later + clientAsync = AsyncClient( + api_key="api_key", api_secret="api_secret" + ) # reuse client later with aioresponses() as m: + def handler(url, **kwargs): - client_order_id = kwargs['data'][0][1] - assert client_order_id.startswith('x-HNA2TXFJ') - m.post("https://api.binance.com/api/v3/order", payload={'id': 1}, status=200, callback=handler) - await clientAsync.create_order(symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1) + client_order_id = kwargs["data"][0][1] + assert client_order_id.startswith("x-HNA2TXFJ") + + m.post( + "https://api.binance.com/api/v3/order", + payload={"id": 1}, + status=200, + callback=handler, + ) + await clientAsync.create_order( + symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1 + ) await clientAsync.close_connection() @@ -117,22 +151,41 @@ def handler(url, **kwargs): async def test_swap_id_async(): clientAsync = AsyncClient(api_key="api_key", api_secret="api_secret") with aioresponses() as m: + def handler(url, **kwargs): - client_order_id = kwargs['data'][0][1] - assert client_order_id.startswith('x-Cb7ytekJ') - m.post("https://fapi.binance.com/fapi/v1/order", payload={'id': 1}, status=200, callback=handler) - await clientAsync.futures_create_order(symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1) + client_order_id = kwargs["data"][0][1] + assert client_order_id.startswith("x-Cb7ytekJ") + + m.post( + "https://fapi.binance.com/fapi/v1/order", + payload={"id": 1}, + status=200, + callback=handler, + ) + await clientAsync.futures_create_order( + symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1 + ) await clientAsync.close_connection() + @pytest.mark.asyncio() async def test_papi_um_id_async(): clientAsync = AsyncClient(api_key="api_key", api_secret="api_secret") with aioresponses() as m: + def handler(url, **kwargs): - client_order_id = kwargs['data'][0][1] - assert client_order_id.startswith('x-Cb7ytekJ') - m.post("https://papi.binance.com/papi/v1/um/order", payload={'id': 1}, status=200, callback=handler) - await clientAsync.papi_create_um_order(symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1) + client_order_id = kwargs["data"][0][1] + assert client_order_id.startswith("x-Cb7ytekJ") + + m.post( + "https://papi.binance.com/papi/v1/um/order", + payload={"id": 1}, + status=200, + callback=handler, + ) + await clientAsync.papi_create_um_order( + symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1 + ) await clientAsync.close_connection() @@ -140,31 +193,58 @@ def handler(url, **kwargs): async def test_papi_cm_id_async(): clientAsync = AsyncClient(api_key="api_key", api_secret="api_secret") with aioresponses() as m: + def handler(url, **kwargs): - client_order_id = kwargs['data'][0][1] - assert client_order_id.startswith('x-Cb7ytekJ') - m.post("https://papi.binance.com/papi/v1/cm/order", payload={'id': 1}, status=200, callback=handler) - await clientAsync.papi_create_cm_order(symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1) + client_order_id = kwargs["data"][0][1] + assert client_order_id.startswith("x-Cb7ytekJ") + + m.post( + "https://papi.binance.com/papi/v1/cm/order", + payload={"id": 1}, + status=200, + callback=handler, + ) + await clientAsync.papi_create_cm_order( + symbol="LTCUSDT", side="BUY", type="MARKET", quantity=0.1 + ) await clientAsync.close_connection() + @pytest.mark.asyncio() async def test_coin_id_async(): clientAsync = AsyncClient(api_key="api_key", api_secret="api_secret") with aioresponses() as m: + def handler(url, **kwargs): - client_order_id = kwargs['data'][0][1] - assert client_order_id.startswith('x-Cb7ytekJ') - m.post("https://dapi.binance.com/dapi/v1/order", payload={'id': 1}, status=200, callback=handler) - await clientAsync.futures_coin_create_order(symbol="LTCUSD_PERP", side="BUY", type="MARKET", quantity=0.1) + client_order_id = kwargs["data"][0][1] + assert client_order_id.startswith("x-Cb7ytekJ") + + m.post( + "https://dapi.binance.com/dapi/v1/order", + payload={"id": 1}, + status=200, + callback=handler, + ) + await clientAsync.futures_coin_create_order( + symbol="LTCUSD_PERP", side="BUY", type="MARKET", quantity=0.1 + ) await clientAsync.close_connection() + @pytest.mark.asyncio() async def test_swap_batch_id_async(): with aioresponses() as m: clientAsync = AsyncClient(api_key="api_key", api_secret="api_secret") + def handler(url, **kwargs): - assert 'x-Cb7ytekJ' in kwargs['data'][0][1] - m.post("https://fapi.binance.com/fapi/v1/batchOrders", payload={'id': 1}, status=200, callback=handler) + assert "x-Cb7ytekJ" in kwargs["data"][0][1] + + m.post( + "https://fapi.binance.com/fapi/v1/batchOrders", + payload={"id": 1}, + status=200, + callback=handler, + ) order = {"symbol": "LTCUSDT", "side": "BUY", "type": "MARKET", "quantity": 0.1} orders = [order, order] await clientAsync.futures_place_batch_order(batchOrders=orders) @@ -175,10 +255,22 @@ def handler(url, **kwargs): async def test_coin_batch_id_async(): with aioresponses() as m: clientAsync = AsyncClient(api_key="api_key", api_secret="api_secret") + def handler(url, **kwargs): - assert 'x-Cb7ytekJ' in kwargs['data'][0][1] - m.post("https://dapi.binance.com/dapi/v1/batchOrders", payload={'id': 1}, status=200, callback=handler) - order = {"symbol": "LTCUSD_PERP", "side": "BUY", "type": "MARKET", "quantity": 0.1} + assert "x-Cb7ytekJ" in kwargs["data"][0][1] + + m.post( + "https://dapi.binance.com/dapi/v1/batchOrders", + payload={"id": 1}, + status=200, + callback=handler, + ) + order = { + "symbol": "LTCUSD_PERP", + "side": "BUY", + "type": "MARKET", + "quantity": 0.1, + } orders = [order, order] await clientAsync.futures_coin_place_batch_order(batchOrders=orders) await clientAsync.close_connection() diff --git a/tests/test_ping.py b/tests/test_ping.py index af55267a..495e6004 100644 --- a/tests/test_ping.py +++ b/tests/test_ping.py @@ -1,4 +1,3 @@ - from binance.client import AsyncClient import os import pytest @@ -7,42 +6,58 @@ proxies = {} proxy = os.getenv("PROXY") + def test_papi_ping_sync(client): ping_response = client.papi_ping() assert ping_response is not None + def test_ping_sync(client): ping_response = client.ping() assert ping_response is not None + def test_futures_ping(client): ping_response = client.futures_ping() assert ping_response is not None + def test_coin_ping(client): ping_response = client.futures_coin_ping() assert ping_response is not None + @pytest.mark.asyncio() async def test_papi_ping_async(): - clientAsync = AsyncClient(api_key="api_key", api_secret="api_secret", https_proxy=proxy) + clientAsync = AsyncClient( + api_key="api_key", api_secret="api_secret", https_proxy=proxy + ) ping_response = await clientAsync.papi_ping() assert ping_response is not None + @pytest.mark.asyncio() async def test_ping_async(): - clientAsync = AsyncClient(api_key="api_key", api_secret="api_secret", https_proxy=proxy) + clientAsync = AsyncClient( + api_key="api_key", api_secret="api_secret", https_proxy=proxy + ) ping_response = await clientAsync.ping() assert ping_response is not None + @pytest.mark.asyncio() async def test_futures_ping_async(): - clientAsync = AsyncClient(api_key="api_key", api_secret="api_secret", https_proxy=proxy) + clientAsync = AsyncClient( + api_key="api_key", api_secret="api_secret", https_proxy=proxy + ) ping_response = await clientAsync.futures_ping() assert ping_response is not None + @pytest.mark.asyncio() async def test_coin_ping_async(): - clientAsync = AsyncClient(api_key="api_key", api_secret="api_secret", https_proxy=proxy) + clientAsync = AsyncClient( + api_key="api_key", api_secret="api_secret", https_proxy=proxy + ) ping_response = await clientAsync.futures_coin_ping() - assert ping_response is not None \ No newline at end of file + assert ping_response is not None diff --git a/tests/test_socket_manager.py b/tests/test_socket_manager.py index 763cd788..64e7fac1 100644 --- a/tests/test_socket_manager.py +++ b/tests/test_socket_manager.py @@ -3,8 +3,9 @@ def assert_message(msg): - assert msg['stream'] == '!ticker@arr' - assert len(msg['data']) > 0 + assert msg["stream"] == "!ticker@arr" + assert len(msg["data"]) > 0 + @pytest.mark.asyncio() async def test_ticker_socket(): @@ -20,4 +21,4 @@ async def test_ticker_socket(): except Exception as e: print(f"An error occurred: {e}") - await client.close_connection() \ No newline at end of file + await client.close_connection() diff --git a/tests/test_streams.py b/tests/test_streams.py index b371ff3a..b307305e 100644 --- a/tests/test_streams.py +++ b/tests/test_streams.py @@ -7,9 +7,9 @@ async def test_socket_stopped_on_aexit(): client = AsyncClient() bm = BinanceSocketManager(client) - ts1 = bm.trade_socket('BNBBTC') + ts1 = bm.trade_socket("BNBBTC") async with ts1: pass - ts2 = bm.trade_socket('BNBBTC') + ts2 = bm.trade_socket("BNBBTC") assert ts2 is not ts1, "socket should be removed from _conn on exit" await client.close_connection() diff --git a/tests/test_threaded_socket_manager.py b/tests/test_threaded_socket_manager.py index 3b00dce3..9adabfd5 100644 --- a/tests/test_threaded_socket_manager.py +++ b/tests/test_threaded_socket_manager.py @@ -1,5 +1,3 @@ - - from binance import ThreadedWebsocketManager @@ -8,17 +6,19 @@ twm: ThreadedWebsocketManager + def handle_socket_message(msg): global received_ohlcv, received_depth print(msg) - if 'e' in msg: - if msg['e'] == 'depthUpdate': + if "e" in msg: + if msg["e"] == "depthUpdate": received_depth = True - if msg['e'] == 'kline': + if msg["e"] == "kline": received_ohlcv = True if received_depth and received_ohlcv: twm.stop() + def test_threaded_socket_manager(): global twm twm = ThreadedWebsocketManager(api_key="", api_secret="", testnet=True) @@ -31,4 +31,4 @@ def test_threaded_socket_manager(): twm.start_depth_socket(callback=handle_socket_message, symbol=symbol) - twm.join() \ No newline at end of file + twm.join()