Python urllib3.exceptions.ProtocolError() Examples
The following are 30
code examples of urllib3.exceptions.ProtocolError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
urllib3.exceptions
, or try the search function
.
Example #1
Source File: discovery.py From python-base with Apache License 2.0 | 7 votes |
def _load_server_info(self): def just_json(_, serialized): return serialized if not self._cache.get('version'): try: self._cache['version'] = { 'kubernetes': self.client.request('get', '/version', serializer=just_json) } except (ValueError, MaxRetryError) as e: if isinstance(e, MaxRetryError) and not isinstance(e.reason, ProtocolError): raise if not self.client.configuration.host.startswith("https://"): raise ValueError("Host value %s should start with https:// when talking to HTTPS endpoint" % self.client.configuration.host) else: raise self.__version = self._cache['version']
Example #2
Source File: resources.py From k8s-sidecar with MIT License | 6 votes |
def _watch_resource_loop(mode, *args): while True: try: # Always wait to slow down the loop in case of exceptions sleep(os.getenv("ERROR_THROTTLE_SLEEP", 5)) if mode == "SLEEP": listResources(*args) sleep(os.getenv("SLEEP_TIME", 60)) else: _watch_resource_iterator(*args) except ApiException as e: if e.status != 500: print(f"{timestamp()} ApiException when calling kubernetes: {e}\n") else: raise except ProtocolError as e: print(f"{timestamp()} ProtocolError when calling kubernetes: {e}\n") except MaxRetryError as e: print(f"{timestamp()} MaxRetryError when calling kubernetes: {e}\n") except Exception as e: print(f"{timestamp()} Received unknown exception: {e}\n")
Example #3
Source File: data_checks.py From Binance-bot with GNU General Public License v3.0 | 6 votes |
def route_check_altlast(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip): calc_done = False route_gain = -1 bid_p2 = -1 ask_p3 = -1 ask_p1 = -1 while calc_done == False: try: ask_p1 = float(client.depth(pair_1, limit = 5)['asks'][0][0]) - float(pair_1_pip) bid_p2 = float(client.depth(pair_2, limit = 5)['bids'][0][0]) + float(pair_2_pip) ask_p3 = float(client.depth(pair_3, limit = 5)['asks'][0][0]) - float(pair_3_pip) except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str(e.__traceback__)) client.set_offset() else: # route_gain = ((ask_p1 - pair_1_pip) / ((bid_p2 + pair_2_pip)) * (ask_p3 - pair_3_pip)) route_gain = ask_p1 / bid_p2 * ask_p3 calc_done = True return (route_gain, ask_p1, bid_p2, ask_p3)
Example #4
Source File: helper.py From cc-utils with Apache License 2.0 | 6 votes |
def wait_until_deployment_available(self, namespace: str, name: str, timeout_seconds: int=60): '''Block until the given deployment has at least one available replica (or timeout) Return `True` if the deployment is available, `False` if a timeout occured. ''' not_empty(namespace) not_empty(name) w = watch.Watch() # Work around IncompleteRead errors resulting in ProtocolErrors - no fault of our own start_time = int(time.time()) while (start_time + timeout_seconds) > time.time(): try: for event in w.stream( self.apps_api.list_namespaced_deployment, namespace=namespace, timeout_seconds=timeout_seconds ): deployment_spec = event['object'] if deployment_spec is not None: if deployment_spec.metadata.name == name: if deployment_spec.status.available_replicas is not None \ and deployment_spec.status.available_replicas > 0: return True # Check explicitly if timeout occurred if (start_time + timeout_seconds) < time.time(): return False # Regular Watch.stream() timeout occurred, no need for further checks return False except ProtocolError: info('http connection error - ignored')
Example #5
Source File: data_checks.py From Binance-bot with GNU General Public License v3.0 | 6 votes |
def route_check_altfirst(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip): calc_done = False route_gain = -1 bid_p1 = -1 ask_p2 = -1 bid_p3 = -1 while calc_done == False: try: bid_p1 = float(client.depth(pair_1, limit = 5)['bids'][0][0]) ask_p2 = float(client.depth(pair_2, limit = 5)['asks'][0][0]) bid_p3 = float(client.depth(pair_3, limit = 5)['bids'][0][0]) except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str(e.__traceback__)) client.set_offset() else: route_gain = (1 / (bid_p1 + pair_1_pip)) * (ask_p2 - pair_2_pip) / (bid_p3 + pair_3_pip) calc_done = True return (route_gain, bid_p1, ask_p2, bid_p3)
Example #6
Source File: mult_arbit.py From Binance-bot with GNU General Public License v3.0 | 6 votes |
def get_open_ords(self, pair): error_count = 0 got_ords = False open_ords = {} # self.lg.log('Getting open orders for pair ' + pair) while not got_ords and error_count < 10: try: open_ords = client.openOrders(pair) except ( MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str(e.__traceback__) + ' ' + 'Open order request failed try again') error_count += 1 time.sleep(1) client.set_offset() else: got_ords = True finally: if error_count >= 10: self.lg.log('Open orders check failed 10 times') return open_ords
Example #7
Source File: mult_arbit.py From Binance-bot with GNU General Public License v3.0 | 6 votes |
def get_ord_book(self, pair): error_count = 0 book_returned = False ord_book = {} fail = False self.lg.log('Getting order book for pair ' + pair) while not book_returned and not fail: try: ord_book = client.depth(pair, limit=5) except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str(e.__traceback__) + ' ' + 'Order book retrieve for ' + pair + ' failed, keep trying') error_count += 1 time.sleep(1) client.set_offset() else: book_returned = True finally: if error_count >= 5: self.lg.log("Tried to get order book 5 times and failed") fail = True return {"ord_book": ord_book, "fail_flag": fail}
Example #8
Source File: api.py From Binance-bot with GNU General Public License v3.0 | 6 votes |
def set_offset(self): got_time = False while not got_time: try: cur_time = int(time.time() * 1000) bintime = int(self.time()['serverTime']) time_diff = cur_time - bintime if time_diff > 0: self.time_offset = time_diff else: self.time_offset = 500 except (InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: print(str(e) + ' ' + str(e.__traceback__) + 'Time check failed, retry') time.sleep(.5) else: got_time = True
Example #9
Source File: data_checks.py From Binance-bot with GNU General Public License v3.0 | 6 votes |
def route_check_t3_ask_oth_lastprice(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip): route_gain = -1 ask_p3 = -1 calc_done = False t_1_price = -1 t_2_price = -1 while calc_done == False: try: prices = client.allPrices() for p in prices: symbol = p['symbol'] if symbol == pair_1: t_1_price = float(p['price']) - pair_1_pip if symbol == pair_2: t_2_price = float(p['price']) + pair_2_pip ask_p3 = float(client.depth(pair_3, limit=5)['asks'][0][0]) - pair_3_pip except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str(e.__traceback__)) client.set_offset() else: route_gain = t_1_price / t_2_price * ask_p3 calc_done = True return (route_gain, t_1_price, t_2_price, ask_p3)
Example #10
Source File: data_checks.py From Binance-bot with GNU General Public License v3.0 | 6 votes |
def route_check_alt_last_lastprice(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip): route_gain = -1 calc_done = False t_1_price = -1 t_2_price = -1 t_3_price = -1 while calc_done == False: try: prices = client.allPrices() for p in prices: symbol = p['symbol'] if symbol == pair_1: t_1_price = float(p['price']) if symbol == pair_2: t_2_price = float(p['price']) if symbol == pair_3: t_3_price = float(p['price']) except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str(e.__traceback__)) client.set_offset() else: route_gain = (t_1_price / (t_2_price) * t_3_price) calc_done = True return route_gain
Example #11
Source File: data_checks.py From Binance-bot with GNU General Public License v3.0 | 5 votes |
def route_check_altlast_take_t2_t3(self, pair_1, pair_2, pair_3, pair_1_pip): calc_done = False route_gain = -1 while calc_done == False: try: ask_p1 = float(client.depth(pair_1, limit = 5)['asks'][0][0]) ask_p2 = float(client.depth(pair_2, limit = 5)['asks'][0][0]) bid_p3 = float(client.depth(pair_3, limit = 5)['bids'][0][0]) except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str(e.__traceback__)) client.set_offset() else: route_gain = (ask_p1 - pair_1_pip) / ask_p2 * bid_p3 calc_done = True return route_gain
Example #12
Source File: data_checks.py From Binance-bot with GNU General Public License v3.0 | 5 votes |
def route_check_altlast_take_t2(self, pair_1, pair_2, pair_3, pair_1_pip, pair_3_pip): calc_done = False route_gain = -1 while calc_done == False: try: ask_p1 = float(client.depth(pair_1, limit = 5)['asks'][0][0]) ask_p2 = float(client.depth(pair_2, limit = 5)['asks'][0][0]) ask_p3 = float(client.depth(pair_3, limit = 5)['asks'][0][0]) except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str(e.__traceback__)) else: route_gain = ((ask_p1 - pair_1_pip) / ((ask_p2)) * (ask_p3 - pair_3_pip)) calc_done = True return route_gain
Example #13
Source File: data_checks.py From Binance-bot with GNU General Public License v3.0 | 5 votes |
def get_low_ask(self, pair): ask = -1 got_ask = False while got_ask == False: try: ask = client.depth(pair, limit = 5)['asks'][0][0] except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str(e.__traceback__)) client.set_offset() else: got_ask = True return ask
Example #14
Source File: data_checks.py From Binance-bot with GNU General Public License v3.0 | 5 votes |
def get_high_bid(self, pair): bid = -1 got_bid = False while got_bid == False: try: bid = client.depth(pair, limit = 5)['bids'][0][0] except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str(e.__traceback__)) client.set_offset() else: got_bid = True return bid
Example #15
Source File: downloader.py From vmaas with GNU General Public License v2.0 | 5 votes |
def _retry_download(self, download_item): for _ in range(self.retry_count): try: self._download(download_item) break except (ProtocolError, ConnectionError): self.logger.exception("Download of '%s' failed: ", download_item.source_url) download_item.status_code = -1
Example #16
Source File: multifolderclone.py From folderclone with GNU General Public License v3.0 | 5 votes |
def _apicall(self,request): resp = None tries = 0 while True: tries += 1 if tries > self.max_retries: return None try: resp = request.execute() except HttpError as error: try: error_details = json.loads(error.content.decode('utf-8')) except json.decoder.JSONDecodeError: time.sleep(self.sleep_time) continue reason = error_details['error']['errors'][0]['reason'] # self._add_error_stats(reason) if reason == 'userRateLimitExceeded': return False elif reason == 'storageQuotaExceeded': print('Got storageQuotaExceeded error. You are not using a Shared Drive.') return False elif reason == 'teamDriveFileLimitExceeded': raise RuntimeError('The Shared Drive is full. No more files can be copied to it.') elif self.error_codes[reason]: time.sleep(self.sleep_time) continue else: return None except (socket.error,ProtocolError,TransportError) as e: reason = str(e) # self._add_error_stats(reason) time.sleep(self.sleep_time) continue else: return resp
Example #17
Source File: bot.py From bot with GNU General Public License v3.0 | 5 votes |
def act(self, count=0): if self.aborting: return actions = self.get_actions(self.settings or {}) while datetime.datetime.now() < self.end_time: try: self.shuffle_actions(actions) self.logger.warning("shuffled actions: %s" % list(map(lambda a: a["name"], actions))) for f in actions: if self.aborting: self.logger.warning("ABORTING") return self.logger.warning("RUN: %s" % f["name"]) f["fun"]() count = 0 sleep(1 * 60) sleep(2 * 60) except NoSuchElementException as exc: # if changes to IG layout, upload the file to help us locate the change file_path = os.path.join(gettempdir(), '{}.html'.format(time.strftime('%Y%m%d-%H%M%S'))) with open(file_path, 'wb') as fp: fp.write(self.browser.page_source.encode('utf8')) print('{0}\nIf raising an issue, please also upload the file located at:\n{1}\n{0}'.format( '*' * 70, file_path)) # full stacktrace when raising Github issue self.logger.exception(exc) except (ConnectionRefusedError, RemoteDisconnected, ProtocolError, MaxRetryError, AttributeError) as exc: return self.try_again(count, exc) except Exception as exc: if 'RemoteDisconnected' in str(exc): return self.try_again(count, exc) self.logger.error("Excepiton in act(): %s \n %s" % (exc, traceback.format_exc())) raise
Example #18
Source File: docker_quickstart.py From bot with GNU General Public License v3.0 | 5 votes |
def run(count=0): global bot try: bot = Bot(multi_logs=True, selenium_local_session=False, proxy_address_port=get_proxy(os.environ.get('INSTA_USER')), disable_image_load=True) selenium_url = "http://%s:%d/wd/hub" % (os.environ.get('SELENIUM', 'selenium'), 4444) bot.set_selenium_remote_session(logger=logging.getLogger(), selenium_url=selenium_url, selenium_driver=selenium_driver(selenium_url)) bot.login() bot.set_settings() bot.act() except (NewConnectionError, WebDriverException) as exc: bot.logger.warning("Exception in run: %s; try again: count=%s" % (exc, count)) if count > 3: print("Exception in run(): %s \n %s" % (exc, traceback.format_exc())) report_exception(exc) else: run(count=count + 1) except (ProtocolError, MaxRetryError) as exc: bot.logger.error("Abort because of %s; \n%s" % (exc, traceback.format_exc())) return except Exception as exc: print("Exception in run(): %s \n %s" % (exc, traceback.format_exc())) report_exception(exc) finally: print("END") bot.end()
Example #19
Source File: docker_tryLogin.py From bot with GNU General Public License v3.0 | 5 votes |
def run(count=0): global bot try: bot = Bot(multi_logs=True, selenium_local_session=False, proxy_address_port=get_proxy(os.environ.get('INSTA_USER')), disable_image_load=False) selenium_url = "http://%s:%d/wd/hub" % (os.environ.get('SELENIUM', 'selenium'), 4444) bot.set_selenium_remote_session(logger=logging.getLogger(), selenium_url=selenium_url, selenium_driver=selenium_driver(selenium_url)) bot.try_first_login() except (NewConnectionError, NewConnectionError) as exc: bot.logger.warning("Exception in run: %s; try again: count=%s" % (exc, count)) if count > 3: print("Exception in run(): %s \n %s" % (exc, traceback.format_exc())) report_exception(exc) else: run(count=count + 1) except (ProtocolError, MaxRetryError) as exc: bot.logger.error("Abort because of %s; \n%s" % (exc, traceback.format_exc())) return except Exception as exc: print("Exception in run(): %s \n %s" % (exc, traceback.format_exc())) report_exception(exc) finally: print("END") bot.end()
Example #20
Source File: requester.py From XSStrike with GNU General Public License v3.0 | 5 votes |
def requester(url, data, headers, GET, delay, timeout): if getVar('jsonData'): data = converter(data) elif getVar('path'): url = converter(data, url) data = [] GET, POST = True, False time.sleep(delay) user_agents = ['Mozilla/5.0 (X11; Linux i686; rv:60.0) Gecko/20100101 Firefox/60.0', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36' 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 OPR/43.0.2442.991'] if 'User-Agent' not in headers: headers['User-Agent'] = random.choice(user_agents) elif headers['User-Agent'] == '$': headers['User-Agent'] = random.choice(user_agents) logger.debug('Requester url: {}'.format(url)) logger.debug('Requester GET: {}'.format(GET)) logger.debug_json('Requester data:', data) logger.debug_json('Requester headers:', headers) try: if GET: response = requests.get(url, params=data, headers=headers, timeout=timeout, verify=False, proxies=core.config.proxies) elif getVar('jsonData'): response = requests.post(url, json=data, headers=headers, timeout=timeout, verify=False, proxies=core.config.proxies) else: response = requests.post(url, data=data, headers=headers, timeout=timeout, verify=False, proxies=core.config.proxies) return response except ProtocolError: logger.warning('WAF is dropping suspicious requests.') logger.warning('Scanning will continue after 10 minutes.') time.sleep(600)
Example #21
Source File: etcd.py From patroni with MIT License | 5 votes |
def _do_http_request(self, retry, machines_cache, request_executor, method, path, fields=None, **kwargs): some_request_failed = False for i, base_uri in enumerate(machines_cache): if i > 0: logger.info("Retrying on %s", base_uri) try: response = request_executor(method, base_uri + path, fields=fields, **kwargs) response.data.decode('utf-8') self._check_cluster_id(response) if some_request_failed: self.set_base_uri(base_uri) self._refresh_machines_cache() return response except (HTTPError, HTTPException, socket.error, socket.timeout) as e: self.http.clear() # switch to the next etcd node because we don't know exactly what happened, # whether the key didn't received an update or there is a network problem. if not retry and i + 1 < len(machines_cache): self.set_base_uri(machines_cache[i + 1]) if (isinstance(fields, dict) and fields.get("wait") == "true" and isinstance(e, (ReadTimeoutError, ProtocolError))): logger.debug("Watch timed out.") raise etcd.EtcdWatchTimedOut("Watch timed out: {0}".format(e), cause=e) logger.error("Request to server %s failed: %r", base_uri, e) logger.info("Reconnection allowed, looking for another server.") if not retry: raise etcd.EtcdException('{0} {1} request failed'.format(method, path)) some_request_failed = True raise etcd.EtcdConnectionFailed('No more machines in the cluster')
Example #22
Source File: turtle_trade.py From Binance-bot with GNU General Public License v3.0 | 5 votes |
def get_klines(self, pair, interval, limit): klines = [] got_klines = False while not got_klines: try: klines = client.klines(pair, interval=interval, limit=limit) except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: print(str(e) + ' ' + str(e.__traceback__)) client.set_offset() else: got_klines = True return klines
Example #23
Source File: doc.py From bot with MIT License | 5 votes |
def _fetch_inventory(self, inventory_url: str) -> Optional[dict]: """Get and return inventory from `inventory_url`. If fetching fails, return None.""" fetch_func = functools.partial(intersphinx.fetch_inventory, SPHINX_MOCK_APP, '', inventory_url) for retry in range(1, FAILED_REQUEST_RETRY_AMOUNT+1): try: package = await self.bot.loop.run_in_executor(None, fetch_func) except ConnectTimeout: log.error( f"Fetching of inventory {inventory_url} timed out," f" trying again. ({retry}/{FAILED_REQUEST_RETRY_AMOUNT})" ) except ProtocolError: log.error( f"Connection lost while fetching inventory {inventory_url}," f" trying again. ({retry}/{FAILED_REQUEST_RETRY_AMOUNT})" ) except HTTPError as e: log.error(f"Fetching of inventory {inventory_url} failed with status code {e.response.status_code}.") return None except ConnectionError: log.error(f"Couldn't establish connection to inventory {inventory_url}.") return None else: return package log.error(f"Fetching of inventory {inventory_url} failed.") return None
Example #24
Source File: discovery.py From openshift-restclient-python with Apache License 2.0 | 5 votes |
def _load_server_info(self): def just_json(_, serialized): return serialized if not self._cache.get('version'): try: self._cache['version'] = { 'kubernetes': self.client.request('get', '/version', serializer=just_json) } except (ValueError, MaxRetryError) as e: if isinstance(e, MaxRetryError) and not isinstance(e.reason, ProtocolError): raise if not self.client.configuration.host.startswith("https://"): raise ValueError("Host value %s should start with https:// when talking to HTTPS endpoint" % self.client.configuration.host) else: raise try: self._cache['version']['openshift'] = self.client.request( 'get', '/version/openshift', serializer=just_json, ) except ApiException: pass self.__version = self._cache['version']
Example #25
Source File: Salesforce.py From CumulusCI with BSD 3-Clause "New" or "Revised" License | 5 votes |
def create_webdriver_with_retry(self, *args, **kwargs): """Call the Create Webdriver keyword. Retry on connection resets which can happen if custom domain propagation is slow. """ # Get selenium without referencing selenium.driver which doesn't exist yet selenium = self.builtin.get_library_instance("SeleniumLibrary") for _ in range(12): try: return selenium.create_webdriver(*args, **kwargs) except ProtocolError: # Give browser some more time to start up time.sleep(5) raise Exception("Could not connect to remote webdriver after 1 minute")
Example #26
Source File: sentry-kubernetes.py From sentry-kubernetes with Apache License 2.0 | 5 votes |
def main(): parser = argparse.ArgumentParser() parser.add_argument("--log-level", default=LOG_LEVEL) args = parser.parse_args() log_level = args.log_level.upper() logging.basicConfig(format="%(asctime)s %(message)s", level=log_level) logging.debug("log_level: %s" % log_level) try: config.load_incluster_config() except: config.load_kube_config() while True: try: watch_loop() except ApiException as e: logging.error( "Exception when calling CoreV1Api->list_event_for_all_namespaces: %s\n" % e ) time.sleep(5) except ProtocolError: logging.warning("ProtocolError exception. Continuing...") except Exception as e: logging.exception("Unhandled exception occurred.")
Example #27
Source File: mult_arbit.py From Binance-bot with GNU General Public License v3.0 | 5 votes |
def place_order_onetry(self, pair, quant, price, side, test=False): status = 'not_placed' orderID = '0' trade = {} if test: self.lg.log('Would have placed order as: pair = ' + pair + ', quant = ' + str(quant) + ', price = ' + str(price) + ', side = ' + side) status = 'was_tested' elif not test: self.lg.log('Placing order as pair = ' + pair + ', quant = ' + str(quant) + ', price = ' + str(price) + ', side = ' + side) try: if side == 'sell': trade = client.newLimitSellOrder(pair, quant, price) elif side == 'buy': trade = client.newLimitBuyOrder(pair, quant, price) except MalformedRequest as e: self.lg.log( str(e) + ' ' + str(e.__traceback__) + ' Tried to place order as pair = ' + pair + ', quant = ' + str(quant) + ', price = ' + str(price) + ', side = ' + side) client.set_offset() except StatusUnknown as e: self.lg.log( str(e) + ' ' + str(e.__traceback__) + 'API returned StatusUnknown, checking for placed order') order = self.check_for_open(pair) fail = order["fail_flag"] if not fail: orderID = order["order_ID"] status = order["status"] except (InternalError, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log( str(e) + ' ' + str(e.__traceback__) + " Some sort of connection or internal error occured") else: status = trade["status"] orderID = trade["orderId"] self.lg.log('Returning: orderID = ' + str(orderID) + ', status = ' + status) return {"orderID": orderID, "status": status}
Example #28
Source File: mult_arbit.py From Binance-bot with GNU General Public License v3.0 | 5 votes |
def get_order_stat_remaining(self, pair, Order_id): error_count = 0 info_returned = False status = 'not_found' remaining = -1 executed = -1 fail = False if Order_id == 0: self.lg.log("Tried to check an unplaced order") fail = True while info_returned == False and not fail: try: stat_get = client.queryOrder(pair, orderId=Order_id) except MalformedRequest as e: self.lg.log(str(e) + ' ' + str(e.__traceback__) + ' Order ID not found on status + remain check, keep trying') error_count += 1 time.sleep(5) client.set_offset() except ( InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str(e.__traceback__)) error_count += 1 time.sleep(1) else: status = stat_get['status'] remaining = float(stat_get['origQty']) - float(stat_get['executedQty']) executed = float(stat_get['executedQty']) info_returned = True finally: if error_count >= 5: self.lg.log("Tried to get status/remaining 5 times and failed") fail = True # self.lg.log('Returning: status = ' + status + ' remaining = ' + str(remaining)) return {"status": status, "remaining": remaining, "executed": executed, "fail_flag": fail}
Example #29
Source File: mult_arbit.py From Binance-bot with GNU General Public License v3.0 | 5 votes |
def ord_cancel(self, pair, Order_id): ord_cancelled = False error_count = 0 self.lg.log('Cancelling order ' + str(Order_id)) while not ord_cancelled and error_count < 10: try: client.deleteOrder(pair, orderId=Order_id) except MalformedRequest as e: self.lg.log(str(e) + ' ' + str( e.__traceback__) + ' ' + 'Order ID not found on cancel, try cancelling all open orders for the pair') client.set_offset() cur_open = self.get_open_ords(pair) if cur_open == []: self.lg.log('Could not find the order, but no order open for the pair so must be cancelled') ord_cancelled = True else: for o in cur_open: try: client.deleteOrder(pair, orderId=o['orderId']) except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str( e.__traceback__) + ' ' + 'Trying to cancel open orders after single cancel fails, wtf') client.set_offset() ord_cancelled = True error_count += 1 time.sleep(1) except ( InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: self.lg.log(str(e) + ' ' + str( e.__traceback__) + 'Internal or Unknown error while cancelling order, keep trying') error_count += 1 time.sleep(1) else: ord_cancelled = True finally: if error_count >= 10: self.lg.log('Order cancel failed 10 times, Order ID was: ' + str(Order_id))
Example #30
Source File: manager.py From brutemap with GNU General Public License v3.0 | 5 votes |
def errormanager(func): """ Menangkap spesifikasi pengecualian """ globals()["RETRY_COUNT"] = 0 @functools.wraps(func) def decorated(*args, **kwargs): global RETRY_COUNT try: return func(*args, **kwargs) except ProtocolError as e: # XXX: abaikan ? pass except Exception as e: if issubclass(e.__class__, BrutemapException): raise time.sleep(SETTING.DELAY) logger.error("Error occurred: %s" % str(e)) if RETRY_COUNT != SETTING.MAX_RETRY: RETRY_COUNT += 1 return decorated(*args, **kwargs) raise return decorated