Riy777 commited on
Commit
d16eedb
·
1 Parent(s): f047b93

Update whale_news_data.py

Browse files
Files changed (1) hide show
  1. whale_news_data.py +80 -12
whale_news_data.py CHANGED
@@ -4,14 +4,13 @@ import httpx
4
  import json
5
  import traceback
6
  import time
7
- import math
8
  from datetime import datetime, timedelta
9
  from collections import defaultdict, deque
10
  import ccxt.pro as ccxt
11
  import numpy as np
12
 
13
  class EnhancedWhaleMonitor:
14
- def __init__(self, contracts_db=None):
15
  self.http_client = httpx.AsyncClient(timeout=15.0, limits=httpx.Limits(max_connections=50, max_keepalive_connections=10))
16
 
17
  self.moralis_key = os.getenv("MORALIS_KEY")
@@ -21,6 +20,7 @@ class EnhancedWhaleMonitor:
21
  self.whale_threshold_usd = 100000
22
  self.contracts_db = contracts_db or {}
23
  self.data_manager = None
 
24
 
25
  self.address_labels = {}
26
  self._initialize_dynamic_labels()
@@ -87,6 +87,7 @@ class EnhancedWhaleMonitor:
87
 
88
  self.pattern_performance = {}
89
  self.pattern_success_rates = {}
 
90
 
91
  def _initialize_dynamic_labels(self):
92
  self.address_categories = {
@@ -108,6 +109,45 @@ class EnhancedWhaleMonitor:
108
 
109
  self._load_initial_exchange_addresses()
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  def _load_initial_exchange_addresses(self):
112
  for exchange, addresses in self.exchange_patterns.items():
113
  for address in addresses:
@@ -200,7 +240,7 @@ class EnhancedWhaleMonitor:
200
  self.netflow_data[network][token_symbol]['netflow'].append(current_netflow)
201
 
202
  except Exception as e:
203
- print(f"خطأ في تحديث مقاييس صافي التدفق: {e}")
204
 
205
  def _initialize_token_metrics(self, network, token_symbol):
206
  self.netflow_data[network][token_symbol] = {
@@ -240,7 +280,7 @@ class EnhancedWhaleMonitor:
240
  return zscore
241
 
242
  except Exception as e:
243
- print(f"خطأ في حساب Z-score: {e}")
244
  return 0
245
 
246
  def _generate_netflow_signal(self, network, token_symbol):
@@ -315,7 +355,7 @@ class EnhancedWhaleMonitor:
315
  return signal
316
 
317
  except Exception as e:
318
- print(f"خطأ في توليد إشارة التداول: {e}")
319
  return None
320
 
321
  async def _scan_single_evm_network(self, network):
@@ -397,7 +437,7 @@ class EnhancedWhaleMonitor:
397
  return whale_alerts, trading_signals
398
 
399
  except Exception as e:
400
- print(f"خطأ في مسح شبكة {network}: {e}")
401
  return [], []
402
 
403
  async def get_general_whale_activity(self):
@@ -973,6 +1013,7 @@ class EnhancedWhaleMonitor:
973
  return None
974
 
975
  async def track_pattern_outcome(self, symbol, pattern_analysis, success, profit_percent):
 
976
  if not pattern_analysis:
977
  return
978
 
@@ -985,20 +1026,47 @@ class EnhancedWhaleMonitor:
985
  'total_trades': 0,
986
  'successful_trades': 0,
987
  'total_profit': 0,
988
- 'total_confidence': 0
 
989
  }
990
 
991
  stats = self.pattern_performance[pattern_name]
992
  stats['total_trades'] += 1
993
  stats['total_confidence'] += confidence
 
994
 
995
  if success:
996
  stats['successful_trades'] += 1
997
  stats['total_profit'] += profit_percent
998
 
999
- def get_pattern_reliability(self, pattern_name):
1000
- if pattern_name in self.pattern_performance:
1001
- stats = self.pattern_performance[pattern_name]
1002
  if stats['total_trades'] > 0:
1003
- return stats['successful_trades'] / stats['total_trades']
1004
- return 0.5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  import json
5
  import traceback
6
  import time
 
7
  from datetime import datetime, timedelta
8
  from collections import defaultdict, deque
9
  import ccxt.pro as ccxt
10
  import numpy as np
11
 
12
  class EnhancedWhaleMonitor:
13
+ def __init__(self, contracts_db=None, r2_service=None):
14
  self.http_client = httpx.AsyncClient(timeout=15.0, limits=httpx.Limits(max_connections=50, max_keepalive_connections=10))
15
 
16
  self.moralis_key = os.getenv("MORALIS_KEY")
 
20
  self.whale_threshold_usd = 100000
21
  self.contracts_db = contracts_db or {}
22
  self.data_manager = None
23
+ self.r2_service = r2_service
24
 
25
  self.address_labels = {}
26
  self._initialize_dynamic_labels()
 
87
 
88
  self.pattern_performance = {}
89
  self.pattern_success_rates = {}
90
+ self._load_pattern_performance()
91
 
92
  def _initialize_dynamic_labels(self):
93
  self.address_categories = {
 
109
 
110
  self._load_initial_exchange_addresses()
111
 
112
+ async def _load_pattern_performance(self):
113
+ """تحميل بيانات أداء الأنماط من التخزين"""
114
+ if not self.r2_service:
115
+ return
116
+
117
+ try:
118
+ key = "pattern_performance.json"
119
+ response = self.r2_service.s3_client.get_object(Bucket="trading", Key=key)
120
+ data = json.loads(response['Body'].read())
121
+ self.pattern_performance = data.get('pattern_performance', {})
122
+ self.pattern_success_rates = data.get('pattern_success_rates', {})
123
+ print(f"✅ تم تحميل بيانات أداء الأنماط: {len(self.pattern_performance)} نمط")
124
+ except Exception as e:
125
+ print(f"⚠️ لم يتم العثور على بيانات أداء الأنماط: {e}")
126
+ self.pattern_performance = {}
127
+ self.pattern_success_rates = {}
128
+
129
+ async def _save_pattern_performance(self):
130
+ """حفظ بيانات أداء الأنماط إلى التخزين"""
131
+ if not self.r2_service:
132
+ return
133
+
134
+ try:
135
+ key = "pattern_performance.json"
136
+ data = {
137
+ 'pattern_performance': self.pattern_performance,
138
+ 'pattern_success_rates': self.pattern_success_rates,
139
+ 'last_updated': datetime.now().isoformat(),
140
+ 'total_patterns': len(self.pattern_performance)
141
+ }
142
+
143
+ data_json = json.dumps(data, indent=2).encode('utf-8')
144
+ self.r2_service.s3_client.put_object(
145
+ Bucket="trading", Key=key, Body=data_json, ContentType="application/json"
146
+ )
147
+ print(f"✅ تم حفظ بيانات أداء الأنماط: {len(self.pattern_performance)} نمط")
148
+ except Exception as e:
149
+ print(f"❌ فشل حفظ بيانات أداء الأنماط: {e}")
150
+
151
  def _load_initial_exchange_addresses(self):
152
  for exchange, addresses in self.exchange_patterns.items():
153
  for address in addresses:
 
240
  self.netflow_data[network][token_symbol]['netflow'].append(current_netflow)
241
 
242
  except Exception as e:
243
+ print(f"خطأ في تحديث مقاييس صافي التدفق: {e}")
244
 
245
  def _initialize_token_metrics(self, network, token_symbol):
246
  self.netflow_data[network][token_symbol] = {
 
280
  return zscore
281
 
282
  except Exception as e:
283
+ print(f"خطأ في حساب Z-score: {e}")
284
  return 0
285
 
286
  def _generate_netflow_signal(self, network, token_symbol):
 
355
  return signal
356
 
357
  except Exception as e:
358
+ print(f"خطأ في توليد إشارة التداول: {e}")
359
  return None
360
 
361
  async def _scan_single_evm_network(self, network):
 
437
  return whale_alerts, trading_signals
438
 
439
  except Exception as e:
440
+ print(f"خطأ في مسح شبكة {network}: {e}")
441
  return [], []
442
 
443
  async def get_general_whale_activity(self):
 
1013
  return None
1014
 
1015
  async def track_pattern_outcome(self, symbol, pattern_analysis, success, profit_percent):
1016
+ """تتبع نتائج الأنماط وحفظها"""
1017
  if not pattern_analysis:
1018
  return
1019
 
 
1026
  'total_trades': 0,
1027
  'successful_trades': 0,
1028
  'total_profit': 0,
1029
+ 'total_confidence': 0,
1030
+ 'last_updated': datetime.now().isoformat()
1031
  }
1032
 
1033
  stats = self.pattern_performance[pattern_name]
1034
  stats['total_trades'] += 1
1035
  stats['total_confidence'] += confidence
1036
+ stats['last_updated'] = datetime.now().isoformat()
1037
 
1038
  if success:
1039
  stats['successful_trades'] += 1
1040
  stats['total_profit'] += profit_percent
1041
 
1042
+ # تحديث معدلات النجاح
 
 
1043
  if stats['total_trades'] > 0:
1044
+ self.pattern_success_rates[pattern_name] = {
1045
+ 'success_rate': stats['successful_trades'] / stats['total_trades'],
1046
+ 'avg_profit': stats['total_profit'] / stats['total_trades'],
1047
+ 'total_trades': stats['total_trades'],
1048
+ 'last_updated': datetime.now().isoformat()
1049
+ }
1050
+
1051
+ # الحفظ التلقائي كل 10 تحديثات
1052
+ if stats['total_trades'] % 10 == 0:
1053
+ await self._save_pattern_performance()
1054
+
1055
+ def get_pattern_reliability(self, pattern_name):
1056
+ """الحصول على موثوقية النمط"""
1057
+ if pattern_name in self.pattern_success_rates:
1058
+ return self.pattern_success_rates[pattern_name]['success_rate']
1059
+ return 0.5
1060
+
1061
+ async def save_all_pattern_data(self):
1062
+ """حفظ جميع بيانات الأنماط"""
1063
+ await self._save_pattern_performance()
1064
+
1065
+ def get_pattern_performance_summary(self):
1066
+ """الحصول على ملخص أداء الأنماط"""
1067
+ return {
1068
+ 'pattern_performance': self.pattern_performance,
1069
+ 'pattern_success_rates': self.pattern_success_rates,
1070
+ 'total_patterns_tracked': len(self.pattern_performance),
1071
+ 'last_updated': datetime.now().isoformat()
1072
+ }