Skip to content

Instantly share code, notes, and snippets.

@veer66
Last active November 17, 2021 03:35
Show Gist options
  • Save veer66/4c5a837a1f13f48992be3e9f50ac8bd3 to your computer and use it in GitHub Desktop.
Save veer66/4c5a837a1f13f48992be3e9f50ac8bd3 to your computer and use it in GitHub Desktop.
import time
from pygame import mixer
from pygame.mixer import music
import socket
import ssl
import uuid
import json
MIN_XTZ = 4.7
def ws_upgrade(s, conn_info):
with s.makefile(mode = 'rw', encoding = "ISO-8859-1") as f:
f.write(f'GET {conn_info["path"]} HTTP/1.1\r\n')
f.write(f'Host: {conn_info["host"]}\r\n')
f.write("Connection: Upgrade\r\n")
f.write("Upgrade: websocket\r\n")
f.write(f'Sec-Websocket-Key: {str(uuid.uuid1())}\r\n')
f.write("Sec-WebSocket-Version: 13\r\n")
f.write("\r\n")
f.flush()
# reading response
for line in f:
if line == "\n":
break
def ws_read_extra_len(s, num_of_bytes):
buf = s.recv(num_of_bytes)
len = 0
for i in range(num_of_bytes):
len += buf[i] << (8 * (num_of_bytes - i - 1))
return len
def ws_read_payload_len(s):
match s.recv(1)[0] & 0x7F:
case 127:
return ws_read_extra_len(s, 4)
case 126:
return ws_read_extra_len(s, 2)
case l:
return l
def ws_read_frame(s):
buf = s.recv(1)
header0 = buf[0]
opcode = header0 & 0x0F
match opcode:
case 0x1:
payload_len = ws_read_payload_len(s)
return s.recv(payload_len)
case 0x9:
payload_len = ws_read_payload_len(s)
ping_payload = s.recv(payload_len)
pong_msg = bytes([0x8A, 0x81, payload_len]) + ping_payload
case 0xA:
payload_len = ws_read_payload_len(s)
s.recv(payload_len)
return None
def ws_connect(conn_info):
ctx = ssl.create_default_context()
with socket.create_connection((conn_info["host"], conn_info["port"])) as s:
with ctx.wrap_socket(s, server_hostname = conn_info["host"]) as ss:
ws_upgrade(ss, conn_info)
while True:
yield ws_read_frame(ss)
mixer.init()
music.load('inter.ogg')
while True:
for res in ws_connect({"host": "stream.binance.com",
"port": 9443,
"path": "/ws/xtzusdt@kline_1m"}):
if res is not None:
v = json.loads(res)
m = (float(v["k"]["o"]) + float(v["k"]["c"])) / 2.0
if m < MIN_XTZ:
print(f'm = {m}')
music.play()
time.sleep(360)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment