Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error Remote end closed connection without response #149

Open
tom634 opened this issue Nov 4, 2023 · 0 comments
Open

Error Remote end closed connection without response #149

tom634 opened this issue Nov 4, 2023 · 0 comments

Comments

@tom634
Copy link

tom634 commented Nov 4, 2023

My code is:


import json
from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient
from binance.um_futures import UMFutures
import config
import threading
import time
import websocket
import pandas as pd

SOCKET = "wss://fstream.binance.com/ws/btcusdt@kline_1m"
TIMEOUT = 120
RECONNECT_DELAY = 5  # Initial delay for reconnection attempts
MAX_RECONNECT_DELAY = 60  # Maximum delay for reconnection attempts
futures_client = UMFutures(key=config.API_KEY, secret=config.API_SECRET)
connection_lock = threading.Lock()
last_received_time = time.time()

def check_connection():
    global ws_client, last_received_time
    reconnect_delay = RECONNECT_DELAY
    while True:
        time.sleep(TIMEOUT)
        with connection_lock:
            if time.time() - last_received_time > TIMEOUT:
                print(f"No message received for {TIMEOUT} seconds. Reconnecting...")
                try:
                    # Gracefully close the existing connection if possible
                    if ws_client:
                        ws_client.stop()
                except Exception as e:
                    print(f"Error when stopping ws_client: {e}")
                finally:
                    ws_client = None  # Clear the reference to the old ws_client

                # Attempt to reconnect with an exponential backoff
                while ws_client is None:
                    try:
                        ws_client = UMFuturesWebsocketClient(SOCKET, on_message=on_message)
                        print("Reconnected to the WebSocket.")
                        reconnect_delay = RECONNECT_DELAY  # Reset reconnect delay after a successful connection
                    except Exception as e:
                        print(f"Error when reconnecting: {e}")
                        print(f"Will try to reconnect in {reconnect_delay} seconds.")
                        time.sleep(reconnect_delay)
                        reconnect_delay = min(reconnect_delay * 2, MAX_RECONNECT_DELAY)  # Exponential backoff

def on_message(ws_client, message):
    global last_received_time
    last_received_time = time.time()  # Update the time of the last received message

    json_message = json.loads(message)
    candle = json_message['k']
    if candle['x']:
        # Ensure that we have the lock before accessing the shared futures_client
        with connection_lock:
            response = futures_client.get_position_risk(recvWindow=6000)
            btcusdt_data = next((item for item in response if item['symbol'] == 'BTCUSDT'), None)
            print(pd.to_datetime(candle['t'], unit='ms').strftime('%H:%M:%S'), btcusdt_data)

# Initialize the WebSocket client
with connection_lock:
    ws_client = UMFuturesWebsocketClient(SOCKET, on_message=on_message)

# Start the connection monitor thread
connection_thread = threading.Thread(target=check_connection)
connection_thread.start()

# The main thread can continue doing other tasks, or enter an idle state.
# You can add your main thread logic here.

sometimes it reads my position information, sometimes not and my output is:

21:49:00 {'symbol': 'BTCUSDT', 'positionAmt': '0.000', 'entryPrice': '0.0', 'breakEvenPrice': '0.0', 'markPrice': '34800.92137916', 'unRealizedProfit': '0.00000000', 'liquidationPrice': '0', 'leverage': '1', 'maxNotionalValue': '5.0E8', 'marginType': 'cross', 'isolatedMargin': '0.00000000', 'isAutoAddMargin': 'false', 'positionSide': 'BOTH', 'notional': '0', 'isolatedWallet': '0', 'updateTime': 1698891058519, 'isolated': False, 'adlQuantile': 0}
**ERROR:binance.websocket.websocket_client:Error from callback <function on_message at 0x0000021A0685F920>: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))**
21:51:00 {'symbol': 'BTCUSDT', 'positionAmt': '0.000', 'entryPrice': '0.0', 'breakEvenPrice': '0.0', 'markPrice': '34800.00000000', 'unRealizedProfit': '0.00000000', 'liquidationPrice': '0', 'leverage': '1', 'maxNotionalValue': '5.0E8', 'marginType': 'cross', 'isolatedMargin': '0.00000000', 'isAutoAddMargin': 'false', 'positionSide': 'BOTH', 'notional': '0', 'isolatedWallet': '0', 'updateTime': 1698891058519, 'isolated': False, 'adlQuantile': 0}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant