-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtelegram_client.py
More file actions
275 lines (222 loc) · 9.64 KB
/
telegram_client.py
File metadata and controls
275 lines (222 loc) · 9.64 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
import logging
import requests
import html
from typing import Optional
logger = logging.getLogger(__name__)
class TelegramClient:
"""Send alerts to Telegram with topic support"""
def __init__(self, bot_token: str, chat_id, topic_id: Optional[int] = None):
"""
Initialize Telegram client
Args:
bot_token: Telegram bot token from BotFather
chat_id: Target chat ID for alerts
topic_id: Optional Telegram topic ID (for supergroups with topics enabled)
"""
self.bot_token = bot_token
self.chat_id = int(chat_id) if isinstance(chat_id, str) else chat_id
self.topic_id = topic_id
self.api_url = f"https://api.telegram.org/bot{bot_token}"
if not bot_token or not chat_id:
logger.error("Telegram credentials missing. Check .env file.")
raise ValueError("TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID required in .env")
if self.topic_id:
logger.info(f"✅ Telegram topic configured: Topic ID {self.topic_id}")
async def send_message(self, text: str, topic_id: Optional[int] = None, chat_id: Optional[int] = None) -> bool:
"""
Send a message to Telegram chat/topic
Args:
text: Message text (supports HTML formatting)
topic_id: Optional topic ID (overrides self.topic_id if provided)
chat_id: Optional chat ID (overrides self.chat_id if provided, for DM replies)
Returns:
True if sent successfully, False otherwise
"""
try:
payload = {
"chat_id": chat_id or self.chat_id,
"text": text,
"parse_mode": "HTML"
}
# Use provided topic_id, fall back to self.topic_id
effective_topic_id = topic_id or self.topic_id
if effective_topic_id:
payload["message_thread_id"] = effective_topic_id
response = requests.post(
f"{self.api_url}/sendMessage",
json=payload,
timeout=10
)
if response.status_code == 200:
result = response.json()
if result.get("ok"):
logger.debug(f"Message sent successfully")
return True
else:
logger.error(f"Telegram API error: {result.get('description')}")
return False
else:
logger.error(f"HTTP error {response.status_code}: {response.text}")
return False
except requests.exceptions.Timeout:
logger.error("Telegram request timed out")
return False
except Exception as e:
logger.error(f"Error sending Telegram message: {e}")
return False
async def send_funding_alert(self, alert: dict) -> bool:
"""
Send a formatted funding rate alert
Args:
alert: Alert dictionary with funding rate info
Returns:
True if sent successfully
"""
message = self._format_funding_alert(alert)
return await self.send_message(message)
def _format_funding_alert(self, alert: dict) -> str:
"""Format funding rate alert as Telegram message"""
symbol = html.escape(alert.get("symbol", "UNKNOWN"))
rate = alert.get("fundingRate", 0)
prev_rate = alert.get("prevFundingRate")
alert_type = alert.get("alertType", "change")
funding_interval = alert.get("fundingInterval", "8h")
prev_interval = alert.get("prevFundingInterval", funding_interval)
settlement_time = alert.get("settlementTime", "")
# Format rates as percentages with + for positive
rate_pct = rate * 100
def format_rate(r):
return f"+{r:.4f}%" if r >= 0 else f"{r:.4f}%"
# Determine color based on current rate
if rate >= 0:
color_emoji = "🟢"
else:
color_emoji = "🔴"
# Handle LIVE RATE alerts (previously called "predicted")
if alert_type == "predicted":
if rate >= 0:
bias_text = "Positive (Longs Pay Shorts)"
else:
bias_text = "Negative (Shorts Pay Longs)"
header = f"⚡ <b>EXTREME FUNDING RATE</b>\n\n{color_emoji} <b>{symbol}</b>"
message = f"""{header}
• Bias: {bias_text}
• Live Rate: <b>{format_rate(rate_pct)}</b>
• Interval: {funding_interval}
• Settles: {settlement_time}
<i>This rate will settle at the next funding time</i>"""
return message.strip()
# For settlement alerts, we need prev_rate
prev_rate_pct = (prev_rate or 0) * 100
# Determine bias text based on sign change
prev_positive = (prev_rate or 0) >= 0
curr_positive = rate >= 0
is_flip = False
if prev_rate is not None:
if prev_positive and not curr_positive:
bias_text = "Flipped from Positive to Negative"
color_emoji = "🔴"
is_flip = True
elif not prev_positive and curr_positive:
bias_text = "Flipped from Negative to Positive"
color_emoji = "🟢"
is_flip = True
elif curr_positive:
bias_text = "Positive (Longs Pay Shorts)"
else:
bias_text = "Negative (Shorts Pay Longs)"
else:
if curr_positive:
bias_text = "Positive (Longs Pay Shorts)"
else:
bias_text = "Negative (Shorts Pay Longs)"
# Check for interval change
interval_text = f"{funding_interval}"
is_interval_change = prev_interval and prev_interval != funding_interval
if is_interval_change:
interval_text = f"{prev_interval} → {funding_interval}"
# Build header based on alert type
if alert_type == "extreme":
header = f"⚠️ <b>EXTREME RATE</b>\n\n{color_emoji} <b>{symbol}</b>"
elif is_flip:
header = f"🔄 <b>BIAS FLIPPED</b>\n\n{color_emoji} <b>{symbol}</b>"
elif is_interval_change:
header = f"⏰ <b>INTERVAL CHANGED</b>\n\n{color_emoji} <b>{symbol}</b>"
else:
header = f"{color_emoji} <b>{symbol}</b>"
# Clean format with only green/red dots and bullets
if prev_rate is not None:
rate_line = f"• Rate: <b>{format_rate(prev_rate_pct)}</b> → <b>{format_rate(rate_pct)}</b>"
else:
rate_line = f"• Rate: <b>{format_rate(rate_pct)}</b>"
message = f"""{header}
• Bias: {bias_text}
{rate_line}
• Interval: {interval_text}
• Settled: {settlement_time}"""
return message.strip()
async def send_startup_message(self, symbols: list, intervals: dict = None) -> bool:
"""Send bot startup notification"""
# Count by interval if provided
interval_info = ""
if intervals:
interval_info = f"""
<b>Funding Intervals:</b>
• 1-hour: {intervals.get('1', 0)} symbols
• 2-hour: {intervals.get('2', 0)} symbols
• 4-hour: {intervals.get('4', 0)} symbols
• 8-hour: {intervals.get('8', 0)} symbols
"""
message = f"""
🚀 <b>Funding Rate Bot Started</b>
Monitoring <b>{len(symbols)}</b> symbols for funding rate changes.
{interval_info}
<b>Alert Types:</b>
• ⚡ Extreme live rates (before settlement)
• ⚠️ Extreme rates at settlement (≥0.1%)
• 🔄 Rate flips (+ ↔ -)
<i>Bot checks every 30 minutes.</i>
"""
return await self.send_message(message.strip())
async def send_startup_message_old(self, symbols: list) -> bool:
"""Send bot startup notification"""
safe_symbols = [html.escape(s) for s in symbols]
message = f"""
🚀 <b>Mudrex Funding Rate Bot Started</b>
Monitoring {len(symbols)} symbols for funding rate changes:
{', '.join(safe_symbols[:5])}{'...' if len(symbols) > 5 else ''}
Alerts will be sent when:
• Funding rate changes significantly
• Rate becomes extreme (>0.1%)
• Rate flips (positive ↔ negative)
<i>Bot is now active!</i>
"""
return await self.send_message(message.strip())
async def send_summary(self, rates: dict) -> bool:
"""Send a summary of current funding rates"""
if not rates:
return await self.send_message("No funding rate data available.")
# Sort by absolute funding rate (most extreme first)
sorted_rates = sorted(
rates.items(),
key=lambda x: abs(x[1].get("fundingRate", 0)),
reverse=True
)
lines = ["📊 <b>Current Funding Rates (Top 10)</b>\n"]
for symbol, data in sorted_rates[:10]:
safe_symbol = html.escape(symbol)
rate = data.get("fundingRate", 0)
rate_pct = rate * 100
if rate > 0.0005:
emoji = "🔴" # High positive (longs pay)
elif rate > 0:
emoji = "🟠" # Positive
elif rate < -0.0005:
emoji = "🟢" # High negative (shorts pay)
elif rate < 0:
emoji = "🔵" # Negative
else:
emoji = "⚪"
lines.append(f"{emoji} <b>{safe_symbol}</b>: {rate_pct:+.4f}%")
lines.append("\n<i>🔴 Longs pay | 🟢 Shorts pay</i>")
return await self.send_message("\n".join(lines))