Losing connection to the binance api server

Hello,

I have a bot using the API python-binance to place orders in the market in several accounts at the same time.

All the information about the market is being acquired via websocket, so I am sure this is not the problem as it is using another stream of communication for asking the market info then for placing the orders.

After several hours working, the bot gets errors like “Connection reset by peer”, or the one I am attaching here. The object of the connection is rejected by Binance, even with a very very low activity (it places orders every 1-2 hours and no more than 2.) I am pretty sure that is not a code problem as it works without any problem for 6-8 hours but then Binance decides to disconnect it.

My questions:

  • Why is this happening to my bot?
  • What are the desconnection rules of the Binance API for checking if I am missing something

  • A single connection to stream.binance.com is only valid for 24 hours; expect to be disconnected at the 24 hour mark
  • The websocket server will send a ping frame every 3 minutes. If the websocket server does not receive a pong frame back from the connection within a 10 minute period, the connection will be disconnected. Unsolicited pong frames are allowed.

Take note of this 2 rule stated in the documentation (Binance API Documentation)

Ensure that your code is ready handle any disconnection pass the 24 hour mark and also that your websocket library will reply a ping frame automatically.

Hello, thanks for your answer.

Both things are covered in the code, and anyway we keep getting disconnected.

As you can see, the error is not with the stream, is with the rest API connection to place orders. We follow every step in the documentation and anyway keep getting disconnected. Please can you try to help us with other solutions?

Do this errors tell you something? “HTTPSConnectionPool(host=‘api.binance.com’, port=443): Read timed out. (read timeout=10)” It is from the rest API, and we are not getting data from there, so it is not caused by stressing the network. As you can see, there is no HTTP error so we are not getting disconected because of the limits

Are you allowed to connect to Binance from your location?

1 Like

Yes of course I am allowed, this happens usually after some hours working properly @Chai

will please someone answer?

You should try, try+except and recreate your client to connect again with your api and security key in exception and have to pass or continue the program. I hope it will work.

You should include in your program some code that catches the disconnect event to reopen the connection, you know something like websocket.onclose()

fijate, si poniendo una vpn, para tener otra ip. o en su defecto, por ahi reniciando el router y tener otra ip, si te continua pasando.
a mi me pasaba lo mismo y puse vpn de otro pais, y no me esta dando error.
el error me pasa con ip de alemania, pero con ip de vpn de paris, no me pasa.
vamos a ver si continua asi. espeor sirva la info.

The error message “HTTPSConnectionPool(host=‘api.binance.com 1’, port=443): Read timed out. (read timeout=10)” indicates that the request to the Binance API is timing out. This happens when the server takes too long to respond, exceeding the specified timeout period (10 seconds in this case).

Potential Causes:

  1. Server-side delays: The Binance API server may be experiencing high traffic or delays, causing it to respond slowly.
  2. Network issues: Although you mentioned the network isn’t stressed, there might still be intermittent network issues between your server and the Binance API server.
  3. Incorrect URL: The hostname 'api.binance.com 1' appears incorrect due to the space and number. The correct hostname should be 'api.binance.com'.

Solutions you can try:

Increase the Timeout: You can increase the read timeout value to give the server more time to respond.

import requests

response = requests.get(‘https://api.binance.com/api/v3/ticker/price’, timeout=20)

Retry Mechanism: Implement a retry mechanism to handle intermittent network issues or server delays.

import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

retry_strategy = Retry(
total=3, # Total number of retries
backoff_factor=1, # Time to wait between retries
status_forcelist=[429, 500, 502, 503, 504], # Retry on these status codes
method_whitelist=[“HEAD”, “GET”, “OPTIONS”]
)

adapter = HTTPAdapter(max_retries=retry_strategy)
http = requests.Session()
http.mount(“https://”, adapter)
http.mount(“http://”, adapter)

try:
response = http.get(‘https://api.binance.com/api/v3/ticker/price’, timeout=10)
response.raise_for_status()
data = response.json()
print(data)
except requests.exceptions.RequestException as e:
print(f"Error: {e}")

Check URL: Ensure the URL and hostname are correct. The correct URL should not have any spaces or additional characters.

response = requests.get(‘https://api.binance.com/api/v3/ticker/price’, timeout=10)

Corrected URL and Retry Mechanism

import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
method_whitelist=[“HEAD”, “GET”, “OPTIONS”]
)

adapter = HTTPAdapter(max_retries=retry_strategy)
http = requests.Session()
http.mount(“https://”, adapter)
http.mount(“http://”, adapter)

try:
response = http.get(‘https://api.binance.com/api/v3/ticker/price’, timeout=10)
response.raise_for_status()
data = response.json()
print(data)
except requests.exceptions.RequestException as e:
print(f"Error: {e}")