Riy777 commited on
Commit
2ecc875
·
verified ·
1 Parent(s): 504d398

Update data_manager.py

Browse files
Files changed (1) hide show
  1. data_manager.py +66 -6
data_manager.py CHANGED
@@ -8,7 +8,7 @@ import ccxt.pro as ccxt
8
  import numpy as np
9
  import logging
10
 
11
- # تعطيل تسجيل HTTP المزعج
12
  logging.getLogger("httpx").setLevel(logging.WARNING)
13
  logging.getLogger("httpcore").setLevel(logging.WARNING)
14
 
@@ -22,10 +22,12 @@ class DataManager:
22
  'sandbox': False,
23
  'enableRateLimit': True,
24
  'timeout': 30000,
25
- 'verbose': False # تعطيل التسجيل التفصيلي
26
  })
27
  self.exchange.rateLimit = 800
 
28
  except Exception as e:
 
29
  self.exchange = None
30
 
31
  self._whale_data_cache = {}
@@ -50,6 +52,9 @@ class DataManager:
50
  'INFURA_KEY': "🟢 متوفر" if os.getenv('INFURA_KEY') else "🔴 غير متوفر"
51
  }
52
 
 
 
 
53
  await self._load_markets()
54
 
55
  async def _load_markets(self):
@@ -57,12 +62,14 @@ class DataManager:
57
  if not self.exchange:
58
  return
59
 
 
60
  await self.exchange.load_markets()
61
  self.market_cache = self.exchange.markets
62
  self.last_market_load = datetime.now()
 
63
 
64
  except Exception as e:
65
- pass
66
 
67
  async def close(self):
68
  if self.http_client:
@@ -101,6 +108,7 @@ class DataManager:
101
  return None
102
 
103
  except Exception as e:
 
104
  return None
105
 
106
  async def _get_price_from_kucoin(self, symbol):
@@ -111,6 +119,7 @@ class DataManager:
111
  trading_symbol = f"{symbol}/USDT"
112
 
113
  if trading_symbol not in self.market_cache:
 
114
  return None
115
 
116
  ticker = await self.exchange.fetch_ticker(trading_symbol)
@@ -118,9 +127,11 @@ class DataManager:
118
  if price and price > 0:
119
  return float(price)
120
  else:
 
121
  return None
122
 
123
  except Exception as e:
 
124
  return None
125
 
126
  async def _get_price_from_coingecko_fallback(self, network):
@@ -144,11 +155,14 @@ class DataManager:
144
 
145
  price = data.get(coin_id, {}).get('usd')
146
  if price and price > 0:
 
147
  return price
148
  else:
 
149
  return None
150
 
151
  except Exception as e:
 
152
  return None
153
 
154
  async def get_sentiment_safe_async(self):
@@ -171,6 +185,7 @@ class DataManager:
171
  "timestamp": datetime.now().isoformat()
172
  }
173
  except Exception as e:
 
174
  if attempt < max_retries - 1:
175
  await asyncio.sleep(1)
176
 
@@ -234,6 +249,7 @@ class DataManager:
234
  return market_context
235
 
236
  except Exception as e:
 
237
  if attempt < max_retries - 1:
238
  await asyncio.sleep(3)
239
 
@@ -358,6 +374,7 @@ class DataManager:
358
  return {'bitcoin': None, 'ethereum': None}
359
 
360
  except Exception as e:
 
361
  return {'bitcoin': None, 'ethereum': None}
362
 
363
  async def _get_prices_from_kucoin_safe(self):
@@ -373,8 +390,11 @@ class DataManager:
373
  if btc_price and btc_price > 0:
374
  prices['bitcoin'] = btc_price
375
  self.price_cache['bitcoin'] = btc_price
 
 
 
376
  except Exception as e:
377
- pass
378
 
379
  try:
380
  eth_ticker = await self.exchange.fetch_ticker('ETH/USDT')
@@ -382,12 +402,16 @@ class DataManager:
382
  if eth_price and eth_price > 0:
383
  prices['ethereum'] = eth_price
384
  self.price_cache['ethereum'] = eth_price
 
 
 
385
  except Exception as e:
386
- pass
387
 
388
  return prices
389
 
390
  except Exception as e:
 
391
  return {'bitcoin': None, 'ethereum': None}
392
 
393
  async def _get_prices_from_coingecko(self):
@@ -405,11 +429,15 @@ class DataManager:
405
  if btc_price and eth_price:
406
  self.price_cache['bitcoin'] = btc_price
407
  self.price_cache['ethereum'] = eth_price
 
 
408
  return {'bitcoin': btc_price, 'ethereum': eth_price}
409
  else:
 
410
  return {'bitcoin': None, 'ethereum': None}
411
 
412
  except Exception as e:
 
413
  return {'bitcoin': None, 'ethereum': None}
414
 
415
  def _get_minimal_market_context(self):
@@ -560,11 +588,15 @@ class DataManager:
560
  return final_score
561
 
562
  except Exception as e:
 
563
  return 0.0
564
 
565
  async def find_high_potential_candidates(self, count=20):
566
  try:
 
 
567
  if not self.exchange:
 
568
  return []
569
 
570
  if not self.market_cache or not self.last_market_load or (datetime.now() - self.last_market_load).total_seconds() > 3600:
@@ -575,12 +607,16 @@ class DataManager:
575
  if symbol.endswith('/USDT') and self.market_cache[symbol].get('active', False)
576
  ]
577
 
 
 
578
  candidates_with_scores = []
579
  analyzed_count = 0
580
 
581
  for symbol in usdt_symbols[:100]:
582
  try:
583
  analyzed_count += 1
 
 
584
 
585
  ohlcv_1h = await self.exchange.fetch_ohlcv(symbol, '1h', limit=50)
586
 
@@ -612,18 +648,27 @@ class DataManager:
612
  })
613
 
614
  except Exception as e:
 
 
615
  continue
616
 
617
  candidates_with_scores.sort(key=lambda x: x['technical_score'], reverse=True)
618
  top_candidates = candidates_with_scores[:count]
619
 
 
 
 
 
 
620
  return top_candidates
621
 
622
  except Exception as e:
 
623
  return []
624
 
625
  async def get_fast_pass_data_async(self, candidates):
626
  try:
 
627
  results = []
628
 
629
  timeframes = [
@@ -647,14 +692,17 @@ class DataManager:
647
  ohlcv = await self.exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
648
 
649
  if not ohlcv or len(ohlcv) < 50:
 
650
  has_sufficient_data = False
651
  break
652
 
653
  ohlcv_data[timeframe] = ohlcv
 
654
 
655
- await asyncio.sleep(0.05)
656
 
657
  except Exception as e:
 
658
  has_sufficient_data = False
659
  break
660
 
@@ -667,21 +715,29 @@ class DataManager:
667
  }
668
 
669
  results.append(result_data)
 
 
 
670
 
671
  except Exception as symbol_error:
 
672
  continue
673
 
 
674
  return results
675
 
676
  except Exception as e:
 
677
  return []
678
 
679
  async def get_latest_price_async(self, symbol):
680
  try:
681
  if not self.exchange:
 
682
  return None
683
 
684
  if symbol not in self.market_cache:
 
685
  return None
686
 
687
  ticker = await self.exchange.fetch_ticker(symbol)
@@ -690,9 +746,11 @@ class DataManager:
690
  if current_price:
691
  return float(current_price)
692
  else:
 
693
  return None
694
 
695
  except Exception as e:
 
696
  return None
697
 
698
  async def get_available_symbols(self):
@@ -711,6 +769,7 @@ class DataManager:
711
  return usdt_symbols
712
 
713
  except Exception as e:
 
714
  return []
715
 
716
  async def validate_symbol(self, symbol):
@@ -724,6 +783,7 @@ class DataManager:
724
  return symbol in self.market_cache and self.market_cache[symbol].get('active', False)
725
 
726
  except Exception as e:
 
727
  return False
728
 
729
  print("✅ DataManager loaded - Real-time market data from KuCoin ready")
 
8
  import numpy as np
9
  import logging
10
 
11
+ # تعطيل تسجيل HTTP المزعج فقط
12
  logging.getLogger("httpx").setLevel(logging.WARNING)
13
  logging.getLogger("httpcore").setLevel(logging.WARNING)
14
 
 
22
  'sandbox': False,
23
  'enableRateLimit': True,
24
  'timeout': 30000,
25
+ 'verbose': False
26
  })
27
  self.exchange.rateLimit = 800
28
+ print("✅ تم تهيئة اتصال KuCoin بنجاح")
29
  except Exception as e:
30
+ print(f"❌ فشل تهيئة اتصال KuCoin: {e}")
31
  self.exchange = None
32
 
33
  self._whale_data_cache = {}
 
52
  'INFURA_KEY': "🟢 متوفر" if os.getenv('INFURA_KEY') else "🔴 غير متوفر"
53
  }
54
 
55
+ for key, status in api_status.items():
56
+ print(f" {key}: {status}")
57
+
58
  await self._load_markets()
59
 
60
  async def _load_markets(self):
 
62
  if not self.exchange:
63
  return
64
 
65
+ print("🔄 جلب أحدث بيانات الأسواق من KuCoin...")
66
  await self.exchange.load_markets()
67
  self.market_cache = self.exchange.markets
68
  self.last_market_load = datetime.now()
69
+ print(f"✅ تم تحميل {len(self.market_cache)} سوق من KuCoin")
70
 
71
  except Exception as e:
72
+ print(f"❌ فشل تحميل بيانات الأسواق: {e}")
73
 
74
  async def close(self):
75
  if self.http_client:
 
108
  return None
109
 
110
  except Exception as e:
111
+ print(f"❌ فشل جلب سعر {network}: {e}")
112
  return None
113
 
114
  async def _get_price_from_kucoin(self, symbol):
 
119
  trading_symbol = f"{symbol}/USDT"
120
 
121
  if trading_symbol not in self.market_cache:
122
+ print(f"⚠️ السوق {trading_symbol} غير متوفر في KuCoin")
123
  return None
124
 
125
  ticker = await self.exchange.fetch_ticker(trading_symbol)
 
127
  if price and price > 0:
128
  return float(price)
129
  else:
130
+ print(f"⚠️ لم يتم العثور على سعر صالح لـ {symbol}")
131
  return None
132
 
133
  except Exception as e:
134
+ print(f"❌ فشل جلب سعر {symbol} من KuCoin: {e}")
135
  return None
136
 
137
  async def _get_price_from_coingecko_fallback(self, network):
 
155
 
156
  price = data.get(coin_id, {}).get('usd')
157
  if price and price > 0:
158
+ print(f"✅ سعر {network.upper()} (CoinGecko): ${price:,.2f}")
159
  return price
160
  else:
161
+ print(f"⚠️ لم يتم العثور على سعر {network} في CoinGecko")
162
  return None
163
 
164
  except Exception as e:
165
+ print(f"❌ فشل جلب سعر {network} من CoinGecko: {e}")
166
  return None
167
 
168
  async def get_sentiment_safe_async(self):
 
185
  "timestamp": datetime.now().isoformat()
186
  }
187
  except Exception as e:
188
+ print(f"❌ فشل جلب بيانات المشاعر (المحاولة {attempt + 1}): {e}")
189
  if attempt < max_retries - 1:
190
  await asyncio.sleep(1)
191
 
 
249
  return market_context
250
 
251
  except Exception as e:
252
+ print(f"❌ فشل جلب سياق السوق (المحاولة {attempt + 1}): {e}")
253
  if attempt < max_retries - 1:
254
  await asyncio.sleep(3)
255
 
 
374
  return {'bitcoin': None, 'ethereum': None}
375
 
376
  except Exception as e:
377
+ print(f"❌ فشل جلب الأسعار: {e}")
378
  return {'bitcoin': None, 'ethereum': None}
379
 
380
  async def _get_prices_from_kucoin_safe(self):
 
390
  if btc_price and btc_price > 0:
391
  prices['bitcoin'] = btc_price
392
  self.price_cache['bitcoin'] = btc_price
393
+ print(f"✅ سعر BTC: ${btc_price:,.2f}")
394
+ else:
395
+ print("⚠️ لم يتم العثور على سعر BTC صالح")
396
  except Exception as e:
397
+ print(f"❌ فشل جلب سعر BTC: {e}")
398
 
399
  try:
400
  eth_ticker = await self.exchange.fetch_ticker('ETH/USDT')
 
402
  if eth_price and eth_price > 0:
403
  prices['ethereum'] = eth_price
404
  self.price_cache['ethereum'] = eth_price
405
+ print(f"✅ سعر ETH: ${eth_price:,.2f}")
406
+ else:
407
+ print("⚠️ لم يتم العثور على سعر ETH صالح")
408
  except Exception as e:
409
+ print(f"❌ فشل جلب سعر ETH: {e}")
410
 
411
  return prices
412
 
413
  except Exception as e:
414
+ print(f"❌ خطأ في _get_prices_from_kucoin_safe: {e}")
415
  return {'bitcoin': None, 'ethereum': None}
416
 
417
  async def _get_prices_from_coingecko(self):
 
429
  if btc_price and eth_price:
430
  self.price_cache['bitcoin'] = btc_price
431
  self.price_cache['ethereum'] = eth_price
432
+ print(f"✅ سعر BTC (CoinGecko): ${btc_price:,.2f}")
433
+ print(f"✅ سعر ETH (CoinGecko): ${eth_price:,.2f}")
434
  return {'bitcoin': btc_price, 'ethereum': eth_price}
435
  else:
436
+ print("⚠️ لم يتم العثور على أسعار صالحة من CoinGecko")
437
  return {'bitcoin': None, 'ethereum': None}
438
 
439
  except Exception as e:
440
+ print(f"❌ فشل جلب الأسعار من CoinGecko: {e}")
441
  return {'bitcoin': None, 'ethereum': None}
442
 
443
  def _get_minimal_market_context(self):
 
588
  return final_score
589
 
590
  except Exception as e:
591
+ print(f"❌ خطأ في حساب الدرجة التقنية لـ {symbol}: {e}")
592
  return 0.0
593
 
594
  async def find_high_potential_candidates(self, count=20):
595
  try:
596
+ print(f"🔍 البحث عن {count} رمز ذو إمكانات عالية بناءً على المؤشرات التقنية...")
597
+
598
  if not self.exchange:
599
+ print("❌ لا يوجد اتصال بـ KuCoin")
600
  return []
601
 
602
  if not self.market_cache or not self.last_market_load or (datetime.now() - self.last_market_load).total_seconds() > 3600:
 
607
  if symbol.endswith('/USDT') and self.market_cache[symbol].get('active', False)
608
  ]
609
 
610
+ print(f"✅ تم العثور على {len(usdt_symbols)} رمز USDT نشط في KuCoin")
611
+
612
  candidates_with_scores = []
613
  analyzed_count = 0
614
 
615
  for symbol in usdt_symbols[:100]:
616
  try:
617
  analyzed_count += 1
618
+ if analyzed_count % 10 == 0:
619
+ print(f"📊 تم تحليل {analyzed_count} رمز من أصل {min(100, len(usdt_symbols))}")
620
 
621
  ohlcv_1h = await self.exchange.fetch_ohlcv(symbol, '1h', limit=50)
622
 
 
648
  })
649
 
650
  except Exception as e:
651
+ if "rate limit" not in str(e).lower():
652
+ print(f"⚠️ خطأ في تحليل الرمز {symbol}: {e}")
653
  continue
654
 
655
  candidates_with_scores.sort(key=lambda x: x['technical_score'], reverse=True)
656
  top_candidates = candidates_with_scores[:count]
657
 
658
+ print(f"✅ تم العثور على {len(top_candidates)} مرشح عالي الجودة من أصل {analyzed_count} رمز تم تحليله")
659
+
660
+ for candidate in top_candidates[:5]:
661
+ print(f" 🥇 {candidate['symbol']}: درجة {candidate['technical_score']:.3f}")
662
+
663
  return top_candidates
664
 
665
  except Exception as e:
666
+ print(f"❌ خطأ في find_high_potential_candidates: {e}")
667
  return []
668
 
669
  async def get_fast_pass_data_async(self, candidates):
670
  try:
671
+ print(f"📊 جلب بيانات OHLCV لـ {len(candidates)} مرشح من KuCoin...")
672
  results = []
673
 
674
  timeframes = [
 
692
  ohlcv = await self.exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
693
 
694
  if not ohlcv or len(ohlcv) < 50:
695
+ print(f"⚠️ بيانات غير كافية للرمز {symbol} في الإطار {timeframe}: {len(ohlcv) if ohlcv else 0} شمعة")
696
  has_sufficient_data = False
697
  break
698
 
699
  ohlcv_data[timeframe] = ohlcv
700
+ print(f" ✅ {symbol} - {timeframe}: {len(ohlcv)} شمعة")
701
 
702
+ await asyncio.sleep(0.1)
703
 
704
  except Exception as e:
705
+ print(f"❌ خطأ في جلب بيانات {symbol} للإطار {timeframe}: {e}")
706
  has_sufficient_data = False
707
  break
708
 
 
715
  }
716
 
717
  results.append(result_data)
718
+ print(f"✅ تم تجميع بيانات {symbol} بنجاح")
719
+ else:
720
+ print(f"❌ فشل تجميع بيانات كافية لـ {symbol}")
721
 
722
  except Exception as symbol_error:
723
+ print(f"❌ خطأ في معالجة الرمز {symbol}: {symbol_error}")
724
  continue
725
 
726
+ print(f"✅ تم تجميع بيانات لـ {len(results)} مرشح بنجاح")
727
  return results
728
 
729
  except Exception as e:
730
+ print(f"❌ خطأ في get_fast_pass_data_async: {e}")
731
  return []
732
 
733
  async def get_latest_price_async(self, symbol):
734
  try:
735
  if not self.exchange:
736
+ print("❌ لا يوجد اتصال بـ KuCoin")
737
  return None
738
 
739
  if symbol not in self.market_cache:
740
+ print(f"⚠️ السوق {symbol} غير متوفر في KuCoin")
741
  return None
742
 
743
  ticker = await self.exchange.fetch_ticker(symbol)
 
746
  if current_price:
747
  return float(current_price)
748
  else:
749
+ print(f"❌ لم يتم العثور على سعر لـ {symbol}")
750
  return None
751
 
752
  except Exception as e:
753
+ print(f"❌ خطأ في get_latest_price_async لـ {symbol}: {e}")
754
  return None
755
 
756
  async def get_available_symbols(self):
 
769
  return usdt_symbols
770
 
771
  except Exception as e:
772
+ print(f"❌ خطأ في get_available_symbols: {e}")
773
  return []
774
 
775
  async def validate_symbol(self, symbol):
 
783
  return symbol in self.market_cache and self.market_cache[symbol].get('active', False)
784
 
785
  except Exception as e:
786
+ print(f"❌ خطأ في validate_symbol لـ {symbol}: {e}")
787
  return False
788
 
789
  print("✅ DataManager loaded - Real-time market data from KuCoin ready")