Skip to content

Instantly share code, notes, and snippets.

@aKamrani
Last active October 31, 2024 08:32
Show Gist options
  • Select an option

  • Save aKamrani/6811687cfa4caf091c5bdef761dcecdf to your computer and use it in GitHub Desktop.

Select an option

Save aKamrani/6811687cfa4caf091c5bdef761dcecdf to your computer and use it in GitHub Desktop.
Binance Socket Monitoring | /etc/systemd/system/binance-monitor.service | /opt/binance-monitor/binance-monitor.py
import websocket
import time
import threading
import datetime
BINANCE_URL = "wss://stream.binance.com:9443/stream"
is_connected = False
def on_open(ws):
global is_connected
is_connected = True
print("WebSocket connection opened")
def on_message(ws, message):
pass # No need to handle messages for connection monitoring
def on_error(ws, error):
global is_connected
is_connected = False
print(f"WebSocket error: {error}")
def on_close(ws, close_status_code, close_msg):
global is_connected
is_connected = False
print("WebSocket connection closed")
def run_websocket():
while True:
try:
ws = websocket.WebSocketApp(
BINANCE_URL,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close
)
ws.run_forever()
except Exception as e:
print(f"Exception occurred: {e}")
print("Reconnecting in 1 minute...")
time.sleep(60) # Wait for 1 minute before reconnecting
def log_connection_status():
while True:
time.sleep(60) # Wait for 1 minute
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
status = "UP" if is_connected else "DOWN"
with open("connection_status.log", "a") as log_file:
log_file.write(f"{current_time} - Connection status: {status}\n")
if __name__ == "__main__":
websocket_thread = threading.Thread(target=run_websocket)
websocket_thread.start()
log_connection_status()
[Unit]
Description=Binance Stream Monitor
After=network.target
[Service]
User=root
WorkingDirectory=/opt/binance-monitor
ExecStart=/usr/bin/python3 /opt/binance-monitor/binance-monitor.py
Restart=on-failure
RestartSec=60
[Install]
WantedBy=multi-user.target
sudo apt install python3-websocket
sudo systemctl daemon-reload
sudo systemctl start binance-monitor.service
sudo systemctl enable binance-monitor.service
sudo systemctl status binance-monitor.service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment