Search code examples
pythoncoinbase-api

Is my code crashing because of internet connection issue? if so is there a way i can make a snippet of code to check connection before trying api?


Im using Jupyter Notebook to run a fairly basic crypto trading bot with an API on coinbase and after an arbitrary amount of time, sometimes 6 hours other times 18 hours, the code will error and stop working.. can has anyone had this problem or are able to determine the problem from the error script produced. error code given below..

    OSError                                   Traceback (most recent call last)
~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    596             # Make the request on the httplib connection object.
--> 597             httplib_response = self._make_request(conn, method, url,
    598                                                   timeout=timeout_obj,

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    385                     # otherwise it looks like a programming error was the cause.
--> 386                     six.raise_from(e, None)
    387         except (SocketTimeout, BaseSSLError, SocketError) as e:

~\anaconda3\lib\site-packages\requests\packages\urllib3\packages\six.py in raise_from(value, from_value)

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    381                 try:
--> 382                     httplib_response = conn.getresponse()
    383                 except Exception as e:

~\anaconda3\lib\http\client.py in getresponse(self)
   1370             try:
-> 1371                 response.begin()
   1372             except ConnectionError:

~\anaconda3\lib\http\client.py in begin(self)
    318         while True:
--> 319             version, status, reason = self._read_status()
    320             if status != CONTINUE:

~\anaconda3\lib\http\client.py in _read_status(self)
    279     def _read_status(self):
--> 280         line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
    281         if len(line) > _MAXLINE:

~\anaconda3\lib\socket.py in readinto(self, b)
    703             try:
--> 704                 return self._sock.recv_into(b)
    705             except timeout:

~\anaconda3\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py in recv_into(self, *args, **kwargs)
    292             else:
--> 293                 return self.recv_into(*args, **kwargs)
    294 

~\anaconda3\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py in recv_into(self, *args, **kwargs)
    281             else:
--> 282                 raise SocketError(str(e))
    283         except OpenSSL.SSL.ZeroReturnError as e:

OSError: (10054, 'WSAECONNRESET')

During handling of the above exception, another exception occurred:

ProtocolError                             Traceback (most recent call last)
~\anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    412             if not chunked:
--> 413                 resp = conn.urlopen(
    414                     method=request.method,

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    647 
--> 648             retries = retries.increment(method, url, error=e, _pool=self,
    649                                         _stacktrace=sys.exc_info()[2])

~\anaconda3\lib\site-packages\requests\packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
    346             if read is False or not self._is_method_retryable(method):
--> 347                 raise six.reraise(type(error), error, _stacktrace)
    348             elif read is not None:

~\anaconda3\lib\site-packages\requests\packages\urllib3\packages\six.py in reraise(tp, value, tb)
    684         if value.__traceback__ is not tb:
--> 685             raise value.with_traceback(tb)
    686         raise value

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    596             # Make the request on the httplib connection object.
--> 597             httplib_response = self._make_request(conn, method, url,
    598                                                   timeout=timeout_obj,

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    385                     # otherwise it looks like a programming error was the cause.
--> 386                     six.raise_from(e, None)
    387         except (SocketTimeout, BaseSSLError, SocketError) as e:

~\anaconda3\lib\site-packages\requests\packages\urllib3\packages\six.py in raise_from(value, from_value)

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    381                 try:
--> 382                     httplib_response = conn.getresponse()
    383                 except Exception as e:

~\anaconda3\lib\http\client.py in getresponse(self)
   1370             try:
-> 1371                 response.begin()
   1372             except ConnectionError:

~\anaconda3\lib\http\client.py in begin(self)
    318         while True:
--> 319             version, status, reason = self._read_status()
    320             if status != CONTINUE:

~\anaconda3\lib\http\client.py in _read_status(self)
    279     def _read_status(self):
--> 280         line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
    281         if len(line) > _MAXLINE:

~\anaconda3\lib\socket.py in readinto(self, b)
    703             try:
--> 704                 return self._sock.recv_into(b)
    705             except timeout:

~\anaconda3\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py in recv_into(self, *args, **kwargs)
    292             else:
--> 293                 return self.recv_into(*args, **kwargs)
    294 

~\anaconda3\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py in recv_into(self, *args, **kwargs)
    281             else:
--> 282                 raise SocketError(str(e))
    283         except OpenSSL.SSL.ZeroReturnError as e:

ProtocolError: ('Connection aborted.', OSError("(10054, 'WSAECONNRESET')"))

During handling of the above exception, another exception occurred:

ConnectionError                           Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_26992/2760925491.py in <module>
     36 # dead zone
     37     if (price_diff < buy_diff) and (price_diff > sell_diff) and (wait_time<run_time):
---> 38         price_difference()
     39         wait_time = (run_time+180)
     40         run_log.logger.info("price difference in dead zone")

~\AppData\Local\Temp/ipykernel_26992/3172399590.py in price_difference()
     46     global difference
     47     global lastDiff
---> 48     price()
     49     historic_price()
     50     if current_price < hist_avg:

~\AppData\Local\Temp/ipykernel_26992/3172399590.py in price()
     23     global current_ask
     24     global last_price
---> 25     var=auth_client.get_product_order_book(trade_pair)
     26     bids=var.get('bids')
     27     asks=var.get('asks')

~\anaconda3\lib\site-packages\cbpro\public_client.py in get_product_order_book(self, product_id, level)
     86         """
     87         params = {'level': level}
---> 88         return self._send_message('get',
     89                                   '/products/{}/book'.format(product_id),
     90                                   params=params)

~\anaconda3\lib\site-packages\cbpro\public_client.py in _send_message(self, method, endpoint, params, data)
    266         """
    267         url = self.url + endpoint
--> 268         r = self.session.request(method, url, params=params, data=data,
    269                                  auth=self.auth, timeout=30)
    270         return r.json()

~\anaconda3\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    486         }
    487         send_kwargs.update(settings)
--> 488         resp = self.send(prep, **send_kwargs)
    489 
    490         return resp

~\anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
    607 
    608         # Send the request
--> 609         r = adapter.send(request, **kwargs)
    610 
    611         # Total elapsed time of the request (approximately)

~\anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    471 
    472         except (ProtocolError, socket.error) as err:
--> 473             raise ConnectionError(err, request=request)
    474 
    475         except MaxRetryError as e:

ConnectionError: ('Connection aborted.', OSError("(10054, 'WSAECONNRESET')"))

Solution

  • so it might not be the perfect solution but it's going to work for me in this case, have a script simply restart the main script if/when it crashes.

    from subprocess import run
    from time import sleep
    
    # Path and name to the script you are trying to start
    file_path = "CBPRO_BTC_USDC_V3.py" 
    print('program started')
    restart_timer = 60
    def start_script():
        try:
            # Make sure 'python' command is available
            run("python "+file_path, check=True) 
        except:
            # Script crashed, lets restart it!
            handle_crash()
    
    def handle_crash():
        print('Restarting in 60 seconds')
        sleep(restart_timer)  # Restarts the script after 60 seconds
        start_script()
    
    start_script()