Spaces:
Sleeping
Sleeping
Download bot.py from Anoar2025/Traingular: direct link, hf CLI and curl.
- Browser
- Download file 16.7 kB
-
https://huggingface.co/spaces/Anoar2025/Traingular/resolve/main/bot.py
- Command line
-
hf download hf://spaces/Anoar2025/Traingular/bot.py
-
curl -L -o bot.py https://huggingface.co/spaces/Anoar2025/Traingular/resolve/main/bot.py
16.7 kB
| import time | |
| import requests | |
| import os | |
| import threading | |
| from collections import defaultdict | |
| from flask import Flask, jsonify, render_template_string | |
| from datetime import datetime | |
| import sys | |
| # ---------------------- إعدادات عامة ---------------------- | |
| BASE_CURRENCY = "USDT" | |
| TRADE_AMOUNT = 50.0 | |
| MIN_PROFIT_PERCENT = 0.10 | |
| MIN_PRICE_THRESHOLD = 0.00001 | |
| # ---------------------- إعدادات تيليجرام ---------------------- | |
| TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "") | |
| TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "") | |
| # ---------------------- إعدادات البروكسي (اختياري) ---------------------- | |
| HTTP_PROXY = os.environ.get("HTTP_PROXY", None) | |
| HTTPS_PROXY = os.environ.get("HTTPS_PROXY", None) | |
| proxies = None | |
| if HTTP_PROXY or HTTPS_PROXY: | |
| proxies = { | |
| "http": HTTP_PROXY, | |
| "https": HTTPS_PROXY | |
| } | |
| print(f"🛜 تم تفعيل البروكسي: {HTTPS_PROXY or HTTP_PROXY}") | |
| # ---------------------- هياكل البيانات ---------------------- | |
| SYMBOLS_INFO = [] | |
| ALL_TRIANGLES = [] | |
| PRICE_CACHE = {} | |
| UNIQUE_SYMBOLS_NEEDED = set() | |
| # حالة البوت للمراقبة | |
| BOT_STATUS = { | |
| "running": True, | |
| "last_scan_time": None, | |
| "last_scan_duration": 0, | |
| "symbols_count": 0, | |
| "triangles_count": 0, | |
| "prices_updated": False, | |
| "last_opportunities": [], | |
| "errors": [] | |
| } | |
| # ---------------------- إرسال تنبيه تيليجرام (مع فحص الاتصال) ---------------------- | |
| def send_telegram_message(text, parse_mode="Markdown"): | |
| """إرسال رسالة عامة إلى تيليجرام (قناة أو حساب)""" | |
| if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID: | |
| print("⚠️ لم يتم تعيين توكن تيليجرام أو معرف الدردشة.") | |
| return False | |
| # --- فحص اتصال تيليجرام (يتم مرة واحدة عند البداية) --- | |
| if not hasattr(send_telegram_message, "connection_checked"): | |
| print("🛜 فحص الاتصال بـ api.telegram.org...") | |
| try: | |
| test_resp = requests.get("https://api.telegram.org", timeout=10, proxies=proxies) | |
| print(f"✅ الاتصال بـ api.telegram.org ناجح. حالة الاستجابة: {test_resp.status_code}") | |
| except Exception as e: | |
| err_msg = f"❌ فشل الاتصال بـ api.telegram.org: {e}. تأكد من عدم وجود حظر أو مشكلة DNS." | |
| print(err_msg) | |
| BOT_STATUS["errors"].append(err_msg) | |
| send_telegram_message.connection_checked = True | |
| # --- نهاية الفحص --- | |
| try: | |
| resp = requests.post( | |
| f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage", | |
| json={"chat_id": TELEGRAM_CHAT_ID, "text": text, "parse_mode": parse_mode}, | |
| timeout=15, | |
| proxies=proxies | |
| ) | |
| if resp.status_code != 200: | |
| error_msg = f"⚠️ خطأ في إرسال رسالة تيليجرام (الحالة: {resp.status_code}): {resp.text}" | |
| print(error_msg) | |
| BOT_STATUS["errors"].append(error_msg) | |
| return False | |
| return True | |
| except Exception as e: | |
| print(f"⚠️ فشل إرسال تنبيه تيليجرام: {e}") | |
| return False | |
| def send_startup_message(): | |
| message = f""" | |
| 🤖 *بوت المراجحة المثلثية قيد التشغيل* | |
| 🕒 الوقت: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | |
| 💰 العملة الأساسية: {BASE_CURRENCY} | |
| 💵 مبلغ التداول: {TRADE_AMOUNT} USDT | |
| 📊 الحد الأدنى للربح: {MIN_PROFIT_PERCENT}% | |
| """ | |
| send_telegram_message(message) | |
| def send_opportunity_alert(sym1, sym2, sym3, profit, percent, final): | |
| """إرسال إشعار فرصة إلى القناة""" | |
| message = f""" | |
| ✨ *فرصة مراجحة مثلثية مكتشفة!* | |
| المثلث: `{sym1}` → `{sym2}` → `{sym3}` | |
| 💰 الربح: `{profit:.4f} USDT` | |
| 📈 النسبة: `{percent:.4f}%` | |
| 💵 المبلغ النهائي: `{final:.4f} USDT` | |
| 🕒 {datetime.now().strftime('%H:%M:%S')} | |
| """ | |
| send_telegram_message(message) | |
| # ---------------------- تحميل الأزواج من Binance ---------------------- | |
| def load_symbols(): | |
| global SYMBOLS_INFO, BOT_STATUS | |
| print("⏳ تحميل أزواج Binance...") | |
| try: | |
| # --- فحص اتصال Binance قبل البدء --- | |
| print("🛜 فحص الاتصال بـ api.binance.com...") | |
| ping_resp = requests.get("https://api.binance.com/api/v3/ping", timeout=10, proxies=proxies) | |
| if ping_resp.status_code == 200: | |
| print("✅ الاتصال بـ api.binance.com ناجح.") | |
| else: | |
| print(f"⚠️ استجابة غير متوقعة من Binance: {ping_resp.status_code}") | |
| # --- نهاية الفحص --- | |
| resp = requests.get( | |
| "https://api.binance.com/api/v3/exchangeInfo", | |
| timeout=20, | |
| proxies=proxies | |
| ) | |
| data = resp.json() | |
| SYMBOLS_INFO.clear() | |
| for s in data.get("symbols", []): | |
| if s.get("status") == "TRADING": | |
| SYMBOLS_INFO.append((s["symbol"], s["baseAsset"], s["quoteAsset"])) | |
| BOT_STATUS["symbols_count"] = len(SYMBOLS_INFO) | |
| print(f"✅ تم تحميل {len(SYMBOLS_INFO)} زوج نشط.") | |
| if len(SYMBOLS_INFO) == 0: | |
| print("❌ لم يتم تحميل أي زوج! تأكد من أن البروكسي يعمل أو أن Binance لا يحظر IP الخاص بك.") | |
| send_telegram_message("❌ فشل تحميل الأزواج من Binance. تحقق من إعدادات البروكسي.") | |
| else: | |
| send_telegram_message(f"✅ تم تحميل {len(SYMBOLS_INFO)} زوج نشط من Binance.") | |
| return True | |
| except Exception as e: | |
| err_msg = f"❌ خطأ في تحميل الأزواج: {e}" | |
| print(err_msg) | |
| BOT_STATUS["errors"].append(err_msg) | |
| send_telegram_message(f"⚠️ فشل تحميل الأزواج: {e}") | |
| return False | |
| # ---------------------- بناء مثلثات المراجحة ---------------------- | |
| def build_triangles(): | |
| global ALL_TRIANGLES, UNIQUE_SYMBOLS_NEEDED, BOT_STATUS | |
| graph = defaultdict(list) | |
| for sym, base, quote in SYMBOLS_INFO: | |
| graph[base].append((quote, sym)) | |
| graph[quote].append((base, sym)) | |
| ALL_TRIANGLES.clear() | |
| UNIQUE_SYMBOLS_NEEDED.clear() | |
| for first_coin, sym1 in graph[BASE_CURRENCY]: | |
| for second_coin, sym2 in graph[first_coin]: | |
| if second_coin == BASE_CURRENCY: continue | |
| for third_coin, sym3 in graph[second_coin]: | |
| if third_coin == BASE_CURRENCY: | |
| ALL_TRIANGLES.append((sym1, sym2, sym3)) | |
| UNIQUE_SYMBOLS_NEEDED.update([sym1, sym2, sym3]) | |
| BOT_STATUS["triangles_count"] = len(ALL_TRIANGLES) | |
| print(f"✅ تم توليد {len(ALL_TRIANGLES)} مثلث.") | |
| print(f"✅ الأزواج المطلوبة للأسعار: {len(UNIQUE_SYMBOLS_NEEDED)}") | |
| # ---------------------- تحديث الأسعار (أفضل Bid/Ask) ---------------------- | |
| def update_prices(): | |
| global PRICE_CACHE, BOT_STATUS | |
| session = requests.Session() | |
| if proxies: | |
| session.proxies.update(proxies) | |
| new_cache = {} | |
| for symbol in UNIQUE_SYMBOLS_NEEDED: | |
| try: | |
| resp = session.get( | |
| "https://api.binance.com/api/v3/depth", | |
| params={"symbol": symbol, "limit": 1}, | |
| timeout=5 | |
| ) | |
| data = resp.json() | |
| asks = data.get("asks", []) | |
| bids = data.get("bids", []) | |
| if asks and bids: | |
| ask = float(asks[0][0]) | |
| bid = float(bids[0][0]) | |
| if ask >= MIN_PRICE_THRESHOLD and bid >= MIN_PRICE_THRESHOLD: | |
| new_cache[symbol] = (bid, ask) | |
| except Exception: | |
| pass | |
| if len(new_cache) >= max(1, len(UNIQUE_SYMBOLS_NEEDED) * 0.9): | |
| PRICE_CACHE = new_cache | |
| BOT_STATUS["prices_updated"] = True | |
| return True | |
| BOT_STATUS["prices_updated"] = False | |
| return False | |
| # ---------------------- حساب الربح للمثلث ---------------------- | |
| def calculate(sym1, sym2, sym3): | |
| if sym1 not in PRICE_CACHE or sym2 not in PRICE_CACHE or sym3 not in PRICE_CACHE: | |
| return None | |
| bid1, ask1 = PRICE_CACHE[sym1] | |
| bid2, ask2 = PRICE_CACHE[sym2] | |
| bid3, ask3 = PRICE_CACHE[sym3] | |
| fee = 0.001 | |
| try: | |
| amount = (TRADE_AMOUNT / ask1) * (1 - fee) | |
| amount = (amount / ask2) * (1 - fee) | |
| final_amount = amount * bid3 * (1 - fee) | |
| profit = final_amount - TRADE_AMOUNT | |
| percent = (profit / TRADE_AMOUNT) * 100 | |
| if percent > 10.0: | |
| return None | |
| return profit, percent, final_amount | |
| except: | |
| return None | |
| # ---------------------- فحص جميع المثلثات ---------------------- | |
| def scan_and_display(): | |
| global BOT_STATUS | |
| if not PRICE_CACHE: | |
| return 0 | |
| found_count = 0 | |
| opportunities = [] | |
| for sym1, sym2, sym3 in ALL_TRIANGLES: | |
| res = calculate(sym1, sym2, sym3) | |
| if res: | |
| profit, percent, final = res | |
| if percent >= MIN_PROFIT_PERCENT: | |
| print_opportunity(sym1, sym2, sym3, profit, percent, final) | |
| opportunities.append({ | |
| "triangle": f"{sym1}→{sym2}→{sym3}", | |
| "profit": profit, | |
| "percent": percent, | |
| "final": final, | |
| "time": datetime.now().isoformat() | |
| }) | |
| send_opportunity_alert(sym1, sym2, sym3, profit, percent, final) | |
| found_count += 1 | |
| BOT_STATUS["last_opportunities"] = opportunities[:5] | |
| return found_count | |
| def print_opportunity(sym1, sym2, sym3, profit, percent, final): | |
| print("\n" + "="*80) | |
| print(f"✨ فرصة مراجحة مثلثية مكتشفة!") | |
| print(f" المثلث: {sym1} → {sym2} → {sym3}") | |
| print(f" 💰 الربح: {profit:.4f} USDT") | |
| print(f" 📈 النسبة: {percent:.4f}%") | |
| print(f" 💵 المبلغ النهائي: {final:.4f} USDT") | |
| print("="*80) | |
| # ---------------------- الحلقة الرئيسية للبوت ---------------------- | |
| def bot_loop(): | |
| print("🚀 بدء تشغيل بوت المراجحة...") | |
| send_startup_message() | |
| # تحميل الأزواج وبناء المثلثات | |
| if not load_symbols(): | |
| print("❌ تعذر تحميل الأزواج. إعادة المحاولة خلال 30 ثانية...") | |
| time.sleep(30) | |
| if not load_symbols(): | |
| print("❌ فشل تحميل الأزواج بعد المحاولة الثانية. تحقق من الاتصال أو استخدم Proxy.") | |
| send_telegram_message("❌ البوت لم يتمكن من تحميل الأزواج. تحقق من logs.") | |
| build_triangles() | |
| print(f"\n🔍 المبلغ={TRADE_AMOUNT} USDT | الحد الأدنى={MIN_PROFIT_PERCENT}%") | |
| print("⏳ جاري جلب الأسعار وفحص الفرص بشكل مستمر...\n") | |
| while BOT_STATUS["running"]: | |
| start_scan = time.time() | |
| try: | |
| if update_prices(): | |
| count = scan_and_display() | |
| elapsed = time.time() - start_scan | |
| BOT_STATUS["last_scan_time"] = datetime.now().isoformat() | |
| BOT_STATUS["last_scan_duration"] = elapsed | |
| if count == 0: | |
| print(f"🔍 لا توجد فرص ≥{MIN_PROFIT_PERCENT}% (المسح استغرق {elapsed:.2f} ثانية)", end="\r") | |
| else: | |
| print(f"\n✅ تم العثور على {count} فرصة خلال هذه الدورة (استغرقت {elapsed:.2f} ثانية)\n") | |
| else: | |
| print("⚠️ فشل تحديث الأسعار - إعادة المحاولة...") | |
| BOT_STATUS["errors"].append("فشل تحديث الأسعار") | |
| if len(SYMBOLS_INFO) == 0: | |
| load_symbols() | |
| build_triangles() | |
| except Exception as e: | |
| err_msg = f"خطأ في دورة المسح: {e}" | |
| print(f"❌ {err_msg}") | |
| BOT_STATUS["errors"].append(err_msg) | |
| send_telegram_message(f"⚠️ خطأ في البوت: {e}") | |
| time.sleep(2) | |
| # ---------------------- تطبيق Flask للوحة التحكم ---------------------- | |
| app = Flask(__name__) | |
| HTML_TEMPLATE = """ | |
| <!DOCTYPE html> | |
| <html dir="rtl" lang="ar"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>لوحة تحكم بوت المراجحة</title> | |
| <style> | |
| body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #f0f2f6; margin: 20px; } | |
| .container { max-width: 800px; margin: auto; background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); } | |
| h1 { color: #1e3a8a; border-bottom: 2px solid #e2e8f0; padding-bottom: 10px; } | |
| .status-card { background: #f8fafc; padding: 15px; border-radius: 10px; margin: 15px 0; } | |
| .badge { padding: 4px 12px; border-radius: 20px; font-weight: bold; } | |
| .online { background: #10b981; color: white; } | |
| .offline { background: #ef4444; color: white; } | |
| table { width: 100%; border-collapse: collapse; margin: 20px 0; } | |
| th, td { padding: 10px; text-align: right; border-bottom: 1px solid #ddd; } | |
| th { background: #e2e8f0; } | |
| .refresh-btn { background: #3b82f6; color: white; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-size: 16px; } | |
| .refresh-btn:hover { background: #2563eb; } | |
| .error { color: #b91c1c; background: #fee2e2; padding: 10px; border-radius: 8px; margin: 10px 0; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <h1>🤖 بوت المراجحة المثلثية - Binance</h1> | |
| <div class="status-card"> | |
| <span>الحالة: </span> | |
| <span class="badge {{ 'online' if status.running else 'offline' }}"> | |
| {{ 'نشط' if status.running else 'متوقف' }} | |
| </span> | |
| </div> | |
| <h3>📊 إحصائيات</h3> | |
| <table> | |
| <tr><th>آخر مسح</th><td>{{ status.last_scan_time or 'لم يتم بعد' }}</td></tr> | |
| <tr><th>مدة آخر مسح</th><td>{{ "%.2f"|format(status.last_scan_duration) if status.last_scan_duration else '---' }} ثانية</td></tr> | |
| <tr><th>عدد الأزواج المحملة</th><td>{{ status.symbols_count }}</td></tr> | |
| <tr><th>عدد المثلثات المولدة</th><td>{{ status.triangles_count }}</td></tr> | |
| <tr><th>آخر تحديث للأسعار</th><td>{{ 'ناجح' if status.prices_updated else 'فشل' }}</td></tr> | |
| </table> | |
| <h3>✨ آخر الفرص المكتشفة</h3> | |
| {% if status.last_opportunities %} | |
| <table> | |
| <tr><th>المثلث</th><th>الربح (USDT)</th><th>النسبة</th></tr> | |
| {% for opp in status.last_opportunities %} | |
| <tr> | |
| <td>{{ opp.triangle }}</td> | |
| <td>{{ "%.4f"|format(opp.profit) }}</td> | |
| <td>{{ "%.4f"|format(opp.percent) }}%</td> | |
| </tr> | |
| {% endfor %} | |
| </table> | |
| {% else %} | |
| <p>لم تكتشف أي فرصة بعد.</p> | |
| {% endif %} | |
| {% if status.errors %} | |
| <h3>⚠️ أخطاء حديثة</h3> | |
| <div class="error"> | |
| {% for err in status.errors[-3:] %} | |
| <p>{{ err }}</p> | |
| {% endfor %} | |
| </div> | |
| {% endif %} | |
| <button class="refresh-btn" onclick="location.reload();">🔄 تحديث الحالة</button> | |
| <p style="margin-top: 20px; font-size: 12px; color: #64748b;">التحديث تلقائي عند الضغط على الزر.</p> | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| def dashboard(): | |
| return render_template_string(HTML_TEMPLATE, status=BOT_STATUS) | |
| def status_json(): | |
| return jsonify(BOT_STATUS) | |
| def start_flask(): | |
| app.run(host='0.0.0.0', port=7860) | |
| # ---------------------- نقطة البداية ---------------------- | |
| if __name__ == "__main__": | |
| # بدء خيط Flask لعرض لوحة التحكم | |
| flask_thread = threading.Thread(target=start_flask, daemon=True) | |
| flask_thread.start() | |
| # بدء حلقة البوت في الخيط الرئيسي | |
| bot_loop() |