Update data_manager.py
Browse files- data_manager.py +173 -33
data_manager.py
CHANGED
|
@@ -37,7 +37,7 @@ class DataManager:
|
|
| 37 |
async def initialize(self):
|
| 38 |
self.http_client = httpx.AsyncClient(timeout=30.0)
|
| 39 |
await self._load_markets()
|
| 40 |
-
print("✅ DataManager initialized -
|
| 41 |
|
| 42 |
async def _load_markets(self):
|
| 43 |
try:
|
|
@@ -208,16 +208,26 @@ class DataManager:
|
|
| 208 |
|
| 209 |
async def layer1_rapid_screening(self) -> List[Dict[str, Any]]:
|
| 210 |
"""
|
| 211 |
-
الطبقة 1: فحص سريع -
|
| 212 |
"""
|
| 213 |
print("📊 الطبقة 1: جلب أفضل 200 عملة حسب حجم التداول...")
|
| 214 |
|
| 215 |
-
#
|
| 216 |
-
print(" 🔍 جلب
|
| 217 |
-
volume_data = await self.
|
| 218 |
|
| 219 |
if not volume_data:
|
| 220 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
return []
|
| 222 |
|
| 223 |
# أخذ أفضل 200 عملة حسب الحجم فقط
|
|
@@ -242,26 +252,36 @@ class DataManager:
|
|
| 242 |
|
| 243 |
return final_candidates
|
| 244 |
|
| 245 |
-
async def
|
| 246 |
-
"""
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
if not
|
|
|
|
|
|
|
|
|
|
| 260 |
continue
|
| 261 |
|
|
|
|
| 262 |
current_price = ticker.get('last', 0)
|
| 263 |
-
|
| 264 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
# فلترة أولية: تجاهل العملات ذات الحجم المنخفض جداً
|
| 267 |
if dollar_volume < 50000: # أقل من 50K دولار
|
|
@@ -271,18 +291,138 @@ class DataManager:
|
|
| 271 |
'symbol': symbol,
|
| 272 |
'dollar_volume': dollar_volume,
|
| 273 |
'current_price': current_price,
|
| 274 |
-
'volume_24h':
|
|
|
|
| 275 |
})
|
| 276 |
|
| 277 |
processed += 1
|
| 278 |
-
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
async def _apply_advanced_indicators(self, volume_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 288 |
"""تطبيق المؤشرات المتقدمة على أفضل العملات حسب الحجم"""
|
|
@@ -329,7 +469,7 @@ class DataManager:
|
|
| 329 |
high_24h = ticker.get('high', 0)
|
| 330 |
low_24h = ticker.get('low', 0)
|
| 331 |
open_price = ticker.get('open', 0)
|
| 332 |
-
price_change_24h = ticker.get('percentage', 0) or 0
|
| 333 |
|
| 334 |
# حساب المؤشرات المتقدمة
|
| 335 |
volatility = self._calculate_volatility(high_24h, low_24h, current_price)
|
|
@@ -589,4 +729,4 @@ class DataManager:
|
|
| 589 |
print(f"❌ خطأ في التحقق من الرمز {symbol}: {e}")
|
| 590 |
return False
|
| 591 |
|
| 592 |
-
print("✅ DataManager loaded -
|
|
|
|
| 37 |
async def initialize(self):
|
| 38 |
self.http_client = httpx.AsyncClient(timeout=30.0)
|
| 39 |
await self._load_markets()
|
| 40 |
+
print("✅ DataManager initialized - Efficient Volume-Based Screening")
|
| 41 |
|
| 42 |
async def _load_markets(self):
|
| 43 |
try:
|
|
|
|
| 208 |
|
| 209 |
async def layer1_rapid_screening(self) -> List[Dict[str, Any]]:
|
| 210 |
"""
|
| 211 |
+
الطبقة 1: فحص سريع - جلب أفضل 200 عملة حسب الحجم مباشرة
|
| 212 |
"""
|
| 213 |
print("📊 الطبقة 1: جلب أفضل 200 عملة حسب حجم التداول...")
|
| 214 |
|
| 215 |
+
# المحاولة 1: الطريقة المثلى - استخدام fetch_tickers
|
| 216 |
+
print(" 🔍 المحاولة 1: جلب جميع التاكرز مرة واحدة...")
|
| 217 |
+
volume_data = await self._get_volume_data_optimal()
|
| 218 |
|
| 219 |
if not volume_data:
|
| 220 |
+
# المحاولة 2: الطريقة البديلة - استخدام API المباشر
|
| 221 |
+
print(" 🔄 المحاولة 2: استخدام API المباشر...")
|
| 222 |
+
volume_data = await self._get_volume_data_direct_api()
|
| 223 |
+
|
| 224 |
+
if not volume_data:
|
| 225 |
+
# المحاولة 3: الطريقة التقليدية (الاحتياطية)
|
| 226 |
+
print(" ⚠️ المحاولة 3: استخدام الطريقة التقليدية...")
|
| 227 |
+
volume_data = await self._get_volume_data_traditional()
|
| 228 |
+
|
| 229 |
+
if not volume_data:
|
| 230 |
+
print("❌ فشل جميع محاولات جلب بيانات الأحجام")
|
| 231 |
return []
|
| 232 |
|
| 233 |
# أخذ أفضل 200 عملة حسب الحجم فقط
|
|
|
|
| 252 |
|
| 253 |
return final_candidates
|
| 254 |
|
| 255 |
+
async def _get_volume_data_optimal(self) -> List[Dict[str, Any]]:
|
| 256 |
+
"""الطريقة المثلى: استخدام fetch_tickers لجميع البيانات مرة واحدة"""
|
| 257 |
+
try:
|
| 258 |
+
if not self.exchange:
|
| 259 |
+
return []
|
| 260 |
+
|
| 261 |
+
print(" 📊 جلب جميع بيانات التداول مرة واحدة...")
|
| 262 |
+
tickers = self.exchange.fetch_tickers()
|
| 263 |
+
|
| 264 |
+
volume_data = []
|
| 265 |
+
processed = 0
|
| 266 |
+
|
| 267 |
+
for symbol, ticker in tickers.items():
|
| 268 |
+
# تصفية أزواج USDT النشطة فقط
|
| 269 |
+
if not symbol.endswith('/USDT'):
|
| 270 |
+
continue
|
| 271 |
+
|
| 272 |
+
if not ticker.get('active', True):
|
| 273 |
continue
|
| 274 |
|
| 275 |
+
# استخدام quoteVolume (الحجم بالدولار) إذا متوفر
|
| 276 |
current_price = ticker.get('last', 0)
|
| 277 |
+
quote_volume = ticker.get('quoteVolume', 0)
|
| 278 |
+
|
| 279 |
+
if quote_volume > 0:
|
| 280 |
+
dollar_volume = quote_volume
|
| 281 |
+
else:
|
| 282 |
+
# fallback: baseVolume * السعر
|
| 283 |
+
base_volume = ticker.get('baseVolume', 0)
|
| 284 |
+
dollar_volume = base_volume * current_price
|
| 285 |
|
| 286 |
# فلترة أولية: تجاهل العملات ذات الحجم المنخفض جداً
|
| 287 |
if dollar_volume < 50000: # أقل من 50K دولار
|
|
|
|
| 291 |
'symbol': symbol,
|
| 292 |
'dollar_volume': dollar_volume,
|
| 293 |
'current_price': current_price,
|
| 294 |
+
'volume_24h': ticker.get('baseVolume', 0),
|
| 295 |
+
'price_change_24h': (ticker.get('percentage', 0) or 0) * 100
|
| 296 |
})
|
| 297 |
|
| 298 |
processed += 1
|
| 299 |
+
|
| 300 |
+
print(f" ✅ تم معالجة {processed} عملة من أصل {len(tickers)}")
|
| 301 |
+
return volume_data
|
| 302 |
+
|
| 303 |
+
except Exception as e:
|
| 304 |
+
print(f" ❌ فشل الطريقة المثلى: {e}")
|
| 305 |
+
return []
|
| 306 |
+
|
| 307 |
+
async def _get_volume_data_direct_api(self) -> List[Dict[str, Any]]:
|
| 308 |
+
"""الطريقة الثانية: استخدام KuCoin API مباشرة"""
|
| 309 |
+
try:
|
| 310 |
+
print(" 🌐 الاتصال بـ KuCoin API مباشرة...")
|
| 311 |
+
url = "https://api.kucoin.com/api/v1/market/allTickers"
|
| 312 |
+
|
| 313 |
+
async with httpx.AsyncClient(timeout=15) as client:
|
| 314 |
+
response = await client.get(url)
|
| 315 |
+
response.raise_for_status()
|
| 316 |
+
data = response.json()
|
| 317 |
+
|
| 318 |
+
if data.get('code') != '200000':
|
| 319 |
+
raise ValueError(f"استجابة API غير متوقعة: {data.get('code')}")
|
| 320 |
+
|
| 321 |
+
tickers = data['data']['ticker']
|
| 322 |
+
volume_data = []
|
| 323 |
+
|
| 324 |
+
for ticker in tickers:
|
| 325 |
+
symbol = ticker['symbol']
|
| 326 |
|
| 327 |
+
# تصفية أزواج USDT فقط
|
| 328 |
+
if not symbol.endswith('USDT'):
|
| 329 |
+
continue
|
| 330 |
+
|
| 331 |
+
# تحويل الرمز للتنسيق القياسي (BTC-USDT → BTC/USDT)
|
| 332 |
+
formatted_symbol = symbol.replace('-', '/')
|
| 333 |
+
|
| 334 |
+
try:
|
| 335 |
+
dollar_volume = float(ticker['volValue']) # الحجم بالدولار
|
| 336 |
+
current_price = float(ticker['last'])
|
| 337 |
+
price_change = float(ticker['changeRate']) * 100
|
| 338 |
+
|
| 339 |
+
if dollar_volume >= 50000:
|
| 340 |
+
volume_data.append({
|
| 341 |
+
'symbol': formatted_symbol,
|
| 342 |
+
'dollar_volume': dollar_volume,
|
| 343 |
+
'current_price': current_price,
|
| 344 |
+
'volume_24h': float(ticker['vol']),
|
| 345 |
+
'price_change_24h': price_change
|
| 346 |
+
})
|
| 347 |
+
except (ValueError, KeyError) as e:
|
| 348 |
+
continue
|
| 349 |
+
|
| 350 |
+
print(f" ✅ تم جلب {len(volume_data)} عملة من API المباشر")
|
| 351 |
+
return volume_data
|
| 352 |
+
|
| 353 |
+
except Exception as e:
|
| 354 |
+
print(f" ❌ فشل API المباشر: {e}")
|
| 355 |
+
return []
|
| 356 |
+
|
| 357 |
+
async def _get_volume_data_traditional(self) -> List[Dict[str, Any]]:
|
| 358 |
+
"""الطريقة التقليدية: جلب كل رمز على حدة (الاحتياطي)"""
|
| 359 |
+
try:
|
| 360 |
+
if not self.exchange or not self.market_cache:
|
| 361 |
+
return []
|
| 362 |
+
|
| 363 |
+
usdt_symbols = [
|
| 364 |
+
symbol for symbol in self.market_cache.keys()
|
| 365 |
+
if symbol.endswith('/USDT') and self.market_cache[symbol].get('active', False)
|
| 366 |
+
]
|
| 367 |
+
|
| 368 |
+
print(f" 🔄 معالجة {len(usdt_symbols)} عملة (طريقة تقليدية)...")
|
| 369 |
+
|
| 370 |
+
volume_data = []
|
| 371 |
+
processed = 0
|
| 372 |
+
|
| 373 |
+
# معالجة دفعات لتجنب rate limits
|
| 374 |
+
batch_size = 50
|
| 375 |
+
for i in range(0, len(usdt_symbols), batch_size):
|
| 376 |
+
batch = usdt_symbols[i:i + batch_size]
|
| 377 |
+
batch_tasks = [self._process_single_symbol(sym) for sym in batch]
|
| 378 |
+
batch_results = await asyncio.gather(*batch_tasks, return_exceptions=True)
|
| 379 |
+
|
| 380 |
+
for result in batch_results:
|
| 381 |
+
if isinstance(result, dict):
|
| 382 |
+
volume_data.append(result)
|
| 383 |
+
|
| 384 |
+
processed += len(batch)
|
| 385 |
+
print(f" ✅ تم معالجة {processed}/{len(usdt_symbols)} عملة...")
|
| 386 |
+
|
| 387 |
+
# انتظار قصير بين الدفعات
|
| 388 |
+
if i + batch_size < len(usdt_symbols):
|
| 389 |
+
await asyncio.sleep(1)
|
| 390 |
+
|
| 391 |
+
print(f" ✅ تم جمع بيانات {len(volume_data)} عملة مؤهلة")
|
| 392 |
+
return volume_data
|
| 393 |
+
|
| 394 |
+
except Exception as e:
|
| 395 |
+
print(f" ❌ فشل الطريقة التقليدية: {e}")
|
| 396 |
+
return []
|
| 397 |
+
|
| 398 |
+
async def _process_single_symbol(self, symbol: str) -> Dict[str, Any]:
|
| 399 |
+
"""معالجة رمز واحد لجلب بيانات الحجم"""
|
| 400 |
+
try:
|
| 401 |
+
ticker = self.exchange.fetch_ticker(symbol)
|
| 402 |
+
if not ticker:
|
| 403 |
+
return None
|
| 404 |
+
|
| 405 |
+
current_price = ticker.get('last', 0)
|
| 406 |
+
quote_volume = ticker.get('quoteVolume', 0)
|
| 407 |
+
|
| 408 |
+
if quote_volume > 0:
|
| 409 |
+
dollar_volume = quote_volume
|
| 410 |
+
else:
|
| 411 |
+
base_volume = ticker.get('baseVolume', 0)
|
| 412 |
+
dollar_volume = base_volume * current_price
|
| 413 |
+
|
| 414 |
+
if dollar_volume < 50000:
|
| 415 |
+
return None
|
| 416 |
+
|
| 417 |
+
return {
|
| 418 |
+
'symbol': symbol,
|
| 419 |
+
'dollar_volume': dollar_volume,
|
| 420 |
+
'current_price': current_price,
|
| 421 |
+
'volume_24h': ticker.get('baseVolume', 0),
|
| 422 |
+
'price_change_24h': (ticker.get('percentage', 0) or 0) * 100
|
| 423 |
+
}
|
| 424 |
+
except Exception:
|
| 425 |
+
return None
|
| 426 |
|
| 427 |
async def _apply_advanced_indicators(self, volume_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 428 |
"""تطبيق المؤشرات المتقدمة على أفضل العملات حسب الحجم"""
|
|
|
|
| 469 |
high_24h = ticker.get('high', 0)
|
| 470 |
low_24h = ticker.get('low', 0)
|
| 471 |
open_price = ticker.get('open', 0)
|
| 472 |
+
price_change_24h = (ticker.get('percentage', 0) or 0) * 100
|
| 473 |
|
| 474 |
# حساب المؤشرات المتقدمة
|
| 475 |
volatility = self._calculate_volatility(high_24h, low_24h, current_price)
|
|
|
|
| 729 |
print(f"❌ خطأ في التحقق من الرمز {symbol}: {e}")
|
| 730 |
return False
|
| 731 |
|
| 732 |
+
print("✅ DataManager loaded - Multi-Method Volume Screening System")
|