Spaces:
Running
Running
File size: 23,633 Bytes
bdf5ede 00bb5c9 af73eb9 d69dead 28fa18b 24a0949 53cf6c0 28fa18b 53cf6c0 d2775f3 53cf6c0 d2775f3 c6f72fe 7f28923 af73eb9 248e033 7f28923 c6f72fe 56e3f87 af73eb9 248e033 c6f72fe af73eb9 c6f72fe dceb75a c6f72fe 87e3669 56e3f87 7f28923 d69dead 53cf6c0 248e033 56e3f87 af73eb9 24a0949 56e3f87 dceb75a af73eb9 56e3f87 dceb75a 56e3f87 dceb75a 56e3f87 53cf6c0 ea38153 af73eb9 53cf6c0 24a0949 d69dead 248e033 24a0949 d69dead 24a0949 56e3f87 d69dead 24a0949 d69dead 24a0949 d69dead 248e033 24a0949 d69dead 56e3f87 24a0949 87e3669 24a0949 87e3669 24a0949 87e3669 24a0949 248e033 24a0949 ed04390 248e033 24a0949 248e033 7f28923 248e033 24a0949 ed04390 24a0949 ed04390 ea38153 24a0949 ea38153 c6f72fe ea38153 248e033 ea38153 dceb75a ea38153 c6f72fe ea38153 c6f72fe af73eb9 248e033 ea38153 af73eb9 248e033 ea38153 c6f72fe ea38153 24a0949 ea38153 24a0949 ea38153 248e033 ea38153 248e033 ea38153 56e3f87 ea38153 dceb75a ea38153 87e3669 24a0949 87e3669 ea38153 87e3669 24a0949 53cf6c0 24a0949 af73eb9 24a0949 af73eb9 24a0949 af73eb9 24a0949 af73eb9 53cf6c0 af73eb9 53cf6c0 af73eb9 afa0eeb af73eb9 53cf6c0 af73eb9 c6f72fe af73eb9 24a0949 af73eb9 c6f72fe af73eb9 24a0949 af73eb9 24a0949 af73eb9 24a0949 af73eb9 248e033 af73eb9 248e033 af73eb9 248e033 af73eb9 248e033 af73eb9 248e033 af73eb9 6598c39 af73eb9 248e033 24a0949 af73eb9 24a0949 af73eb9 24a0949 5663c09 af73eb9 5663c09 24a0949 af73eb9 24a0949 af73eb9 248e033 af73eb9 248e033 af73eb9 248e033 af73eb9 248e033 af73eb9 248e033 af73eb9 24a0949 af73eb9 24a0949 6598c39 af73eb9 7f28923 248e033 af73eb9 7f28923 af73eb9 7f28923 248e033 7f28923 af73eb9 248e033 af73eb9 7f28923 af73eb9 7f28923 248e033 af73eb9 7f28923 248e033 af73eb9 afa0eeb af73eb9 afa0eeb af73eb9 afa0eeb 7f28923 248e033 af73eb9 7f28923 6598c39 24a0949 6598c39 116ef05 56e3f87 af73eb9 116ef05 afa0eeb 116ef05 6598c39 248e033 56e3f87 24a0949 56e3f87 24a0949 56e3f87 24a0949 56e3f87 24a0949 56e3f87 af73eb9 |
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 |
# data_manager.py
import os
import asyncio
import httpx
import traceback
import time
from datetime import datetime
import ccxt # استخدام ccxt العادي بدلاً من pro
import numpy as np
import logging
from typing import List, Dict, Any
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
class DataManager:
def __init__(self, contracts_db, whale_monitor):
self.contracts_db = contracts_db or {}
self.whale_monitor = whale_monitor
# إعدادات الأداء المحسنة
self.batch_size = 25 # حجم دفعة معقول
self.cache_duration = 300
try:
self.exchange = ccxt.kucoin({
'sandbox': False,
'enableRateLimit': True,
'timeout': 30000,
'verbose': False,
})
print("✅ تم تهيئة اتصال KuCoin بنجاح (CCXT Standard)")
except Exception as e:
print(f"❌ فشل تهيئة اتصال KuCoin: {e}")
self.exchange = None
self.http_client = None
self.market_cache = {}
self.last_market_load = None
self.symbol_cache = {}
self.cache_timestamp = {}
async def initialize(self):
self.http_client = httpx.AsyncClient(timeout=30.0)
await self._load_markets()
print("✅ DataManager initialized - Focused on Top 200 Symbols")
async def _load_markets(self):
try:
if not self.exchange:
return
print("🔄 جلب أحدث بيانات الأسواق من KuCoin...")
self.exchange.load_markets() # sync call instead of await
self.market_cache = self.exchange.markets
self.last_market_load = datetime.now()
print(f"✅ تم تحميل {len(self.market_cache)} سوق من KuCoin")
except Exception as e:
print(f"❌ فشل تحميل بيانات الأسواق: {e}")
async def close(self):
if self.http_client:
await self.http_client.aclose()
# لا داعي لـ close في ccxt العادي
async def get_market_context_async(self):
"""جلب سياق السوق الأساسي فقط"""
try:
sentiment_data = await self.get_sentiment_safe_async()
price_data = await self._get_prices_with_fallback()
bitcoin_price = price_data.get('bitcoin')
ethereum_price = price_data.get('ethereum')
market_context = {
'timestamp': datetime.now().isoformat(),
'bitcoin_price_usd': bitcoin_price,
'ethereum_price_usd': ethereum_price,
'fear_and_greed_index': sentiment_data.get('feargreed_value') if sentiment_data else None,
'sentiment_class': sentiment_data.get('feargreed_class') if sentiment_data else 'NEUTRAL',
'market_trend': self._determine_market_trend(bitcoin_price, sentiment_data),
'btc_sentiment': self._get_btc_sentiment(bitcoin_price),
'data_quality': 'HIGH' if bitcoin_price and ethereum_price else 'LOW'
}
return market_context
except Exception as e:
print(f"❌ فشل جلب سياق السوق: {e}")
return self._get_minimal_market_context()
async def get_sentiment_safe_async(self):
"""جلب بيانات المشاعر"""
try:
async with httpx.AsyncClient(timeout=10) as client:
response = await client.get("https://api.alternative.me/fng/")
response.raise_for_status()
data = response.json()
if 'data' not in data or not data['data']:
raise ValueError("بيانات المشاعر غير متوفرة")
latest_data = data['data'][0]
return {
"feargreed_value": int(latest_data['value']),
"feargreed_class": latest_data['value_classification'],
"source": "alternative.me",
"timestamp": datetime.now().isoformat()
}
except Exception as e:
print(f"❌ فشل جلب بيانات المشاعر: {e}")
return None
def _determine_market_trend(self, bitcoin_price, sentiment_data):
"""تحديد اتجاه السوق"""
if bitcoin_price is None:
return "UNKNOWN"
score = 0
if bitcoin_price > 60000:
score += 1
elif bitcoin_price < 55000:
score -= 1
if sentiment_data and sentiment_data.get('feargreed_value') is not None:
fear_greed = sentiment_data.get('feargreed_value')
if fear_greed > 60:
score += 1
elif fear_greed < 40:
score -= 1
if score >= 1:
return "bull_market"
elif score <= -1:
return "bear_market"
else:
return "sideways_market"
def _get_btc_sentiment(self, bitcoin_price):
if bitcoin_price is None:
return 'UNKNOWN'
elif bitcoin_price > 60000:
return 'BULLISH'
elif bitcoin_price < 55000:
return 'BEARISH'
else:
return 'NEUTRAL'
async def _get_prices_with_fallback(self):
"""جلب أسعار البيتكوين والإيثيريوم"""
try:
prices = await self._get_prices_from_kucoin_safe()
if prices.get('bitcoin') and prices.get('ethereum'):
return prices
return await self._get_prices_from_coingecko()
except Exception as e:
print(f"❌ فشل جلب الأسعار: {e}")
return {'bitcoin': None, 'ethereum': None}
async def _get_prices_from_kucoin_safe(self):
if not self.exchange:
return {'bitcoin': None, 'ethereum': None}
try:
prices = {'bitcoin': None, 'ethereum': None}
btc_ticker = self.exchange.fetch_ticker('BTC/USDT') # sync call
btc_price = float(btc_ticker.get('last', 0)) if btc_ticker.get('last') else None
if btc_price and btc_price > 0:
prices['bitcoin'] = btc_price
eth_ticker = self.exchange.fetch_ticker('ETH/USDT') # sync call
eth_price = float(eth_ticker.get('last', 0)) if eth_ticker.get('last') else None
if eth_price and eth_price > 0:
prices['ethereum'] = eth_price
return prices
except Exception as e:
print(f"❌ خطأ في جلب الأسعار من KuCoin: {e}")
return {'bitcoin': None, 'ethereum': None}
async def _get_prices_from_coingecko(self):
"""الاحتياطي: جلب الأسعار من CoinGecko"""
try:
await asyncio.sleep(0.5)
url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd"
async with httpx.AsyncClient() as client:
response = await client.get(url, timeout=10)
response.raise_for_status()
data = response.json()
btc_price = data.get('bitcoin', {}).get('usd')
eth_price = data.get('ethereum', {}).get('usd')
if btc_price and eth_price:
return {'bitcoin': btc_price, 'ethereum': eth_price}
else:
return {'bitcoin': None, 'ethereum': None}
except Exception as e:
print(f"❌ فشل جلب الأسعار من CoinGecko: {e}")
return {'bitcoin': None, 'ethereum': None}
def _get_minimal_market_context(self):
"""سياق سوق بدائي عند الفشل"""
return {
'timestamp': datetime.now().isoformat(),
'data_available': False,
'market_trend': 'UNKNOWN',
'btc_sentiment': 'UNKNOWN',
'data_quality': 'LOW'
}
async def layer1_rapid_screening(self) -> List[Dict[str, Any]]:
"""
الطبقة 1: فحص سريع لأفضل 200 عملة بناءً على مؤشرات هامة
"""
print("📊 الطبقة 1: فحص سريع لأفضل العملات بناءً على مؤشرات هامة...")
# الحصول على جميع الرموز النشطة
usdt_symbols = [
symbol for symbol in self.market_cache.keys()
if symbol.endswith('/USDT') and self.market_cache[symbol].get('active', False)
]
print(f"🔍 تحليل {len(usdt_symbols)} عملة متاحة...")
# جلب بيانات التداول لجميع الرموز وتقييمها
all_symbols_data = []
for i, symbol in enumerate(usdt_symbols):
try:
symbol_data = await self._get_symbol_trading_data(symbol)
if symbol_data:
all_symbols_data.append(symbol_data)
if i % 50 == 0:
print(f" 📈 معالجة {i}/{len(usdt_symbols)} عملة...")
await asyncio.sleep(0.05) # وقت انتظار قصير جداً
except Exception as e:
continue
print(f"✅ تم جمع بيانات {len(all_symbols_data)} عملة")
if not all_symbols_data:
return []
# تصنيف العملات بناءً على مؤشرات هامة
scored_symbols = []
for symbol_data in all_symbols_data:
try:
score = self._calculate_comprehensive_score(symbol_data)
if score > 0: # قبول العملات ذات الدرجة الإيجابية فقط
symbol_data['layer1_score'] = score
scored_symbols.append(symbol_data)
except Exception as e:
continue
# ترتيب العملات حسب الدرجة (من الأعلى للأدنى)
scored_symbols.sort(key=lambda x: x.get('layer1_score', 0), reverse=True)
# أخذ أفضل 200 عملة فقط
top_200 = scored_symbols[:200]
print(f"🎯 تم اختيار أفضل {len(top_200)} عملة للطبقة 2")
# عرض أفضل 15 عملة
print("🏆 أفضل 15 عملة من الطبقة 1:")
for i, symbol_data in enumerate(top_200[:15]):
score = symbol_data.get('layer1_score', 0)
volume = symbol_data.get('dollar_volume', 0)
change = symbol_data.get('price_change_24h', 0)
volatility = symbol_data.get('volatility_score', 0)
print(f" {i+1:2d}. {symbol_data['symbol']}: {score:.3f} | ${volume:>8,.0f} | {change:>+6.1f}% | تقلب: {volatility:.3f}")
return top_200
async def _get_symbol_trading_data(self, symbol: str) -> Dict[str, Any]:
"""جلب بيانات التداول لرمز واحد"""
try:
ticker = self.exchange.fetch_ticker(symbol)
if not ticker:
return None
current_price = ticker.get('last', 0)
volume_24h = ticker.get('baseVolume', 0)
dollar_volume = volume_24h * current_price
price_change_24h = ticker.get('percentage', 0) or 0
high_24h = ticker.get('high', 0)
low_24h = ticker.get('low', 0)
open_price = ticker.get('open', 0)
# حساب مؤشرات إضافية هامة
volatility = self._calculate_volatility_score(high_24h, low_24h, current_price)
volume_trend = self._calculate_volume_trend(dollar_volume)
price_strength = self._calculate_price_strength(current_price, open_price, price_change_24h)
return {
'symbol': symbol,
'current_price': current_price,
'volume_24h': volume_24h,
'dollar_volume': dollar_volume,
'price_change_24h': price_change_24h,
'high_24h': high_24h,
'low_24h': low_24h,
'open_price': open_price,
'volatility_score': volatility,
'volume_trend': volume_trend,
'price_strength': price_strength,
'reasons': []
}
except Exception as e:
return None
def _calculate_comprehensive_score(self, symbol_data: Dict[str, Any]) -> float:
"""حساب درجة شاملة تعتمد على مؤشرات هامة للربحية"""
dollar_volume = symbol_data.get('dollar_volume', 0)
price_change = symbol_data.get('price_change_24h', 0)
volatility = symbol_data.get('volatility_score', 0)
volume_trend = symbol_data.get('volume_trend', 0)
price_strength = symbol_data.get('price_strength', 0)
# 1. السيولة والحجم (35%) - الأهم لتجنب العملات الميتة
if dollar_volume < 100000: # أقل من 100K دولار - رفض
return 0
volume_score = 0
if dollar_volume >= 10000000: # 10M+
volume_score = 1.0
elif dollar_volume >= 5000000: # 5M+
volume_score = 0.9
elif dollar_volume >= 2000000: # 2M+
volume_score = 0.8
elif dollar_volume >= 1000000: # 1M+
volume_score = 0.7
elif dollar_volume >= 500000: # 500K+
volume_score = 0.6
elif dollar_volume >= 250000: # 250K+
volume_score = 0.5
elif dollar_volume >= 100000: # 100K+
volume_score = 0.4
# 2. الزخم السعري (25%) - البحث عن حركة قوية
momentum_score = 0
if price_change >= 20: # +20%+ - قوي جداً
momentum_score = 1.0
elif price_change >= 15: # +15%+
momentum_score = 0.9
elif price_change >= 10: # +10%+
momentum_score = 0.8
elif price_change >= 5: # +5%+
momentum_score = 0.7
elif price_change >= 2: # +2%+
momentum_score = 0.6
elif price_change >= 0: # موجب
momentum_score = 0.5
elif price_change >= -5: # حتى -5% (فرصة شراء)
momentum_score = 0.4
elif price_change >= -10: # حتى -10%
momentum_score = 0.3
else: # أكثر من -10% - تجنب
momentum_score = 0.1
# 3. التقلب المناسب (20%) - ليس عالي جداً ولا منخفض جداً
volatility_score = 0
if 0.02 <= volatility <= 0.15: # تقلب مثالي 2%-15%
volatility_score = 1.0
elif 0.01 <= volatility <= 0.20: # مقبول 1%-20%
volatility_score = 0.8
elif volatility <= 0.01: # قليل جداً
volatility_score = 0.3
elif volatility > 0.20: # عالي جداً
volatility_score = 0.2
# 4. قوة السعر (20%) - مزيج من الاتجاه والقوة
strength_score = price_strength
# الدرجة النهائية
final_score = (
volume_score * 0.35 +
momentum_score * 0.25 +
volatility_score * 0.20 +
strength_score * 0.20
)
# تحديث أسباب الترشيح
reasons = []
if volume_score >= 0.7:
reasons.append('high_liquidity')
if momentum_score >= 0.7:
reasons.append('strong_momentum')
if volatility_score >= 0.8:
reasons.append('optimal_volatility')
if strength_score >= 0.7:
reasons.append('price_strength')
symbol_data['reasons'] = reasons
return final_score
def _calculate_volatility_score(self, high_24h: float, low_24h: float, current_price: float) -> float:
"""حساب درجة التقلب"""
if current_price == 0:
return 0
return (high_24h - low_24h) / current_price
def _calculate_volume_trend(self, dollar_volume: float) -> float:
"""حساب اتجاه الحجم"""
if dollar_volume >= 10000000:
return 1.0
elif dollar_volume >= 5000000:
return 0.8
elif dollar_volume >= 1000000:
return 0.6
elif dollar_volume >= 500000:
return 0.4
elif dollar_volume >= 100000:
return 0.2
else:
return 0.1
def _calculate_price_strength(self, current_price: float, open_price: float, price_change: float) -> float:
"""حساب قوة السعر"""
if open_price == 0:
return 0.5
# قوة السعر تعتمد على المسافة من سعر الافتتاح ونسبة التغير
distance_from_open = abs(current_price - open_price) / open_price
change_strength = min(abs(price_change) / 50, 1.0) # تطبيع قوة التغير
return (distance_from_open * 0.6 + change_strength * 0.4)
async def get_ohlcv_data_for_symbols(self, symbols: List[str]) -> List[Dict[str, Any]]:
"""
جلب بيانات OHLCV كاملة للرموز المحددة مع جميع الإطارات الزمنية الـ6
"""
results = []
print(f"📊 جلب بيانات OHLCV كاملة لـ {len(symbols)} عملة...")
print(" 📈 الإطارات الزمنية: 5m, 15m, 1h, 4h, 1d, 1w")
for i, symbol in enumerate(symbols):
try:
ohlcv_data = await self._fetch_complete_ohlcv(symbol)
if ohlcv_data:
results.append(ohlcv_data)
print(f" ✅ ({i+1}/{len(symbols)}) تم جلب بيانات {symbol}")
else:
print(f" ❌ ({i+1}/{len(symbols)}) فشل جلب بيانات {symbol}")
# وقت انتظار لتجنب rate limits
await asyncio.sleep(0.3)
except Exception as symbol_error:
print(f" ❌ ({i+1}/{len(symbols)}) خطأ في {symbol}: {symbol_error}")
continue
print(f"✅ تم تجميع بيانات OHLCV كاملة لـ {len(results)} عملة")
return results
async def _fetch_complete_ohlcv(self, symbol: str) -> Dict[str, Any]:
"""جلب بيانات OHLCV كاملة مع جميع الإطارات الزمنية الـ6"""
try:
ohlcv_data = {}
# جميع الإطارات الزمنية الـ6 المطلوبة
timeframes = [
('5m', 100), # 5 دقائق - 100 شمعة
('15m', 100), # 15 دقيقة - 100 شمعة
('1h', 100), # 1 ساعة - 100 شمعة
('4h', 100), # 4 ساعات - 100 شمعة
('1d', 100), # 1 يوم - 100 شمعة
('1w', 50), # 1 أسبوع - 50 شمعة
]
has_sufficient_data = True
for timeframe, limit in timeframes:
try:
# استخدام fetch_ohlcv العادي (ليس pro)
ohlcv = self.exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
if ohlcv and len(ohlcv) >= 20: # تأكد من وجود بيانات كافية
ohlcv_data[timeframe] = ohlcv
else:
print(f" ⚠️ بيانات غير كافية لـ {symbol} على {timeframe}")
has_sufficient_data = False
break
except Exception as e:
print(f" ⚠️ خطأ في {symbol} على {timeframe}: {e}")
has_sufficient_data = False
break
if has_sufficient_data and ohlcv_data:
# جلب السعر الحالي
try:
ticker = self.exchange.fetch_ticker(symbol)
current_price = ticker.get('last', 0) if ticker else 0
return {
'symbol': symbol,
'ohlcv': ohlcv_data,
'current_price': current_price,
'timestamp': datetime.now().isoformat()
}
except Exception as price_error:
print(f" ⚠️ خطأ في جلب السعر لـ {symbol}: {price_error}")
return None
else:
return None
except Exception as e:
print(f" ❌ خطأ عام في {symbol}: {e}")
return None
async def get_latest_price_async(self, symbol):
"""جلب السعر الحالي لعملة محددة"""
try:
if not self.exchange:
return None
ticker = self.exchange.fetch_ticker(symbol)
current_price = ticker.get('last')
if current_price:
return float(current_price)
else:
return None
except Exception as e:
print(f"❌ خطأ في جلب السعر لـ {symbol}: {e}")
return None
async def get_available_symbols(self):
"""الحصول على جميع الرموز المتاحة"""
try:
if not self.exchange:
return []
if not self.market_cache:
await self._load_markets()
usdt_symbols = [
symbol for symbol in self.market_cache.keys()
if symbol.endswith('/USDT') and self.market_cache[symbol].get('active', False)
]
return usdt_symbols
except Exception as e:
print(f"❌ خطأ في جلب الرموز المتاحة: {e}")
return []
async def validate_symbol(self, symbol):
"""التحقق من صحة الرمز"""
try:
if not self.exchange:
return False
if not self.market_cache:
await self._load_markets()
return symbol in self.market_cache and self.market_cache[symbol].get('active', False)
except Exception as e:
print(f"❌ خطأ في التحقق من الرمز {symbol}: {e}")
return False
print("✅ DataManager loaded - CCXT Standard with Top 200 Symbols & Full OHLCV Timeframes") |