-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtelegram_bot.py
More file actions
585 lines (500 loc) · 22 KB
/
Copy pathtelegram_bot.py
File metadata and controls
585 lines (500 loc) · 22 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
"""
Modernized Telegram bot integration with python-telegram-bot v20+
"""
import asyncio
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Dict, List, Optional
from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.constants import ParseMode
from telegram.error import BadRequest, RetryAfter, TelegramError
from telegram.ext import (
Application,
CallbackQueryHandler,
CommandHandler,
)
from database import get_trading_stats, log_error
from logger import get_logger
logger = get_logger("telegram_bot")
@dataclass
class TradeSignal:
"""Trade signal data structure"""
symbol: str
action: str # "LONG", "SHORT", "CLOSE", "HOLD"
price: float
confidence: float
position: float
pnl: Optional[float] = None
pnl_pct: Optional[float] = None
reason: str = ""
timestamp: datetime = None
def __post_init__(self):
if self.timestamp is None:
self.timestamp = datetime.now()
class TelegramNotifications:
"""Enhanced Telegram notification system"""
def __init__(self, token: str, chat_id: str):
self.bot = Bot(token=token)
self.chat_id = chat_id
self.enabled = bool(token and chat_id)
self.logger = get_logger("telegram_notifications")
# Rate limiting
self.last_message_time = {}
self.message_queue = asyncio.Queue()
self.rate_limit_delay = 1.0 # seconds between messages
# Message formatting
self.use_markdown = True
self.message_templates = self._load_templates()
if self.enabled:
self.logger.info("Telegram notifications enabled", chat_id=chat_id)
else:
self.logger.warning("Telegram notifications disabled - missing credentials")
def _load_templates(self) -> Dict[str, str]:
"""Load message templates"""
return {
"position_opened": (
"🔔 <b>POSITION OPENED</b>\n"
"🪙 <b>{symbol}</b>\n"
"💰 <b>Entry Price:</b> <code>${price:,.2f}</code>\n"
"📊 <b>Action:</b> {action_emoji} <b>{action}</b>\n"
"📈 <b>Confidence:</b> <code>{confidence:.1%}</code>\n"
"📝 <b>Reason:</b> {reason}\n"
"⏱️ <b>Time:</b> <code>{timestamp}</code>"
),
"position_closed": (
"🔔 <b>POSITION CLOSED</b>\n"
"🪙 <b>{symbol}</b>\n"
"💰 <b>Exit Price:</b> <code>${price:,.2f}</code>\n"
"📈 <b>PnL:</b> {pnl_emoji} <b>{pnl_color}{pnl_pct:+.2%}</b>\n"
"💵 <b>Profit:</b> {pnl_color}${profit:,.2f}\n"
"📝 <b>Reason:</b> {reason}\n"
"⏱️ <b>Duration:</b> <code>{duration:.1f}h</code>\n"
"⏰ <b>Time:</b> <code>{timestamp}</code>"
),
"signal": (
"📊 <b>TRADING SIGNAL</b>\n"
"🪙 <b>{symbol}</b>\n"
"💰 <b>Price:</b> <code>${price:,.2f}</code>\n"
"📈 <b>Signal:</b> {action_emoji} <b>{action}</b>\n"
"📊 <b>Position:</b> <code>{position:+.2f}</code>\n"
"🎯 <b>Confidence:</b> <code>{confidence:.1%}</code>\n"
"⏰ <b>Time:</b> <code>{timestamp}</code>"
),
"error": (
"⚠️ <b>SYSTEM ERROR</b>\n"
"🔧 <b>Component:</b> <code>{source}</code>\n"
"❌ <b>Error:</b> <code>{error}</code>\n"
"🪙 <b>Symbol:</b> <code>{symbol}</code>\n"
"⏰ <b>Time:</b> <code>{timestamp}</code>"
),
"warning": (
"⚠️ <b>WARNING</b>\n"
"🔧 <b>Component:</b> <code>{source}</code>\n"
"📝 <b>Message:</b> {message}\n"
"🪙 <b>Symbol:</b> <code>{symbol}</code>\n"
"⏰ <b>Time:</b> <code>{timestamp}</code>"
),
}
async def send_message(
self,
message: str,
parse_mode: str = ParseMode.HTML,
reply_markup: Optional[InlineKeyboardMarkup] = None,
) -> bool:
"""Send message with rate limiting and error handling"""
if not self.enabled:
return False
# Rate limiting
current_time = datetime.now()
time_since_last = (
current_time - self.last_message_time.get("general", current_time)
).total_seconds()
if time_since_last < self.rate_limit_delay:
await asyncio.sleep(self.rate_limit_delay - time_since_last)
try:
await self.bot.send_message(
chat_id=self.chat_id,
text=message,
parse_mode=parse_mode,
reply_markup=reply_markup,
disable_web_page_preview=True,
)
self.last_message_time["general"] = datetime.now()
return True
except RetryAfter as e:
self.logger.warning(f"Telegram rate limit hit, waiting {e.retry_after}s")
await asyncio.sleep(e.retry_after)
return await self.send_message(message, parse_mode, reply_markup)
except BadRequest as e:
self.logger.error(f"Bad request error: {e}")
return False
except TelegramError as e:
self.logger.error(f"Telegram error sending message: {e}")
log_error(e, "telegram_bot", f"Failed to send message: {message[:100]}")
return False
async def send_trade_signal(self, signal: TradeSignal) -> bool:
"""Send trading signal notification"""
if not self.enabled:
return True
# Determine message type and template
if "OPENED" in signal.action:
template = "position_opened"
action_emoji = "🟢" if "LONG" in signal.action else "🔴"
elif "CLOSED" in signal.action:
template = "position_closed"
action_emoji = ""
else:
template = "signal"
action_emoji = (
"🟢"
if "LONG" in signal.action
else "🔴"
if "SHORT" in signal.action
else "⚪️"
)
# Format message
try:
message = self.message_templates[template].format(
symbol=signal.symbol,
action=signal.action,
action_emoji=action_emoji,
price=signal.price,
confidence=signal.confidence,
position=signal.position,
reason=signal.reason,
timestamp=signal.timestamp.strftime("%H:%M:%S"),
pnl=signal.pnl,
pnl_pct=signal.pnl_pct,
profit=signal.pnl * abs(signal.position)
if signal.pnl and signal.position
else 0,
pnl_emoji="✅"
if signal.pnl and signal.pnl > 0
else "❌"
if signal.pnl and signal.pnl < 0
else "⚪️",
pnl_color="green" if signal.pnl and signal.pnl >= 0 else "red",
duration=0, # Will be calculated if needed
)
# Add inline buttons for closed positions
reply_markup = None
if template == "position_closed":
keyboard = [
[
InlineKeyboardButton(
"📊 View Details",
callback_data=f"trade_details_{signal.symbol}",
),
InlineKeyboardButton(
"📈 Analytics", callback_data=f"analytics_{signal.symbol}"
),
]
]
reply_markup = InlineKeyboardMarkup(keyboard)
return await self.send_message(message, reply_markup=reply_markup)
except Exception as e:
self.logger.error(f"Error formatting trade signal: {e}")
return False
async def send_error_alert(
self, error: Exception, source: str, symbol: str = ""
) -> bool:
"""Send error alert"""
signal = TradeSignal(
symbol=symbol or "SYSTEM",
action="ERROR",
price=0,
confidence=0,
position=0,
reason=str(error),
timestamp=datetime.now(),
)
message = self.message_templates["error"].format(
symbol=signal.symbol,
source=source,
error=str(error)[:200], # Limit error message length
timestamp=signal.timestamp.strftime("%H:%M:%S"),
)
return await self.send_message(message)
async def send_warning(self, message: str, source: str, symbol: str = "") -> bool:
"""Send warning message"""
warning_message = self.message_templates["warning"].format(
symbol=symbol or "SYSTEM",
source=source,
message=message,
timestamp=datetime.now().strftime("%H:%M:%S"),
)
return await self.send_message(warning_message)
async def send_performance_report(self, symbols: List[str] = None) -> bool:
"""Send performance report"""
try:
# Get trading statistics
if symbols:
stats = {
symbol: get_trading_stats(symbol, hours=24) for symbol in symbols
}
else:
stats = {"ALL": get_trading_stats(hours=24)}
# Build report message
report_lines = [
"📊 <b>DAILY PERFORMANCE REPORT</b>\n",
"=" * 30,
f"📅 <b>Date:</b> <code>{datetime.now().strftime('%Y-%m-%d')}</code>",
f"⏰ <b>Time:</b> <code>{datetime.now().strftime('%H:%M:%S')}</code>\n",
]
total_profit = 0
total_trades = 0
total_wins = 0
for symbol, stat in stats.items():
if stat["total_trades"] > 0:
profit_color = "green" if stat["total_profit"] >= 0 else "red"
report_lines.extend(
[
f"\n<b>🪙 {symbol}</b>\n",
f"📈 <b>Trades:</b> <code>{stat['total_trades']}</code>\n",
f"✅ <b>Win Rate:</b> <code>{stat['win_rate']:.1%}</code>\n",
f"💰 <b>PnL:</b> <b><{profit_color}>{stat['total_profit']:+.2%}</{profit_color}></b>\n",
f"📊 <b>Avg Profit:</b> <code>{stat['avg_profit']:+.2%}</code>\n",
f"🎯 <b>Max Profit:</b> <code>{stat['max_profit']:+.2%}</code>\n",
f"⚠️ <b>Max Loss:</b> <code>{stat['max_loss']:+.2%}</code>",
]
)
total_profit += stat["total_profit"]
total_trades += stat["total_trades"]
total_wins += stat["winning_trades"]
# Add summary
if total_trades > 0:
overall_win_rate = total_wins / total_trades
overall_color = "green" if total_profit >= 0 else "red"
report_lines.extend(
[
"\n<b>📊 SUMMARY</b>\n",
f"🎯 <b>Total Trades:</b> <code>{total_trades}</code>\n",
f"📈 <b>Overall Win Rate:</b> <code>{overall_win_rate:.1%}</code>\n",
f"💰 <b>Total PnL:</b> <b><{overall_color}>{total_profit:+.2%}</{overall_color}></b>",
]
)
else:
report_lines.append("\n📝 <b>No trades in the last 24 hours</b>")
# Add inline buttons
keyboard = [
[
InlineKeyboardButton(
"📊 Detailed Stats", callback_data="detailed_stats"
),
InlineKeyboardButton("🔄 Refresh", callback_data="refresh_report"),
],
[
InlineKeyboardButton("⚙️ Settings", callback_data="settings"),
InlineKeyboardButton("❓ Help", callback_data="help"),
],
]
reply_markup = InlineKeyboardMarkup(keyboard)
return await self.send_message(
"\n".join(report_lines), reply_markup=reply_markup
)
except Exception as e:
self.logger.error(f"Error generating performance report: {e}")
await self.send_error_alert(e, "performance_report")
return False
class InteractiveTelegramBot:
"""Interactive Telegram bot with command handling"""
def __init__(self, token: str, chat_id: str):
self.token = token
self.chat_id = chat_id
self.notifications = TelegramNotifications(token, chat_id)
self.application = None
self.logger = get_logger("telegram_bot")
# Trading state (shared with main application)
self.trading_state = {}
self.active_symbols = set()
async def start(self):
"""Start the bot application"""
try:
self.application = Application.builder().token(self.token).build()
# Add handlers
self.application.add_handler(CommandHandler("start", self.cmd_start))
self.application.add_handler(CommandHandler("help", self.cmd_help))
self.application.add_handler(CommandHandler("status", self.cmd_status))
self.application.add_handler(CommandHandler("stats", self.cmd_stats))
self.application.add_handler(CommandHandler("report", self.cmd_report))
self.application.add_handler(CommandHandler("pause", self.cmd_pause))
self.application.add_handler(CommandHandler("resume", self.cmd_resume))
self.application.add_handler(CallbackQueryHandler(self.handle_callback))
# Start the application
await self.application.initialize()
await self.application.start()
self.logger.info("Telegram bot started successfully")
# Send startup message
await self.notifications.send_message(
"🤖 <b>RL Crypto Trader Bot Started</b>\n"
"✅ Bot is now online and monitoring markets\n"
"Use /help to see available commands"
)
except Exception as e:
self.logger.error(f"Error starting Telegram bot: {e}")
raise
async def shutdown(self):
"""Gracefully shutdown the bot"""
try:
if self.application:
await self.application.stop()
await self.application.shutdown()
self.logger.info("Telegram bot shutdown successfully")
except Exception as e:
self.logger.error(f"Error shutting down Telegram bot: {e}")
async def cmd_start(self, update: Update, context):
"""Handle /start command"""
message = (
"🤖 <b>Welcome to RL Crypto Trader</b>\n\n"
"This bot provides real-time trading signals and performance reports "
"for our reinforcement learning crypto trading system.\n\n"
"📊 <b>Available Commands:</b>\n"
"/help - Show this help message\n"
"/status - Current trading status\n"
"/stats - Trading statistics\n"
"/report - Performance report\n"
"/pause - Pause trading\n"
"/resume - Resume trading\n\n"
"🔔 <b>Notifications:</b>\n"
"You'll receive automatic notifications for:\n"
"• Position openings and closings\n"
"• Trading signals\n"
"• Daily performance reports\n"
"• System errors and warnings"
)
await update.message.reply_text(message, parse_mode=ParseMode.HTML)
async def cmd_help(self, update: Update, context):
"""Handle /help command"""
await self.cmd_start(update, context) # Same as start
async def cmd_status(self, update: Update, context):
"""Handle /status command"""
try:
status_lines = ["📊 <b>Current Trading Status</b>\n", "=" * 25]
for symbol in self.active_symbols:
if symbol in self.trading_state:
state = self.trading_state[symbol]
pos_emoji = (
"🟢"
if state.get("position", 0) > 0
else "🔴"
if state.get("position", 0) < 0
else "⚪️"
)
pos_str = (
"LONG"
if state.get("position", 0) > 0
else "SHORT"
if state.get("position", 0) < 0
else "FLAT"
)
status_lines.extend(
[
f"\n<b>🪙 {symbol}</b>\n",
f"{pos_emoji} <b>Position:</b> {pos_str}\n",
f"💰 <b>Price:</b> <code>${state.get('price', 0):,.2f}</code>\n",
f"📈 <b>PnL:</b> <code>{state.get('pnl', 0):+.2%}</code>\n",
f"🎯 <b>Confidence:</b> <code>{state.get('confidence', 0):.1%}</code>",
]
)
if not self.active_symbols:
status_lines.append("\n⚪️ <b>No active symbols</b>")
status_lines.extend(
[
f"\n🤖 <b>Bot Status:</b> ✅ Online\n"
f"⏰ <b>Uptime:</b> <code>{self._get_uptime()}</code>"
]
)
await update.message.reply_text(
"\n".join(status_lines), parse_mode=ParseMode.HTML
)
except Exception as e:
self.logger.error(f"Error in status command: {e}")
await update.message.reply_text("❌ Error retrieving status")
async def cmd_stats(self, update: Update, context):
"""Handle /stats command"""
try:
stats_lines = ["📊 <b>Trading Statistics</b>\n", "=" * 25]
for symbol in self.active_symbols:
stats = get_trading_stats(symbol, hours=24)
if stats["total_trades"] > 0:
stats_lines.extend(
[
f"\n<b>🪙 {symbol}</b>\n",
f"📈 <b>Trades:</b> <code>{stats['total_trades']}</code>\n",
f"✅ <b>Win Rate:</b> <code>{stats['win_rate']:.1%}</code>\n",
f"💰 <b>PnL:</b> <code>{stats['total_profit']:+.2%}</code>",
]
)
await update.message.reply_text(
"\n".join(stats_lines), parse_mode=ParseMode.HTML
)
except Exception as e:
self.logger.error(f"Error in stats command: {e}")
await update.message.reply_text("❌ Error retrieving statistics")
async def cmd_report(self, update: Update, context):
"""Handle /report command"""
await self.notifications.send_performance_report(list(self.active_symbols))
await update.message.reply_text("📊 Performance report sent!")
async def cmd_pause(self, update: Update, context):
"""Handle /pause command"""
# This would integrate with the main trading system
await update.message.reply_text(
"⏸️ <b>Trading paused</b>\nUse /resume to continue",
parse_mode=ParseMode.HTML,
)
async def cmd_resume(self, update: Update, context):
"""Handle /resume command"""
# This would integrate with the main trading system
await update.message.reply_text(
"▶️ <b>Trading resumed</b>", parse_mode=ParseMode.HTML
)
async def handle_callback(self, update: Update, context):
"""Handle inline keyboard callbacks"""
query = update.callback_query
await query.answer()
data = query.data
if data == "detailed_stats":
await self.cmd_stats(update, context)
elif data == "refresh_report":
await self.notifications.send_performance_report(list(self.active_symbols))
await query.edit_message_text("📊 Report refreshed!")
elif data.startswith("analytics_"):
symbol = data.split("_")[1]
# Handle analytics request
await query.edit_message_text(f"📈 Analytics for {symbol} - Coming soon!")
elif data.startswith("trade_details_"):
symbol = data.split("_")[2]
# Handle trade details request
await query.edit_message_text(
f"📊 Trade details for {symbol} - Coming soon!"
)
def _get_uptime(self) -> str:
"""Get bot uptime"""
# This should track actual startup time
return "Unknown" # Placeholder
async def send_system_alert(self, message: str) -> bool:
"""Send system health alert"""
try:
alert_message = f"🚨 <b>SYSTEM ALERT</b>\n\n{message}"
return await self.send_message(alert_message)
except Exception as e:
self.logger.error(f"Failed to send system alert: {e}")
return False
def update_trading_state(self, symbol: str, state: Dict[str, Any]):
"""Update trading state for a symbol"""
self.trading_state[symbol] = state
self.active_symbols.add(symbol)
async def send_trade_signal(self, signal: TradeSignal) -> bool:
"""Send trade signal through notification system"""
# Update trading state
self.update_trading_state(
signal.symbol,
{
"position": signal.position,
"price": signal.price,
"pnl": signal.pnl,
"confidence": signal.confidence,
"timestamp": signal.timestamp,
},
)
return await self.notifications.send_trade_signal(signal)