'Why does Python requests keep giving me this error? "An existing connection was forcibly closed by the remote host"

I am attempting to send a request to Binance api (crypto exchange) for the latest price of a specific symbol of crypto every ten seconds. However after between 5 to 20 hours it stops working throwing this error:

Traceback (most recent call last): File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen httplib_response = self._make_request( File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 386, in _make_request self._validate_conn(conn) File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 1040, in validate_conn conn.connect() File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connection.py", line 416, in connect self.sock = ssl_wrap_socket( File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\ssl.py", line 449, in ssl_wrap_socket ssl_sock = ssl_wrap_socket_impl( File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\ssl.py", line 493, in _ssl_wrap_socket_impl return ssl_context.wrap_socket(sock, server_hostname=server_hostname) File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 512, in wrap_socket return self.sslsocket_class._create( File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1070, in _create self.do_handshake() File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1341, in do_handshake self._sslobj.do_handshake() ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py", line 440, in send resp = conn.urlopen( File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 785, in urlopen retries = retries.increment( File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\retry.py", line 550, in increment raise six.reraise(type(error), error, _stacktrace) File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\packages\six.py", line 769, in reraise raise value.with_traceback(tb) File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen httplib_response = self._make_request( File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 386, in _make_request self._validate_conn(conn) File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 1040, in validate_conn conn.connect() File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connection.py", line 416, in connect self.sock = ssl_wrap_socket( File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\ssl.py", line 449, in ssl_wrap_socket ssl_sock = ssl_wrap_socket_impl( File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\ssl.py", line 493, in _ssl_wrap_socket_impl return ssl_context.wrap_socket(sock, server_hostname=server_hostname) File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 512, in wrap_socket return self.sslsocket_class._create( File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1070, in _create self.do_handshake() File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1341, in do_handshake self._sslobj.do_handshake() urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "c:\Users\nrspa\Desktop\CryptoBot v2.6 (24h)\main (market).py", line 113, in CB.main() File "c:\Users\nrspa\Desktop\CryptoBot v2.6 (24h)\main (market).py", line 68, in main self.array = self.create_array() File "c:\Users\nrspa\Desktop\CryptoBot v2.6 (24h)\main (market).py", line 46, in create_array self.array.append(self.get_price()) File "c:\Users\nrspa\Desktop\CryptoBot v2.6 (24h)\main (market).py", line 22, in get_price response = requests.get(url, headers = {"User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}) File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\api.py", line 75, in get return request('get', url, params=params, **kwargs) File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\api.py", line 61, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 529, in request resp = self.send(prep, **send_kwargs) File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 645, in send r = adapter.send(request, **kwargs) File "C:\Users\nrspa\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py", line 501, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

Also note that this is my code (it is part of a class) it gets the price from Binance every 10 seconds until the desired array length is reached, at which point it processes the data:

import json
import requests
import time

def get_price(self):
    url = f"https://api.binance.com/api/v3/ticker/price?symbol={self.symbol}" 
    response = requests.get(url, headers = {"User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"})
    json_response = json.loads(response.text)
    return float(json_response['price'])

def create_array(self):
    i = len(self.array)
    if i < self.array_len:
        while i < self.array_len:
            time.sleep(self.time_interval)
            self.array.append(self.get_price())
            i = i + 1
        return self.array
    else:
        main()


Solution 1:[1]

The issue can be caused by a "disagreement" between both sides. It can be that the connection timed out or the server closed it.

The fix is to catch this exception and open the connection again.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ali Zahid Raja