Skip to content

Instantly share code, notes, and snippets.

@behnamonline
Created September 14, 2025 17:45
Show Gist options
  • Select an option

  • Save behnamonline/f4bc39232c856b1869e12910bb9f1d5f to your computer and use it in GitHub Desktop.

Select an option

Save behnamonline/f4bc39232c856b1869e12910bb9f1d5f to your computer and use it in GitHub Desktop.
Bitcoin price Binance WebSocket
# https://www.youtube.com/@behnamonline
import websocket
import json
import os
coin = "btc"
pair = "usdt"
symbol = f"{coin}{pair}".lower()
last_price = None
def on_message(ws, message):
global last_price
data = json.loads(message)
price = float(data['p'])
# پاک کردن ترمینال برای تمیز بودن
os.system('cls' if os.name == 'nt' else 'clear')
if last_price is not None:
if price > last_price:
color = "\033[92m" # سبز
trend = "⬆️"
elif price < last_price:
color = "\033[91m" # قرمز
trend = "⬇️"
else:
color = "\033[93m" # زرد
trend = "➖"
else:
color = "\033[0m"
trend = ""
print(f"{coin.upper()}/{pair.upper()} Price: {color}$ {price:.2f} {trend}\033[0m")
last_price = price
def on_open(ws):
print("📡 Connected to Binance WebSocket")
def on_close(ws, close_status_code, close_msg):
print("❌ Disconnected from Binance WebSocket")
def on_error(ws, error):
print("⚠️ WebSocket Error:", error)
if __name__ == "__main__":
url = f"wss://stream.binance.com:9443/ws/{symbol}@trade"
ws = websocket.WebSocketApp(
url,
on_open=on_open,
on_message=on_message,
on_close=on_close,
on_error=on_error
)
ws.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment