You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
My code is:
sometimes it reads my position information, sometimes not and my output is:
The text was updated successfully, but these errors were encountered: