-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_websocket.py
More file actions
290 lines (230 loc) Β· 9.08 KB
/
run_websocket.py
File metadata and controls
290 lines (230 loc) Β· 9.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import signal
import telebot
from datetime import datetime
import pytz
import asyncio
import queue
import threading
from websocket_manager import WebsocketManager
from utils import *
from config import (TIMEZONE, TELEGRAM_BOT_TOKEN, TEST_TG_CHAT_ID_2,
MAX_RETRIES, ADDRESSES_TO_TRACK, SUBSCRIPTION_TYPE)
bot = telebot.TeleBot(TELEGRAM_BOT_TOKEN, threaded=False)
is_first_message = True
send_to_tg = True
message_queue = queue.Queue()
mirrored_queue = queue.Queue()
try:
timezone = pytz.timezone(TIMEZONE)
except:
timezone = pytz.timezone('Asia/Singapore')
def worker():
while True:
msg_list = message_queue.get()
if msg_list is None:
break
try:
send_to_telegram(msg_list, bot, TEST_TG_CHAT_ID_2, MAX_RETRIES, 1,
5)
except Exception as e:
print(f"Error sending message to Telegram: {e}")
finally:
message_queue.task_done()
print("Current queue before get: ", list(mirrored_queue.queue))
_ = mirrored_queue.get()
worker_thread = threading.Thread(target=worker, daemon=True)
worker_thread.start()
def get_direction_icon(direction):
if direction.lower() in ["open long", "long"]:
return "π’"
elif direction.lower() in ["open short", 'short']:
return "π΄"
elif direction.lower() in ["close long", "close short"]:
return "π΅"
else:
return "βͺ"
def on_user_fills_message(ws_msg):
global is_first_message
if not isinstance(ws_msg, dict):
print("Unexpected message format:", type(ws_msg))
return
try:
fills = ws_msg.get("data", {}).get("fills", [])
if not fills:
print("No fills found in the message.")
return
if is_first_message:
is_first_message = False
print("Skipping alert for historical data.")
return
msg_list = []
header = f"π¨ **Trade Filled Alert** π¨\n\n"
coin_dir_cache = {}
print("Received user fills:")
for fill in fills:
coin = fill.get("coin")
px = float(fill.get("px", 0))
sz = float(fill.get("sz", 0))
sz_usd = px * sz
timestamp = fill.get("time")
direction = fill.get("dir")
hash = fill.get("hash")
if coin not in coin_dir_cache:
coin_dir_cache[coin] = direction
else:
if coin_dir_cache[coin] == direction:
continue
else:
coin_dir_cache[coin] = direction
dt_utc = datetime.utcfromtimestamp(timestamp / 1000)
dt_sg = pytz.utc.localize(dt_utc).astimezone(timezone)
dt_str = dt_sg.strftime('%Y-%m-%d %H:%M:%S')
msg = (
f"π *Tracked Address*: {ADDRESSES_TO_TRACK[0]}\n"
f"#οΈβ£ *Hash*: {hash}\n"
f"β° **Time**: {dt_str}\n"
f"π° **Coin**: {coin}\n"
f"π **Price**: ${px:,.2f}\n"
f"π΅ **Size (in USD)**: ${sz_usd:,.2f}\n"
f"{get_direction_icon(direction)} **Direction**: {direction}\n\n"
)
print(msg)
msg_list.append(msg)
if send_to_tg and msg_list:
msg_list.insert(0, header)
# send_to_telegram(msg_list, bot, TEST_TG_CHAT_ID_2, MAX_RETRIES, 1,
# 5)
message_queue.put(msg_list)
mirrored_queue.put(msg_list)
except Exception as e:
print(f"Error processing userFills message: {e}")
if send_to_tg:
error_message = f"β **An error occurred while processing the userFills message** β\n\n"
error_message += f"**Error Message**: {e}\n"
error_message += f"Please investigate the issue."
msg_list = [error_message]
# send_to_telegram(msg_list, bot, TEST_TG_CHAT_ID_2, MAX_RETRIES, 1,
# 5)
message_queue.put(msg_list)
mirrored_queue.put(msg_list)
def on_order_updates_message(ws_msg):
if not isinstance(ws_msg, dict):
print("Unexpected message format:", type(ws_msg))
return
try:
orders = ws_msg.get("data", [])
if not orders:
print("No order found in the message.")
return
msg_list = []
msg = f"π¨ **Order Updates Alert** π¨\n\n"
msg_list.append(msg)
print("Received user fills:")
for order in orders:
basic_order = order.get("order", {})
status = order.get("status", '')
coin = basic_order.get("coin", '')
side = basic_order.get("side", '')
limit_px = float(basic_order.get("limitPx", 0))
sz = float(basic_order.get("sz", 0))
timestamp = basic_order.get("timestamp", 0)
origSz = float(basic_order.get("origSz", 0))
if side.upper() == 'A':
direction = 'Short'
elif side.upper() == 'B':
direction = 'Long'
else:
direction = 'Unknown'
sz_usd = limit_px * sz
orig_sz_usd = limit_px * origSz
dt_utc = datetime.utcfromtimestamp(timestamp / 1000)
dt_sg = pytz.utc.localize(dt_utc).astimezone(timezone)
dt_str = dt_sg.strftime('%Y-%m-%d %H:%M:%S')
msg = (
f"π *Tracked Address*: {ADDRESSES_TO_TRACK[0]}\n"
f"β° **Time**: {dt_str}\n"
f"π° **Coin**: {coin}\n"
f"π **Limit Price**: ${limit_px:,.2f}\n"
f"π΅ **Size (in USD)**: ${sz_usd:,.2f}\n"
f"π΅ **Original Size (in USD)**: ${orig_sz_usd:,.2f}\n"
f"{get_direction_icon(direction)} **Direction**: {direction}\n"
f"π **Order Status**: {status.capitalize()}\n\n")
print(msg)
msg_list.append(msg)
if send_to_tg:
# send_to_telegram(msg_list, bot, TEST_TG_CHAT_ID_2, MAX_RETRIES, 1,
# 5)
message_queue.put(msg_list)
mirrored_queue.put(msg_list)
except Exception as e:
print(f"Error processing orderUpdates message: {e}")
if send_to_tg:
error_message = f"β **An error occurred while processing the orderUpdates message** β\n\n"
error_message += f"**Error Message**: {e}\n"
error_message += f"Please investigate the issue."
msg_list = [error_message]
# send_to_telegram(msg_list, bot, TEST_TG_CHAT_ID_2, MAX_RETRIES, 1,
# 5)
message_queue.put(msg_list)
mirrored_queue.put(msg_list)
def on_ws_close(ws):
print("WebSocket closed. Reconnecting...")
if send_to_tg:
error_message = f"β **WebSocket Closed** β\n\n"
error_message += f"Attempting to reconnect..."
msg_list = [error_message]
# send_to_telegram(msg_list, bot, TEST_TG_CHAT_ID_2, MAX_RETRIES, 1, 5)
message_queue.put(msg_list)
mirrored_queue.put(msg_list)
reconnect()
def on_ws_error(ws, error):
print(f"WebSocket error: {error}. Reconnecting...")
if send_to_tg:
error_message = f"β **WebSocket Error** β\n\n"
error_message += f"**Error**: {error}\n"
error_message += f"Attempting to reconnect..."
msg_list = [error_message]
# send_to_telegram(msg_list, bot, TEST_TG_CHAT_ID_2, MAX_RETRIES, 1, 5)
message_queue.put(msg_list)
mirrored_queue.put(msg_list)
reconnect()
def create_ws_manager_and_subscribe():
global ws_manager
ws_manager = WebsocketManager("http://api.hyperliquid.xyz")
ws_manager.on_close = on_ws_close
ws_manager.on_error = on_ws_error
ws_manager.start()
if SUBSCRIPTION_TYPE == "userFills":
subscription = {
"type": "userFills",
"user": ADDRESSES_TO_TRACK[0],
}
ws_manager.subscribe(subscription, on_user_fills_message)
else:
subscription = {"type": "orderUpdates", "user": ADDRESSES_TO_TRACK[0]}
ws_manager.subscribe(subscription, on_order_updates_message)
if send_to_tg:
init_message = f"π **WebSocket Started** π\n\n"
init_message += f"**Subscription Type**: {SUBSCRIPTION_TYPE}\n"
init_message += f"**Tracked User Address**: {ADDRESSES_TO_TRACK[0]}"
msg_list = [init_message]
# send_to_telegram(msg_list, bot, TEST_TG_CHAT_ID_2, MAX_RETRIES, 1, 5)
message_queue.put(msg_list)
mirrored_queue.put(msg_list)
def reconnect():
global ws_manager
print("Attempting to reconnect...")
if ws_manager:
ws_manager.stop()
create_ws_manager_and_subscribe()
def signal_handler(sig, frame):
print("Stopping WebSocketManager...")
if ws_manager:
ws_manager.stop()
print("WebSocketManager stopped. Exiting.")
exit(0)
signal.signal(signal.SIGINT, signal_handler)
if __name__ == "__main__":
create_ws_manager_and_subscribe()
while True:
time.sleep(1)