crypto-scanner-bot 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. crypto_scanner/__init__.py +207 -0
  2. crypto_scanner/__main__.py +46 -0
  3. crypto_scanner/blocks/__init__.py +1 -0
  4. crypto_scanner/blocks/balances.py +47 -0
  5. crypto_scanner/blocks/dashboard.py +535 -0
  6. crypto_scanner/blocks/positions.py +407 -0
  7. crypto_scanner/blocks/settings.py +448 -0
  8. crypto_scanner/blocks/tokens.py +326 -0
  9. crypto_scanner/buttons.py +88 -0
  10. crypto_scanner/constants.py +35 -0
  11. crypto_scanner/db/__init__.py +14 -0
  12. crypto_scanner/db/core.py +80 -0
  13. crypto_scanner/db/options.py +20 -0
  14. crypto_scanner/db/schema.py +139 -0
  15. crypto_scanner/db/tokens.py +598 -0
  16. crypto_scanner/health.py +221 -0
  17. crypto_scanner/helpers.py +119 -0
  18. crypto_scanner/jobs.py +408 -0
  19. crypto_scanner/networks.py +509 -0
  20. crypto_scanner/py.typed +0 -0
  21. crypto_scanner/settings.py +139 -0
  22. crypto_scanner/text_input.py +22 -0
  23. crypto_scanner/trading/__init__.py +1 -0
  24. crypto_scanner/trading/monitors.py +465 -0
  25. crypto_scanner/trading/trending.py +230 -0
  26. crypto_scanner/trading/watchers.py +165 -0
  27. crypto_scanner/w3/__init__.py +169 -0
  28. crypto_scanner/w3/audit.py +529 -0
  29. crypto_scanner/w3/tools.py +161 -0
  30. crypto_scanner/w3/trade.py +495 -0
  31. crypto_scanner/w3/v4.py +138 -0
  32. crypto_scanner/web/__init__.py +34 -0
  33. crypto_scanner/web/auth.py +150 -0
  34. crypto_scanner/web/charts.py +130 -0
  35. crypto_scanner/web/core.py +46 -0
  36. crypto_scanner/web/pages.py +150 -0
  37. crypto_scanner/web/views.py +538 -0
  38. crypto_scanner_bot-2.0.0.dist-info/METADATA +166 -0
  39. crypto_scanner_bot-2.0.0.dist-info/RECORD +42 -0
  40. crypto_scanner_bot-2.0.0.dist-info/WHEEL +5 -0
  41. crypto_scanner_bot-2.0.0.dist-info/licenses/LICENSE +21 -0
  42. crypto_scanner_bot-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,535 @@
1
+ """The scanner dashboard: stats per monitor, Health, Archive and Sell All."""
2
+
3
+ from typing import Any
4
+
5
+ from telegram import InlineKeyboardButton, InlineKeyboardMarkup, LoginUrl, Update
6
+ from telegram.ext import ContextTypes
7
+
8
+ from .. import jobs
9
+ from ..constants import PAIR_STATUS, STATS_PERIODS
10
+ from ..db.tokens import (
11
+ clear_archive,
12
+ tokens_get_by_id,
13
+ tokens_get_stats,
14
+ tokens_mark_completed,
15
+ tokens_reset_db,
16
+ )
17
+ from ..health import scanner_health
18
+ from ..helpers import escape_markdown, format_timestamp
19
+ from ..settings import MODE_NAMES, MODE_OFF, SETTINGS, current_mode
20
+ from ..trading.monitors import run_sell_all
21
+ from ..w3.tools import fetch_eth_usd_price
22
+ from . import positions, tokens
23
+
24
+
25
+ async def handle_block(
26
+ context: ContextTypes.DEFAULT_TYPE | None,
27
+ status_arg: str | None = None,
28
+ table: str = "tokens",
29
+ brief: bool = False,
30
+ ) -> dict[str, Any]:
31
+ module = positions if table == "positions" else tokens
32
+ if status_arg and status_arg.isdigit():
33
+ return await module.block_detail(context, status_arg, table)
34
+ if status_arg:
35
+ return await module.block_list(context, status_arg)
36
+ return await _block(context, brief=brief)
37
+
38
+
39
+ async def handle_button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
40
+ query = update.callback_query
41
+
42
+ parts = query.data.split(":")
43
+ action = parts[1] if len(parts) > 1 else "main"
44
+
45
+ if action == "period":
46
+ block = await _block(context, days=int(parts[2]))
47
+ await query.edit_message_text(
48
+ text=block["text"],
49
+ reply_markup=block["reply_markup"],
50
+ parse_mode="Markdown",
51
+ disable_web_page_preview=True,
52
+ )
53
+
54
+ elif action == "refresh":
55
+ row_id = parts[2]
56
+ block = await handle_block(context, status_arg=row_id)
57
+ await query.edit_message_text(
58
+ text="🔄 *Refreshing data...*\n\n" + block["text"],
59
+ reply_markup=block["reply_markup"],
60
+ parse_mode="Markdown",
61
+ )
62
+
63
+ elif action == "health":
64
+ report = await scanner_health()
65
+ alerts = report["alerts"]
66
+ header = "🚨 *SCANNER HEALTH ALERT*" if alerts else "💚 *SCANNER HEALTH OK*"
67
+ dashboard = (
68
+ [
69
+ [
70
+ InlineKeyboardButton(
71
+ "🔧 Open database dashboard", url=SETTINGS.db_dashboard_url
72
+ )
73
+ ]
74
+ ]
75
+ if report.get("db_problem") and SETTINGS.db_dashboard_url
76
+ else []
77
+ )
78
+ await query.edit_message_text(
79
+ f"{header}\n\n"
80
+ + ("\n".join(f"• {a}" for a in alerts) + "\n\n" if alerts else "")
81
+ + report["text"],
82
+ reply_markup=InlineKeyboardMarkup(
83
+ dashboard
84
+ + [
85
+ [
86
+ InlineKeyboardButton(
87
+ "🔄 Refresh", callback_data="scanner:health"
88
+ )
89
+ ],
90
+ [
91
+ InlineKeyboardButton(
92
+ "🔙 Back to Scanner", callback_data="scanner:dashboard"
93
+ )
94
+ ],
95
+ [InlineKeyboardButton("❌ Close", callback_data="cancel")],
96
+ ]
97
+ ),
98
+ parse_mode="Markdown",
99
+ )
100
+
101
+ elif action == "rejected":
102
+ await tokens.button_rejected(update, context)
103
+
104
+ elif action == "status":
105
+ await _button_status(update, context)
106
+
107
+ elif action == "preview":
108
+ await tokens.button_preview(update, context)
109
+
110
+ elif action == "buy_confirm":
111
+ await tokens.button_buy_confirm(update, context)
112
+
113
+ elif action == "buy":
114
+ await tokens.button_buy(update, context)
115
+
116
+ elif action == "sell_all_confirm":
117
+ await query.edit_message_text(
118
+ "⚠️ *Sell every token the bot has bought?*\n\n"
119
+ "This sells whatever is still in the wallet, including positions "
120
+ "already marked completed. Tokens worth less than the gas are skipped.",
121
+ parse_mode="Markdown",
122
+ reply_markup=InlineKeyboardMarkup(
123
+ [
124
+ [
125
+ InlineKeyboardButton(
126
+ "❌ Cancel", callback_data="scanner:dashboard"
127
+ ),
128
+ InlineKeyboardButton(
129
+ "✅ Yes, Sell All", callback_data="scanner:sell_all"
130
+ ),
131
+ ]
132
+ ]
133
+ ),
134
+ )
135
+
136
+ elif action == "sell_all":
137
+ await query.edit_message_text("⏳ *Selling...*", parse_mode="Markdown")
138
+ result = await run_sell_all(context)
139
+ block = await handle_block(context)
140
+ await query.edit_message_text(
141
+ f"{result}\n\n{block['text']}",
142
+ reply_markup=block["reply_markup"],
143
+ parse_mode="Markdown",
144
+ disable_web_page_preview=True,
145
+ )
146
+
147
+ elif action == "p-status":
148
+ await positions.button_status(update, context)
149
+
150
+ elif action == "sell":
151
+ await positions.button_sell(update, context)
152
+
153
+ elif action == "remove_confirm":
154
+ table = parts[2]
155
+ row_id = parts[3]
156
+ record = await tokens_get_by_id(row_id, table)
157
+ symbol = escape_markdown((record or {}).get("symbol") or "Unknown")
158
+ back_cb = "p-status" if table == "positions" else "status"
159
+ action_label = (
160
+ "close this position"
161
+ if table == "positions"
162
+ else "mark this token as completed"
163
+ )
164
+
165
+ await query.edit_message_text(
166
+ f"⚠️ *Are you sure you want to {action_label}?*\n\n${symbol} #{row_id}",
167
+ parse_mode="Markdown",
168
+ reply_markup=InlineKeyboardMarkup(
169
+ [
170
+ [
171
+ InlineKeyboardButton(
172
+ "❌ Cancel",
173
+ callback_data=f"scanner:{back_cb}:{row_id}",
174
+ ),
175
+ InlineKeyboardButton(
176
+ "✅ Yes, Confirm",
177
+ callback_data=f"scanner:remove:{parts[2]}:{row_id}",
178
+ ),
179
+ ]
180
+ ]
181
+ ),
182
+ )
183
+
184
+ elif action == "remove":
185
+ table = parts[2]
186
+ row_id = parts[3]
187
+ record = await tokens_get_by_id(row_id, table)
188
+ symbol = escape_markdown((record or {}).get("symbol") or "Unknown")
189
+
190
+ if record:
191
+ await tokens_mark_completed(record["target_address"])
192
+
193
+ block = await handle_block(context)
194
+ await query.edit_message_text(
195
+ f"✅ *#{row_id}* (${symbol}) marked as completed.\n\n" + block["text"],
196
+ parse_mode="Markdown",
197
+ reply_markup=block["reply_markup"],
198
+ disable_web_page_preview=True,
199
+ )
200
+
201
+ elif action == "wipe" and parts[2:3] in (["archive"], ["tokens"]):
202
+ what = parts[2]
203
+ await query.edit_message_text(
204
+ "⚠️ *Clear the archive?*\n\nRemoves rejected tokens and positions "
205
+ "closed more than 7 days ago."
206
+ if what == "archive"
207
+ else "⚠️ *Clear all tokens?*\n\nRemoves every token and position, "
208
+ "including open ones. Tokens in the wallet are not sold.",
209
+ parse_mode="Markdown",
210
+ reply_markup=InlineKeyboardMarkup(
211
+ [
212
+ [
213
+ InlineKeyboardButton(
214
+ "❌ Cancel", callback_data="scanner:archive"
215
+ ),
216
+ InlineKeyboardButton(
217
+ "✅ Yes, Clear", callback_data=f"scanner:wiped:{what}"
218
+ ),
219
+ ]
220
+ ]
221
+ ),
222
+ )
223
+
224
+ elif action == "wiped" and parts[2:3] in (["archive"], ["tokens"]):
225
+ if parts[2] == "archive":
226
+ await clear_archive()
227
+ else:
228
+ await tokens_reset_db()
229
+ block = await _block_archive(context)
230
+ await query.edit_message_text(
231
+ text=f"✅ {parts[2].capitalize()} cleared.\n\n" + block["text"],
232
+ reply_markup=block["reply_markup"],
233
+ parse_mode="Markdown",
234
+ disable_web_page_preview=True,
235
+ )
236
+
237
+ elif action == "archive":
238
+ block = await _block_archive(context)
239
+ await query.edit_message_text(
240
+ text=block["text"],
241
+ reply_markup=block["reply_markup"],
242
+ parse_mode="Markdown",
243
+ disable_web_page_preview=True,
244
+ )
245
+
246
+
247
+ async def _block(
248
+ context: ContextTypes.DEFAULT_TYPE | None, days: int = 1, brief: bool = False
249
+ ) -> dict[str, Any]:
250
+ stats, last_buy, last_sell, last_scan = await tokens_get_stats(days=days)
251
+ mon_count = stats.get("active_positions", 0)
252
+
253
+ if not stats or stats.get("total", 0) == 0:
254
+ if brief:
255
+ return {"text": ""}
256
+ return {
257
+ "text": "🤖 *Crypto Scanner*\n\n"
258
+ "🪙 *Tokens*\n"
259
+ f"🆕 New: {MODE_NAMES[current_mode('new')]}\n"
260
+ f"📈 Trending: {MODE_NAMES[current_mode('trending')]}\n\n"
261
+ "📡 No new tokens found yet.",
262
+ "reply_markup": InlineKeyboardMarkup(
263
+ [
264
+ [
265
+ InlineKeyboardButton(
266
+ "🔄 Refresh", callback_data="scanner:dashboard"
267
+ )
268
+ ],
269
+ [
270
+ InlineKeyboardButton(
271
+ "₿ Balances", callback_data="scanner:balances"
272
+ ),
273
+ InlineKeyboardButton(
274
+ "⚙️ Settings", callback_data="scanner:settings"
275
+ ),
276
+ ],
277
+ [InlineKeyboardButton("❌ Close", callback_data="cancel")],
278
+ ]
279
+ ),
280
+ }
281
+
282
+ _, last_scan_ts = (
283
+ format_timestamp(last_scan["found_at"]) if last_scan else (None, "Never")
284
+ )
285
+
286
+ _, last_buy_ts = (
287
+ format_timestamp(last_buy["found_at"]) if last_buy else (None, "Never")
288
+ )
289
+ _, last_sell_ts = (
290
+ format_timestamp(last_sell["found_at"]) if last_sell else (None, "Never")
291
+ )
292
+
293
+ stat_text = (
294
+ "" if brief else f"*🤖 Crypto Scanner - {STATS_PERIODS[days]} Stats*\n\n"
295
+ )
296
+ shown = [
297
+ (f"{heading} · {MODE_NAMES[current_mode(monitor)]}", stats["monitors"][monitor])
298
+ for monitor, heading in (
299
+ ("new", "🆕 *New*"),
300
+ ("trending", "📈 *Trending*"),
301
+ )
302
+ if current_mode(monitor) != MODE_OFF
303
+ or any(stats["monitors"][monitor][k] for k in ("found", "bought", "closed"))
304
+ ]
305
+ if len(shown) == 2:
306
+ shown.append(("📊 *Total*", stats["combined"]))
307
+
308
+ if brief and shown:
309
+ shown = [("🤖 *Crypto Scanner*", shown[-1][1])]
310
+
311
+ eth_usd = (
312
+ await fetch_eth_usd_price() if any(m["eth_counted"] for _, m in shown) else 0
313
+ )
314
+ for heading, m in shown:
315
+ lines = [f"Found: {m['found']}", f"Rejected: {m['rejected']}"]
316
+ if m["watched"]:
317
+ lines.append(f"Would buy: {m['watched']}")
318
+ lines += [f"Bought: {m['bought']}", f"Sold: {m['closed']}"]
319
+ if m["closed"]:
320
+ lines += [
321
+ f"Avg Return: `{m['avg_pnl']:+.2f}%`",
322
+ f"Win Rate: `{m['wins'] / m['closed'] * 100:.0f}%` "
323
+ f"({m['wins']}/{m['closed']})",
324
+ ]
325
+ if m["would_closed"]:
326
+ lines.append(
327
+ f"Would have made: `{m['would_avg']:+.2f}%` "
328
+ f"({m['would_wins']}/{m['would_closed']} up)"
329
+ )
330
+ if m["eth_counted"]:
331
+ usd = m["eth_pnl"] * eth_usd
332
+ lines.append(
333
+ f"P&L: `{m['eth_pnl']:+.6f} ETH`"
334
+ + (f" ({'-' if usd < 0 else '+'}${abs(usd):.2f})" if usd else "")
335
+ )
336
+ stat_text += (
337
+ f"{heading}\n"
338
+ + "\n".join(
339
+ f" {'└' if i == len(lines) - 1 else '├'} {line}"
340
+ for i, line in enumerate(lines)
341
+ )
342
+ + "\n\n"
343
+ )
344
+ if not shown:
345
+ stat_text += f"Both monitors are {MODE_NAMES[MODE_OFF]}.\n\n"
346
+
347
+ if brief:
348
+ return {"text": stat_text}
349
+
350
+ next_pairs, next_pairs_delta = jobs.job_status(jobs.application, "New Monitor")
351
+ next_strategy, next_strategy_delta = jobs.job_status(
352
+ jobs.application, "Trending Monitor"
353
+ )
354
+ activity = [
355
+ f"Monitoring: {mon_count}",
356
+ f"Last Buy: {last_buy_ts}",
357
+ f"Last Sell: {last_sell_ts}",
358
+ f"Last Scan: {last_scan_ts}",
359
+ ]
360
+ schedule = [
361
+ f"New Monitor: {next_pairs} ({next_pairs_delta})",
362
+ f"Trending Monitor: {next_strategy} ({next_strategy_delta})",
363
+ ]
364
+ if mon_count > 0:
365
+ next_sell, next_sell_delta = jobs.job_status(jobs.application, "Sell Monitor")
366
+ schedule.append(f"Sell Monitor: {next_sell} ({next_sell_delta})")
367
+
368
+ for title, lines in (("🕒 *Activity*", activity), ("⏭️ *Next Run*", schedule)):
369
+ stat_text += (
370
+ f"{title}\n"
371
+ + "\n".join(
372
+ f" {'└' if i == len(lines) - 1 else '├'} {line}"
373
+ for i, line in enumerate(lines)
374
+ )
375
+ + "\n\n"
376
+ )
377
+
378
+ stat_text = stat_text.rstrip()
379
+
380
+ keyboard = [
381
+ [
382
+ InlineKeyboardButton(
383
+ f"• {label} •" if d == days else label,
384
+ callback_data=f"scanner:period:{d}",
385
+ )
386
+ for d, label in STATS_PERIODS.items()
387
+ ],
388
+ [InlineKeyboardButton("🔄 Refresh", callback_data=f"scanner:period:{days}")],
389
+ ]
390
+
391
+ if mon_count > 0:
392
+ keyboard.append(
393
+ [
394
+ InlineKeyboardButton(
395
+ f"📁 Monitoring ({mon_count})",
396
+ callback_data="scanner:p-status:monitoring",
397
+ )
398
+ ]
399
+ )
400
+
401
+ keyboard.append(
402
+ [
403
+ InlineKeyboardButton("₿ Balances", callback_data="scanner:balances"),
404
+ InlineKeyboardButton("⚙️ Settings", callback_data="scanner:settings"),
405
+ ]
406
+ )
407
+ keyboard.append(
408
+ [
409
+ InlineKeyboardButton("🗂 Archive", callback_data="scanner:archive"),
410
+ InlineKeyboardButton("🩺 Health", callback_data="scanner:health"),
411
+ ]
412
+ )
413
+ keyboard.append(
414
+ [InlineKeyboardButton("💼 Sell All", callback_data="scanner:sell_all_confirm")]
415
+ )
416
+ if SETTINGS.website_url:
417
+ keyboard.append(
418
+ [
419
+ InlineKeyboardButton(
420
+ "🌐 Open Website",
421
+ login_url=LoginUrl(f"{SETTINGS.website_url.rstrip('/')}/login"),
422
+ )
423
+ ]
424
+ )
425
+ keyboard.append([InlineKeyboardButton("❌ Close", callback_data="cancel")])
426
+
427
+ return {
428
+ "text": stat_text,
429
+ "reply_markup": InlineKeyboardMarkup(keyboard),
430
+ "disable_web_page_preview": True,
431
+ }
432
+
433
+
434
+ async def _block_archive(context: ContextTypes.DEFAULT_TYPE) -> dict[str, Any]:
435
+ stats, _, _, _ = await tokens_get_stats(days=1)
436
+ stats = stats or {}
437
+ mon_count = stats.get("active_positions", 0)
438
+ total_comp = stats.get("completed", 0)
439
+ awaiting = stats.get("awaiting", 0)
440
+ rejected = sum(stats.get(s, 0) for s in PAIR_STATUS)
441
+
442
+ text = (
443
+ "🤖 *Crypto Scanner - Archive*\n"
444
+ f" ├ Total: {stats.get('total', 0)}\n"
445
+ f" ├ Pending: {stats.get('pending', 0)}\n"
446
+ f" ├ Awaiting: {awaiting}\n"
447
+ f" ├ Rejected: {rejected}\n"
448
+ f" ├ Monitoring: {mon_count}\n"
449
+ f" └ Completed: {total_comp}\n"
450
+ )
451
+
452
+ keyboard = []
453
+
454
+ pos_buttons = []
455
+ if mon_count > 0:
456
+ pos_buttons.append(
457
+ InlineKeyboardButton(
458
+ f"📁 Monitoring ({mon_count})",
459
+ callback_data="scanner:p-status:monitoring",
460
+ )
461
+ )
462
+ if total_comp > 0:
463
+ pos_buttons.append(
464
+ InlineKeyboardButton(
465
+ f"📁 Completed ({total_comp})",
466
+ callback_data="scanner:p-status:completed",
467
+ )
468
+ )
469
+ if pos_buttons:
470
+ keyboard.append(pos_buttons)
471
+
472
+ if rejected > 0:
473
+ keyboard.append(
474
+ [
475
+ InlineKeyboardButton(
476
+ f"📁 Rejected ({rejected})", callback_data="scanner:rejected"
477
+ )
478
+ ]
479
+ )
480
+
481
+ if awaiting > 0:
482
+ keyboard.append(
483
+ [
484
+ InlineKeyboardButton(
485
+ f"📁 Awaiting ({awaiting})", callback_data="scanner:status:awaiting"
486
+ )
487
+ ]
488
+ )
489
+
490
+ keyboard.append(
491
+ [
492
+ InlineKeyboardButton(
493
+ "📤 Export Tokens", callback_data="scanner:export:tokens"
494
+ ),
495
+ InlineKeyboardButton(
496
+ "📤 Export Positions", callback_data="scanner:export:positions"
497
+ ),
498
+ ]
499
+ )
500
+ keyboard.append(
501
+ [
502
+ InlineKeyboardButton(
503
+ "🗑️ Clear Archive", callback_data="scanner:wipe:archive"
504
+ ),
505
+ InlineKeyboardButton(
506
+ "🎯 Clear Tokens", callback_data="scanner:wipe:tokens"
507
+ ),
508
+ ]
509
+ )
510
+ keyboard.append(
511
+ [InlineKeyboardButton("🔄 Refresh", callback_data="scanner:archive")]
512
+ )
513
+ keyboard.append(
514
+ [InlineKeyboardButton("🔙 Back to Scanner", callback_data="scanner:dashboard")]
515
+ )
516
+ keyboard.append([InlineKeyboardButton("❌ Close", callback_data="cancel")])
517
+
518
+ return {
519
+ "text": text,
520
+ "reply_markup": InlineKeyboardMarkup(keyboard),
521
+ "disable_web_page_preview": True,
522
+ }
523
+
524
+
525
+ async def _button_status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
526
+ query = update.callback_query
527
+ parts = query.data.split(":")
528
+ identifier = ":".join(parts[2:]) if len(parts) > 2 else None
529
+ block = await handle_block(context, status_arg=identifier)
530
+ await query.edit_message_text(
531
+ text=block["text"],
532
+ reply_markup=block["reply_markup"],
533
+ parse_mode="Markdown",
534
+ disable_web_page_preview=True,
535
+ )