Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -16,7 +16,7 @@ try:
|
|
| 16 |
from r2 import R2Service
|
| 17 |
from LLM import LLMService
|
| 18 |
from data_manager import DataManager
|
| 19 |
-
from ml_engine.processor import MLProcessor
|
| 20 |
from learning_engine import LearningEngine
|
| 21 |
from sentiment_news import SentimentAnalyzer
|
| 22 |
from trade_manager import TradeManager
|
|
@@ -26,7 +26,8 @@ except ImportError as e:
|
|
| 26 |
print(f"❌ خطأ في استيراد الوحدات: {e}")
|
| 27 |
sys.exit(1)
|
| 28 |
|
| 29 |
-
# المتغيرات العالمية
|
|
|
|
| 30 |
r2_service_global = None
|
| 31 |
data_manager_global = None
|
| 32 |
llm_service_global = None
|
|
@@ -42,25 +43,17 @@ class StateManager:
|
|
| 42 |
self.initialization_complete = False
|
| 43 |
self.initialization_error = None
|
| 44 |
self.services_initialized = {
|
| 45 |
-
'r2_service': False,
|
| 46 |
-
'
|
| 47 |
-
'llm_service': False,
|
| 48 |
-
'learning_engine': False,
|
| 49 |
-
'trade_manager': False,
|
| 50 |
-
'sentiment_analyzer': False,
|
| 51 |
'symbol_whale_monitor': False
|
| 52 |
}
|
| 53 |
|
| 54 |
async def wait_for_initialization(self, timeout=60):
|
| 55 |
start_time = time.time()
|
| 56 |
while not self.initialization_complete and (time.time() - start_time) < timeout:
|
| 57 |
-
if self.initialization_error:
|
| 58 |
-
raise Exception(f"فشل التهيئة: {self.initialization_error}")
|
| 59 |
await asyncio.sleep(2)
|
| 60 |
-
|
| 61 |
-
if not self.initialization_complete:
|
| 62 |
-
raise Exception(f"انتهت مهلة التهيئة ({timeout} ثانية)")
|
| 63 |
-
|
| 64 |
return self.initialization_complete
|
| 65 |
|
| 66 |
def set_service_initialized(self, service_name):
|
|
@@ -75,196 +68,119 @@ class StateManager:
|
|
| 75 |
|
| 76 |
state_manager = StateManager()
|
| 77 |
|
|
|
|
|
|
|
| 78 |
async def initialize_services():
|
| 79 |
"""تهيئة جميع الخدمات بشكل منفصل"""
|
| 80 |
global r2_service_global, data_manager_global, llm_service_global
|
| 81 |
global learning_engine_global, trade_manager_global, sentiment_analyzer_global
|
| 82 |
global symbol_whale_monitor_global
|
| 83 |
-
|
| 84 |
try:
|
| 85 |
print("🚀 بدء تهيئة الخدمات...")
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
print(" 🔄 تهيئة
|
| 89 |
-
r2_service_global = R2Service()
|
| 90 |
-
state_manager.set_service_initialized('r2_service')
|
| 91 |
-
print(" ✅ R2Service مهيأة")
|
| 92 |
-
|
| 93 |
-
# 2. تحميل قاعدة بيانات العقود
|
| 94 |
-
print(" 🔄 جلب قاعدة بيانات العقود...")
|
| 95 |
-
contracts_database = await r2_service_global.load_contracts_db_async()
|
| 96 |
-
print(f" ✅ تم تحميل {len(contracts_database)} عقد")
|
| 97 |
-
|
| 98 |
-
# 3. تهيئة مراقب الحيتان
|
| 99 |
-
print(" 🔄 تهيئة مراقب الحيتان...")
|
| 100 |
try:
|
| 101 |
from whale_news_data import EnhancedWhaleMonitor
|
| 102 |
symbol_whale_monitor_global = EnhancedWhaleMonitor(contracts_database, r2_service_global)
|
| 103 |
-
state_manager.set_service_initialized('symbol_whale_monitor')
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
print("
|
| 111 |
-
|
| 112 |
-
await data_manager_global.initialize()
|
| 113 |
-
state_manager.set_service_initialized('data_manager')
|
| 114 |
-
print(" ✅ DataManager مهيأ")
|
| 115 |
-
|
| 116 |
-
# 5. تهيئة LLMService
|
| 117 |
-
print(" 🔄 تهيئة LLMService...")
|
| 118 |
-
llm_service_global = LLMService()
|
| 119 |
-
llm_service_global.r2_service = r2_service_global
|
| 120 |
-
state_manager.set_service_initialized('llm_service')
|
| 121 |
-
print(" ✅ LLMService مهيأ")
|
| 122 |
-
|
| 123 |
-
# 6. تهيئة محلل المشاعر
|
| 124 |
-
print(" 🔄 تهيئة محلل المشاعر...")
|
| 125 |
-
sentiment_analyzer_global = SentimentAnalyzer(data_manager_global)
|
| 126 |
-
state_manager.set_service_initialized('sentiment_analyzer')
|
| 127 |
-
print(" ✅ محلل المشاعر مهيأ")
|
| 128 |
-
|
| 129 |
-
# 7. تهيئة محرك التعلم
|
| 130 |
-
print(" 🔄 تهيئة محرك التعلم...")
|
| 131 |
-
learning_engine_global = LearningEngine(r2_service_global, data_manager_global)
|
| 132 |
-
await learning_engine_global.initialize_enhanced()
|
| 133 |
-
state_manager.set_service_initialized('learning_engine')
|
| 134 |
-
print(" ✅ محرك التعلم مهيأ")
|
| 135 |
-
|
| 136 |
-
# 8. تهيئة مدير الصفقات
|
| 137 |
-
print(" 🔄 تهيئة مدير الصفقات...")
|
| 138 |
-
trade_manager_global = TradeManager(r2_service_global, learning_engine_global, data_manager_global)
|
| 139 |
-
state_manager.set_service_initialized('trade_manager')
|
| 140 |
-
print(" ✅ مدير الصفقات مهيأ")
|
| 141 |
-
|
| 142 |
-
print("🎯 اكتملت تهيئة جميع الخدمات بنجاح")
|
| 143 |
-
return True
|
| 144 |
-
|
| 145 |
-
except Exception as e:
|
| 146 |
-
error_msg = f"فشل تهيئة الخدمات: {str(e)}"
|
| 147 |
-
print(f"❌ {error_msg}")
|
| 148 |
-
state_manager.set_initialization_error(error_msg)
|
| 149 |
-
return False
|
| 150 |
|
| 151 |
async def monitor_market_async():
|
| 152 |
"""مراقبة السوق"""
|
| 153 |
global data_manager_global, sentiment_analyzer_global
|
| 154 |
-
|
| 155 |
try:
|
| 156 |
-
if not await state_manager.wait_for_initialization():
|
| 157 |
-
print("❌ فشل تهيئة الخدمات - إيقاف مراقبة السوق")
|
| 158 |
-
return
|
| 159 |
-
|
| 160 |
while True:
|
| 161 |
try:
|
| 162 |
async with state_manager.market_analysis_lock:
|
| 163 |
market_context = await sentiment_analyzer_global.get_market_sentiment()
|
| 164 |
-
if not market_context:
|
| 165 |
-
state.MARKET_STATE_OK = True
|
| 166 |
-
await asyncio.sleep(60)
|
| 167 |
-
continue
|
| 168 |
-
|
| 169 |
bitcoin_sentiment = market_context.get('btc_sentiment')
|
| 170 |
fear_greed_index = market_context.get('fear_and_greed_index')
|
| 171 |
-
|
| 172 |
should_halt_trading, halt_reason = False, ""
|
| 173 |
-
|
| 174 |
-
if
|
| 175 |
-
should_halt_trading, halt_reason = True, "ظروف سوق هابطة"
|
| 176 |
-
|
| 177 |
-
if should_halt_trading:
|
| 178 |
-
state.MARKET_STATE_OK = False
|
| 179 |
-
await r2_service_global.save_system_logs_async({"market_halt": True, "reason": halt_reason})
|
| 180 |
else:
|
| 181 |
-
if not state.MARKET_STATE_OK:
|
| 182 |
-
print("✅ تحسنت ظروف السوق. استئناف العمليات العادية.")
|
| 183 |
state.MARKET_STATE_OK = True
|
| 184 |
-
|
| 185 |
-
await asyncio.sleep(60)
|
| 186 |
-
except Exception as error:
|
| 187 |
-
print(f"❌ خطأ أثناء مراقبة السوق: {error}")
|
| 188 |
-
state.MARKET_STATE_OK = True
|
| 189 |
await asyncio.sleep(60)
|
| 190 |
-
|
| 191 |
-
|
| 192 |
|
| 193 |
|
| 194 |
-
# 🔴 ---
|
| 195 |
-
#
|
| 196 |
-
|
| 197 |
-
async def process_batch_parallel(batch, ml_processor, batch_num, total_batches):
|
| 198 |
"""
|
| 199 |
(معدلة) معالجة دفعة من الرموز بشكل متوازي وإرجاع نتائج مفصلة
|
| 200 |
-
|
|
|
|
| 201 |
"""
|
| 202 |
-
|
| 203 |
-
# 🔴 تحديد 5 عمليات متزامنة كحد أقصى (من الـ 15 في الدفعة)
|
| 204 |
-
# هذا هو مفتاح الحل لمنع انهيار الشبكة
|
| 205 |
-
CONCURRENT_ML_TASKS = 5
|
| 206 |
-
semaphore = asyncio.Semaphore(CONCURRENT_ML_TASKS)
|
| 207 |
-
|
| 208 |
-
tasks_results = []
|
| 209 |
-
|
| 210 |
-
async def process_symbol_with_semaphore(symbol_data):
|
| 211 |
-
"""دالة داخلية لاستهدافها بالـ Semaphore"""
|
| 212 |
-
async with semaphore:
|
| 213 |
-
try:
|
| 214 |
-
# هذه هي المهمة التي تستهلك الشبكة (جلب بيانات الحيتان)
|
| 215 |
-
return await ml_processor.process_and_score_symbol_enhanced(symbol_data)
|
| 216 |
-
except Exception as e:
|
| 217 |
-
# إرجاع الخطأ ليتم تسجيله
|
| 218 |
-
return e
|
| 219 |
-
|
| 220 |
try:
|
| 221 |
-
|
|
|
|
| 222 |
|
| 223 |
batch_tasks = []
|
| 224 |
for symbol_data in batch:
|
| 225 |
-
# 🔴
|
| 226 |
-
task = asyncio.create_task(
|
| 227 |
batch_tasks.append(task)
|
| 228 |
|
| 229 |
-
# انتظار
|
| 230 |
-
|
| 231 |
|
| 232 |
successful_results = []
|
| 233 |
low_score_results = []
|
| 234 |
failed_results = []
|
| 235 |
|
| 236 |
-
|
|
|
|
| 237 |
symbol = batch[i].get('symbol', 'unknown')
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
else:
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
| 249 |
|
| 250 |
-
|
| 251 |
-
return {
|
| 252 |
-
'success': successful_results,
|
| 253 |
-
'low_score': low_score_results,
|
| 254 |
-
'failures': failed_results
|
| 255 |
-
}
|
| 256 |
|
| 257 |
except Exception as error:
|
| 258 |
print(f"❌ [المستهلك] خطأ في معالجة الدفعة {batch_num}: {error}")
|
| 259 |
return {'success': [], 'low_score': [], 'failures': []}
|
| 260 |
-
# 🔴 --- نهاية التعديل الجوهري --- 🔴
|
| 261 |
|
| 262 |
|
|
|
|
|
|
|
| 263 |
async def run_3_layer_analysis():
|
| 264 |
"""
|
| 265 |
-
(معدلة) تشغيل النظام الطبقي (
|
| 266 |
الطبقة 1: data_manager - الفحص السريع
|
| 267 |
-
الطبقة
|
|
|
|
| 268 |
الطبقة 3: LLMService - النموذج الضخم
|
| 269 |
"""
|
| 270 |
|
|
@@ -274,610 +190,385 @@ async def run_3_layer_analysis():
|
|
| 274 |
all_failed_candidates = []
|
| 275 |
final_layer2_candidates = []
|
| 276 |
final_opportunities = []
|
|
|
|
| 277 |
|
| 278 |
try:
|
| 279 |
-
print("🎯 بدء النظام الطبقي المكون من 3 طبقات (
|
| 280 |
|
| 281 |
-
if not await state_manager.wait_for_initialization():
|
| 282 |
-
print("❌ الخدمات غير مهيأة بالكامل")
|
| 283 |
-
return None
|
| 284 |
|
| 285 |
-
# الطبقة 1: الفحص السريع
|
| 286 |
print("\n🔍 الطبقة 1: الفحص السريع (data_manager)...")
|
| 287 |
layer1_candidates = await data_manager_global.layer1_rapid_screening()
|
| 288 |
-
|
| 289 |
-
if not layer1_candidates:
|
| 290 |
-
print("❌ لم يتم العثور على مرشحين في الطبقة 1")
|
| 291 |
-
return None
|
| 292 |
-
|
| 293 |
print(f"✅ تم اختيار {len(layer1_candidates)} عملة للطبقة 2")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
-
#
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
-
#
|
| 298 |
DATA_QUEUE_MAX_SIZE = 2
|
| 299 |
ohlcv_data_queue = asyncio.Queue(maxsize=DATA_QUEUE_MAX_SIZE)
|
| 300 |
-
|
| 301 |
-
# قائمة لتجميع كل النتائج النهائية من المستهلك
|
| 302 |
ml_results_list = []
|
| 303 |
-
|
| 304 |
-
# 2. إعداد المستهلك (MLProcessor)
|
| 305 |
market_context = await data_manager_global.get_market_context_async()
|
| 306 |
ml_processor = MLProcessor(market_context, data_manager_global, learning_engine_global)
|
| 307 |
-
|
| 308 |
-
# حساب إجمالي عدد الدفعات للمستهلك
|
| 309 |
-
batch_size = 15 # يجب أن يتطابق هذا مع حجم الدفعة في data_manager
|
| 310 |
total_batches = (len(layer1_candidates) + batch_size - 1) // batch_size
|
| 311 |
-
|
| 312 |
-
print(f" 🚀 إعداد المنتج/المستهلك: {total_batches} دفعة متوقعة (بحجم {batch_size})")
|
| 313 |
|
| 314 |
-
#
|
| 315 |
-
async def ml_consumer_task(queue: asyncio.Queue, results_list: list):
|
| 316 |
batch_num = 0
|
| 317 |
while True:
|
| 318 |
try:
|
| 319 |
-
# انتظار بيانات من المنتج
|
| 320 |
batch_data = await queue.get()
|
| 321 |
-
|
| 322 |
-
# 🔴 إشارة التوقف (None)
|
| 323 |
-
if batch_data is None:
|
| 324 |
-
queue.task_done()
|
| 325 |
-
print(" 🛑 [المستهلك] تلقى إشارة التوقف.")
|
| 326 |
-
break
|
| 327 |
|
| 328 |
batch_num += 1
|
| 329 |
-
print(f" 📬 [
|
| 330 |
|
| 331 |
-
# 🔴
|
| 332 |
batch_results_dict = await process_batch_parallel(
|
| 333 |
-
batch_data, ml_processor, batch_num, total_batches
|
| 334 |
)
|
| 335 |
|
| 336 |
results_list.append(batch_results_dict)
|
| 337 |
-
|
| 338 |
-
# إبلاغ الطابور بانتهاء معالجة هذه المهمة
|
| 339 |
queue.task_done()
|
|
|
|
| 340 |
|
| 341 |
except Exception as e:
|
| 342 |
-
print(f"❌ [
|
| 343 |
-
traceback.print_exc()
|
| 344 |
-
queue.task_done() # يجب استدعاؤها حتى عند الفشل
|
| 345 |
|
| 346 |
-
#
|
| 347 |
-
print(" ▶️ [
|
| 348 |
-
consumer_task = asyncio.create_task(ml_consumer_task(ohlcv_data_queue, ml_results_list))
|
| 349 |
|
| 350 |
-
#
|
| 351 |
-
|
| 352 |
-
print(" ▶️ [المنتج] بدء تشغيل مهمة المنتج (تدفق بيانات OHLCV)...")
|
| 353 |
producer_task = asyncio.create_task(
|
| 354 |
data_manager_global.stream_ohlcv_data(layer1_symbols, ohlcv_data_queue)
|
| 355 |
)
|
| 356 |
|
| 357 |
-
#
|
| 358 |
await producer_task
|
| 359 |
-
print(" ✅ [
|
| 360 |
|
| 361 |
-
#
|
| 362 |
await ohlcv_data_queue.put(None)
|
| 363 |
|
| 364 |
-
#
|
| 365 |
-
await ohlcv_data_queue.join()
|
| 366 |
-
await consumer_task
|
| 367 |
-
print(" ✅ [
|
| 368 |
-
|
| 369 |
-
# 🔴
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
|
| 371 |
-
# 9. تجميع النتائج
|
| 372 |
print("🔄 تجميع جميع النتائج...")
|
|
|
|
| 373 |
for batch_result in ml_results_list:
|
| 374 |
-
# دمج بيانات الطبقة 1 (الدرجة والأسباب) مع نتائج الطبقة 2
|
| 375 |
for success_item in batch_result['success']:
|
| 376 |
symbol = success_item['symbol']
|
| 377 |
l1_data = next((c for c in layer1_candidates if c['symbol'] == symbol), None)
|
| 378 |
if l1_data:
|
| 379 |
success_item['reasons_for_candidacy'] = l1_data.get('reasons', [])
|
| 380 |
success_item['layer1_score'] = l1_data.get('layer1_score', 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
layer2_candidates.append(success_item)
|
| 382 |
-
|
| 383 |
all_low_score_candidates.extend(batch_result['low_score'])
|
| 384 |
all_failed_candidates.extend(batch_result['failures'])
|
| 385 |
-
|
|
|
|
| 386 |
print(f"✅ اكتمل التحليل المتقدم: {len(layer2_candidates)} نجاح (عالي) | {len(all_low_score_candidates)} نجاح (منخفض) | {len(all_failed_candidates)} فشل")
|
| 387 |
|
| 388 |
-
if not layer2_candidates:
|
| 389 |
-
print("❌ لم يتم العثور على مرشحين في الطبقة 2")
|
| 390 |
-
# استمرار لتسجيل ��لسجل
|
| 391 |
|
| 392 |
-
# 10. الترتيب والفلترة (
|
| 393 |
layer2_candidates.sort(key=lambda x: x.get('enhanced_final_score', 0), reverse=True)
|
| 394 |
target_count = min(10, len(layer2_candidates))
|
| 395 |
final_layer2_candidates = layer2_candidates[:target_count]
|
| 396 |
-
|
| 397 |
print(f"🎯 تم اختيار {len(final_layer2_candidates)} عملة للطبقة 3 (الأقوى فقط)")
|
| 398 |
-
|
| 399 |
await r2_service_global.save_candidates_async(final_layer2_candidates)
|
| 400 |
-
|
| 401 |
print("\n🏆 أفضل 10 عملات من الطبقة 2:")
|
|
|
|
| 402 |
for i, candidate in enumerate(final_layer2_candidates):
|
| 403 |
score = candidate.get('enhanced_final_score', 0)
|
| 404 |
strategy = candidate.get('target_strategy', 'GENERIC')
|
| 405 |
-
mc_score = candidate.get('monte_carlo_probability'
|
| 406 |
pattern = candidate.get('pattern_analysis', {}).get('pattern_detected', 'no_pattern')
|
| 407 |
timeframes = candidate.get('successful_timeframes', 0)
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
print(f"
|
| 411 |
-
if mc_score
|
| 412 |
-
print(f" 🎯 مونت كارلو: {mc_score:.3f}")
|
| 413 |
print(f" 🎯 استراتيجية: {strategy} | نمط: {pattern}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
|
| 415 |
-
# 11. الطبقة 3: التحليل بالنموذج الضخم (
|
| 416 |
print("\n🧠 الطبقة 3: التحليل بالنموذج الضخم (LLMService)...")
|
| 417 |
-
|
| 418 |
for candidate in final_layer2_candidates:
|
| 419 |
try:
|
| 420 |
symbol = candidate['symbol']
|
| 421 |
print(f" 🤔 تحليل {symbol} بالنموذج الضخم...")
|
| 422 |
-
|
| 423 |
ohlcv_data = candidate.get('ohlcv')
|
| 424 |
-
|
| 425 |
-
if not ohlcv_data:
|
| 426 |
-
print(f" ⚠️ لا توجد بيانات شموع لـ {symbol}")
|
| 427 |
-
continue
|
| 428 |
-
|
| 429 |
candidate['raw_ohlcv'] = ohlcv_data
|
| 430 |
-
|
| 431 |
timeframes_count = candidate.get('successful_timeframes', 0)
|
| 432 |
total_candles = sum(len(data) for data in ohlcv_data.values()) if ohlcv_data else 0
|
| 433 |
-
|
| 434 |
-
if total_candles < 30:
|
| 435 |
-
print(f" ⚠️ بيانات شموع غير كافية لـ {symbol}: {total_candles} شمعة فقط")
|
| 436 |
-
continue
|
| 437 |
-
|
| 438 |
print(f" 📊 إرسال {symbol} للنموذج: {total_candles} شمعة في {timeframes_count} إطار زمني")
|
| 439 |
-
|
| 440 |
-
llm_analysis
|
| 441 |
-
|
| 442 |
-
if llm_analysis and llm_analysis.get('action') in ['BUY', 'SELL']:
|
| 443 |
opportunity = {
|
| 444 |
-
'symbol': symbol,
|
| 445 |
-
'
|
| 446 |
-
'decision': llm_analysis,
|
| 447 |
-
'enhanced_score': candidate.get('enhanced_final_score', 0),
|
| 448 |
'llm_confidence': llm_analysis.get('confidence_level', 0),
|
| 449 |
'strategy': llm_analysis.get('strategy', 'GENERIC'),
|
| 450 |
'analysis_timestamp': datetime.now().isoformat(),
|
| 451 |
-
'timeframes_count': timeframes_count,
|
| 452 |
-
'total_candles': total_candles
|
| 453 |
}
|
| 454 |
final_opportunities.append(opportunity)
|
| 455 |
-
|
| 456 |
print(f" ✅ {symbol}: {llm_analysis.get('action')} - ثقة: {llm_analysis.get('confidence_level', 0):.2f}")
|
| 457 |
else:
|
| 458 |
action = llm_analysis.get('action', 'NO_DECISION') if llm_analysis else 'NO_RESPONSE'
|
| 459 |
print(f" ⚠️ {symbol}: لا يوجد قرار تداول من النموذج الضخم ({action})")
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
continue
|
| 464 |
-
|
| 465 |
if final_opportunities:
|
| 466 |
final_opportunities.sort(key=lambda x: (x['llm_confidence'] + x['enhanced_score']) / 2, reverse=True)
|
| 467 |
print(f"\n🏆 النظام الطبقي اكتمل: {len(final_opportunities)} فرصة تداول")
|
| 468 |
for i, opportunity in enumerate(final_opportunities[:5]):
|
| 469 |
print(f" {i+1}. {opportunity['symbol']}: {opportunity['decision'].get('action')} - ثقة: {opportunity['llm_confidence']:.2f} - أطر: {opportunity['timeframes_count']}")
|
| 470 |
|
| 471 |
-
# 12. سجل التدقيق (
|
| 472 |
try:
|
|
|
|
| 473 |
top_10_detailed_summary = []
|
| 474 |
for c in final_layer2_candidates:
|
| 475 |
whale_summary = "Not Available"
|
| 476 |
-
whale_data = c.get('whale_data')
|
| 477 |
if whale_data and whale_data.get('data_available'):
|
| 478 |
signal = whale_data.get('trading_signal', {})
|
| 479 |
action = signal.get('action', 'HOLD')
|
| 480 |
confidence = signal.get('confidence', 0)
|
| 481 |
reason_preview = signal.get('reason', 'N/A')[:75] + "..." if signal.get('reason') else 'N/A'
|
| 482 |
whale_summary = f"Action: {action}, Conf: {confidence:.2f}, Alert: {signal.get('critical_alert', False)}, Reason: {reason_preview}"
|
| 483 |
-
|
|
|
|
|
|
|
| 484 |
top_10_detailed_summary.append({
|
| 485 |
-
"symbol": c.get('symbol'),
|
| 486 |
-
"score": c.get('enhanced_final_score', 0),
|
| 487 |
"timeframes": f"{c.get('successful_timeframes', 'N/A')}/6",
|
| 488 |
-
"whale_data_summary": whale_summary,
|
| 489 |
-
"strategy": c.get('target_strategy', 'N/A'),
|
| 490 |
"pattern": c.get('pattern_analysis', {}).get('pattern_detected', 'N/A'),
|
| 491 |
})
|
| 492 |
-
|
| 493 |
other_successful_candidates = layer2_candidates[target_count:]
|
| 494 |
-
other_success_summary = [
|
| 495 |
-
|
| 496 |
-
for c in other_successful_candidates
|
| 497 |
-
]
|
| 498 |
-
|
| 499 |
-
low_score_summary = [
|
| 500 |
-
{"symbol": c['symbol'], "score": c.get('enhanced_final_score', 0), "timeframes": f"{c.get('successful_timeframes', 'N/A')}/6", "whale_data": "Available" if c.get('whale_data', {}).get('data_available') else "Not Available"}
|
| 501 |
-
for c in all_low_score_candidates
|
| 502 |
-
]
|
| 503 |
-
|
| 504 |
audit_data = {
|
| 505 |
-
"timestamp": datetime.now().isoformat(),
|
| 506 |
-
"total_layer1_candidates": len(layer1_candidates),
|
| 507 |
"total_processed_in_layer2": len(layer2_candidates) + len(all_low_score_candidates) + len(all_failed_candidates),
|
| 508 |
-
"counts": {
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
"success_low_score": len(all_low_score_candidates),
|
| 512 |
-
"failures": len(all_failed_candidates)
|
| 513 |
-
},
|
| 514 |
-
"top_candidates_for_llm": top_10_detailed_summary,
|
| 515 |
-
"other_successful_candidates": other_success_summary,
|
| 516 |
-
"low_score_candidates": low_score_summary,
|
| 517 |
-
"failed_candidates": all_failed_candidates,
|
| 518 |
}
|
| 519 |
-
|
| 520 |
await r2_service_global.save_analysis_audit_log_async(audit_data)
|
| 521 |
print(f"✅ تم حفظ سجل تدقيق التحليل في R2.")
|
| 522 |
-
|
| 523 |
-
except Exception as audit_error:
|
| 524 |
-
print(f"❌ فشل حفظ سجل تدقيق التحليل: {audit_error}")
|
| 525 |
-
traceback.print_exc()
|
| 526 |
-
|
| 527 |
-
if not final_opportunities:
|
| 528 |
-
print("❌ لم يتم العثور على فرص تداول مناسبة")
|
| 529 |
-
return None
|
| 530 |
|
|
|
|
| 531 |
return final_opportunities[0] if final_opportunities else None
|
| 532 |
|
| 533 |
except Exception as error:
|
| 534 |
-
print(f"❌ خطأ في النظام الطبقي: {error}")
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
try:
|
| 538 |
-
audit_data = {
|
| 539 |
-
"timestamp": datetime.now().isoformat(),
|
| 540 |
-
"status": "FAILED",
|
| 541 |
-
"error": str(error),
|
| 542 |
-
"traceback": traceback.format_exc(),
|
| 543 |
-
"total_layer1_candidates": len(layer1_candidates),
|
| 544 |
-
"counts": {
|
| 545 |
-
"sent_to_llm": 0,
|
| 546 |
-
"success_not_top_10": 0,
|
| 547 |
-
"success_low_score": len(all_low_score_candidates),
|
| 548 |
-
"failures": len(all_failed_candidates)
|
| 549 |
-
},
|
| 550 |
-
"failed_candidates": all_failed_candidates
|
| 551 |
-
}
|
| 552 |
await r2_service_global.save_analysis_audit_log_async(audit_data)
|
| 553 |
print("⚠️ تم حفظ سجل تدقيق جزئي بعد الفشل.")
|
| 554 |
-
except Exception as audit_fail_error:
|
| 555 |
-
print(f"❌ فشل حفظ سجل التدقيق أثناء معالجة خطأ آخر: {audit_fail_error}")
|
| 556 |
-
|
| 557 |
return None
|
| 558 |
# 🔴 --- نهاية التعديل الجوهري --- 🔴
|
| 559 |
|
| 560 |
-
|
|
|
|
| 561 |
async def re_analyze_open_trade_async(trade_data):
|
| 562 |
"""إعادة تحليل الصفقة المفتوحة"""
|
| 563 |
symbol = trade_data.get('symbol')
|
| 564 |
try:
|
| 565 |
async with state_manager.trade_analysis_lock:
|
| 566 |
-
# جلب البيانات الحالية
|
| 567 |
market_context = await data_manager_global.get_market_context_async()
|
| 568 |
-
|
| 569 |
-
# 🔴 استخدام نموذج الطابور لجلب بيانات الرمز الواحد
|
| 570 |
ohlcv_data_list = []
|
| 571 |
temp_queue = asyncio.Queue()
|
| 572 |
-
# استدعاء المنتج لرمز واحد
|
| 573 |
await data_manager_global.stream_ohlcv_data([symbol], temp_queue)
|
| 574 |
-
# استهلاك البيانات من الطابور
|
| 575 |
while not temp_queue.empty():
|
| 576 |
-
batch = await temp_queue.get()
|
| 577 |
-
if batch:
|
| 578 |
-
ohlcv_data_list.extend(batch)
|
| 579 |
|
| 580 |
-
if not ohlcv_data_list:
|
| 581 |
-
print(f"⚠️ فشل جلب بيانات إعادة التحليل لـ {symbol}")
|
| 582 |
-
return None
|
| 583 |
-
|
| 584 |
ohlcv_data = ohlcv_data_list[0]
|
| 585 |
|
| 586 |
-
# دمج بيانات الطبقة 1 الوهمية لإعادة التحليل
|
| 587 |
l1_data = await data_manager_global._get_detailed_symbol_data(symbol)
|
| 588 |
-
if l1_data:
|
| 589 |
-
ohlcv_data['reasons_for_candidacy'] = l1_data.get('reasons', ['re-analysis'])
|
| 590 |
-
ohlcv_data['layer1_score'] = l1_data.get('layer1_score', 0.5)
|
| 591 |
|
| 592 |
-
#
|
|
|
|
|
|
|
| 593 |
ml_processor = MLProcessor(market_context, data_manager_global, learning_engine_global)
|
| 594 |
-
|
|
|
|
| 595 |
|
| 596 |
-
if not processed_data:
|
| 597 |
-
return None
|
| 598 |
|
| 599 |
processed_data['raw_ohlcv'] = ohlcv_data.get('raw_ohlcv') or ohlcv_data.get('ohlcv')
|
| 600 |
processed_data['ohlcv'] = processed_data['raw_ohlcv']
|
| 601 |
|
| 602 |
-
# استخدام LLM لإعادة التحليل
|
| 603 |
re_analysis_decision = await llm_service_global.re_analyze_trade_async(trade_data, processed_data)
|
| 604 |
|
| 605 |
if re_analysis_decision:
|
| 606 |
-
await r2_service_global.save_system_logs_async({
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
'strategy': re_analysis_decision.get('strategy', 'GENERIC')
|
| 611 |
-
})
|
| 612 |
-
|
| 613 |
-
return {
|
| 614 |
-
"symbol": symbol,
|
| 615 |
-
"decision": re_analysis_decision,
|
| 616 |
-
"current_price": processed_data.get('current_price')
|
| 617 |
-
}
|
| 618 |
-
else:
|
| 619 |
-
return None
|
| 620 |
-
|
| 621 |
-
except Exception as error:
|
| 622 |
-
await r2_service_global.save_system_logs_async({
|
| 623 |
-
"reanalysis_error": True,
|
| 624 |
-
"symbol": symbol,
|
| 625 |
-
"error": str(error)
|
| 626 |
-
})
|
| 627 |
-
return None
|
| 628 |
|
| 629 |
async def run_bot_cycle_async():
|
| 630 |
"""دورة التداول الرئيسية"""
|
| 631 |
try:
|
| 632 |
-
if not await state_manager.wait_for_initialization():
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
print("🔄 بدء دورة التداول...")
|
| 637 |
-
await r2_service_global.save_system_logs_async({"cycle_started": True})
|
| 638 |
-
|
| 639 |
-
if not r2_service_global.acquire_lock():
|
| 640 |
-
print("❌ فشل الحصول على القفل - تخطي الدورة")
|
| 641 |
-
return
|
| 642 |
-
|
| 643 |
try:
|
| 644 |
-
open_trades = await trade_manager_global.get_open_trades()
|
| 645 |
-
print(f"📋 الصفقات المفتوحة: {len(open_trades)}")
|
| 646 |
-
|
| 647 |
should_look_for_new_trade = len(open_trades) == 0
|
| 648 |
-
|
| 649 |
-
# إعادة تحليل الصفقات المفتوحة
|
| 650 |
if open_trades:
|
| 651 |
now = datetime.now()
|
| 652 |
-
trades_to_reanalyze = [
|
| 653 |
-
trade for trade in open_trades
|
| 654 |
-
if now >= datetime.fromisoformat(trade.get('expected_target_time', now.isoformat()))
|
| 655 |
-
]
|
| 656 |
-
|
| 657 |
if trades_to_reanalyze:
|
| 658 |
print(f"🔄 إعادة تحليل {len(trades_to_reanalyze)} صفقة")
|
| 659 |
for trade in trades_to_reanalyze:
|
| 660 |
result = await re_analyze_open_trade_async(trade)
|
| 661 |
-
if result and result['decision'].get('action') == "CLOSE_TRADE":
|
| 662 |
-
|
| 663 |
-
should_look_for_new_trade = True
|
| 664 |
-
elif result and result['decision'].get('action') == "UPDATE_TRADE":
|
| 665 |
-
await trade_manager_global.update_trade(trade, result['decision'])
|
| 666 |
-
|
| 667 |
-
# البحث عن صفقات جديدة إذا لزم الأمر
|
| 668 |
if should_look_for_new_trade:
|
| 669 |
-
portfolio_state = await r2_service_global.get_portfolio_state_async()
|
| 670 |
-
current_capital = portfolio_state.get("current_capital_usd", 0)
|
| 671 |
-
|
| 672 |
if current_capital > 1:
|
| 673 |
-
print("🎯 البحث عن فرص تداول جديدة (
|
| 674 |
best_opportunity = await run_3_layer_analysis()
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
await trade_manager_global.open_trade(
|
| 679 |
-
best_opportunity['symbol'],
|
| 680 |
-
best_opportunity['decision'],
|
| 681 |
-
best_opportunity['current_price']
|
| 682 |
-
)
|
| 683 |
-
else:
|
| 684 |
-
print("❌ لم يتم العثور على فرص تداول مناسبة")
|
| 685 |
-
else:
|
| 686 |
-
print("❌ رأس المال غير كافي لفتح صفقات جديدة")
|
| 687 |
-
|
| 688 |
finally:
|
| 689 |
-
r2_service_global.release_lock()
|
| 690 |
-
await r2_service_global.save_system_logs_async({
|
| 691 |
-
"cycle_completed": True,
|
| 692 |
-
"open_trades": len(open_trades) if 'open_trades' in locals() else 0
|
| 693 |
-
})
|
| 694 |
-
print("✅ اكتملت دورة التداول")
|
| 695 |
-
|
| 696 |
except Exception as error:
|
| 697 |
-
print(f"❌ Unhandled error in main cycle: {error}")
|
| 698 |
-
|
| 699 |
-
"cycle_error": True,
|
| 700 |
-
"error": str(error)
|
| 701 |
-
})
|
| 702 |
-
if r2_service_global.lock_acquired:
|
| 703 |
-
r2_service_global.release_lock()
|
| 704 |
|
| 705 |
@asynccontextmanager
|
| 706 |
async def lifespan(application: FastAPI):
|
| 707 |
"""إدارة دورة حياة التطبيق"""
|
| 708 |
print("🚀 بدء تهيئة التطبيق...")
|
| 709 |
-
|
| 710 |
try:
|
| 711 |
-
# تهيئة الخدمات
|
| 712 |
success = await initialize_services()
|
| 713 |
-
if not success:
|
| 714 |
-
print("❌ فشل تهيئة التطبيق - إغلاق...")
|
| 715 |
-
yield
|
| 716 |
-
return
|
| 717 |
-
|
| 718 |
-
# بدء المهام الخلفية
|
| 719 |
asyncio.create_task(monitor_market_async())
|
| 720 |
asyncio.create_task(trade_manager_global.start_trade_monitoring())
|
| 721 |
-
|
| 722 |
await r2_service_global.save_system_logs_async({"application_started": True})
|
| 723 |
-
print("🎯 التطبيق جاهز للعمل - نظام الطبقات 3 فعال (
|
| 724 |
-
|
| 725 |
yield
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
traceback.print_exc()
|
| 730 |
-
if r2_service_global:
|
| 731 |
-
await r2_service_global.save_system_logs_async({
|
| 732 |
-
"application_startup_failed": True,
|
| 733 |
-
"error": str(error)
|
| 734 |
-
})
|
| 735 |
-
raise
|
| 736 |
-
finally:
|
| 737 |
-
await cleanup_on_shutdown()
|
| 738 |
-
|
| 739 |
-
application = FastAPI(
|
| 740 |
-
lifespan=lifespan,
|
| 741 |
-
title="AI Trading Bot",
|
| 742 |
-
description="نظام تداول ذكي بثلاث طبقات تحليلية (بنموذج التدفق)",
|
| 743 |
-
version="3.1.0"
|
| 744 |
-
)
|
| 745 |
|
| 746 |
-
|
| 747 |
-
async def root():
|
| 748 |
-
"""الصفحة الرئيسية"""
|
| 749 |
-
return {
|
| 750 |
-
"message": "مرحباً بك في نظام التداول الذكي",
|
| 751 |
-
"system": "3-Layer Analysis System (Streaming Pipeline)",
|
| 752 |
-
"status": "running" if state_manager.initialization_complete else "initializing",
|
| 753 |
-
"timestamp": datetime.now().isoformat()
|
| 754 |
-
}
|
| 755 |
|
|
|
|
|
|
|
| 756 |
@application.get("/run-cycle")
|
| 757 |
async def run_cycle_api():
|
| 758 |
-
"
|
| 759 |
-
if not state_manager.initialization_complete:
|
| 760 |
-
raise HTTPException(status_code=503, detail="الخدمات غير مهيأة بالكامل")
|
| 761 |
asyncio.create_task(run_bot_cycle_async())
|
| 762 |
-
return {"message": "Bot cycle initiated (
|
| 763 |
-
|
| 764 |
@application.get("/health")
|
| 765 |
-
async def health_check():
|
| 766 |
-
"""فحص صحة النظام"""
|
| 767 |
-
services_status = {
|
| 768 |
-
"status": "healthy" if state_manager.initialization_complete else "initializing",
|
| 769 |
-
"initialization_complete": state_manager.initialization_complete,
|
| 770 |
-
"services_initialized": state_manager.services_initialized,
|
| 771 |
-
"initialization_error": state_manager.initialization_error,
|
| 772 |
-
"timestamp": datetime.now().isoformat(),
|
| 773 |
-
"system_architecture": "3-Layer Analysis System (Streaming Pipeline)",
|
| 774 |
-
"layers": {
|
| 775 |
-
"layer1": "Data Manager - Rapid Screening",
|
| 776 |
-
"layer2": "ML Processor - Advanced Analysis (Streaming Consumer)",
|
| 777 |
-
"layer3": "LLM Service - Deep Analysis"
|
| 778 |
-
}
|
| 779 |
-
}
|
| 780 |
-
return services_status
|
| 781 |
-
|
| 782 |
@application.get("/analyze-market")
|
| 783 |
async def analyze_market_api():
|
| 784 |
-
"
|
| 785 |
-
if not state_manager.initialization_complete:
|
| 786 |
-
raise HTTPException(status_code=503, detail="الخدمات غير مهيأة بالكامل")
|
| 787 |
-
|
| 788 |
result = await run_3_layer_analysis()
|
| 789 |
-
if result:
|
| 790 |
-
|
| 791 |
-
"opportunity_found": True,
|
| 792 |
-
"symbol": result['symbol'],
|
| 793 |
-
"action": result['decision'].get('action'),
|
| 794 |
-
"confidence": result['llm_confidence'],
|
| 795 |
-
"strategy": result['strategy']
|
| 796 |
-
}
|
| 797 |
-
else:
|
| 798 |
-
return {"opportunity_found": False, "message": "No suitable opportunities found"}
|
| 799 |
-
|
| 800 |
@application.get("/portfolio")
|
| 801 |
async def get_portfolio_api():
|
| 802 |
-
"
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
try:
|
| 807 |
-
portfolio_state = await r2_service_global.get_portfolio_state_async()
|
| 808 |
-
open_trades = await trade_manager_global.get_open_trades()
|
| 809 |
-
|
| 810 |
-
return {
|
| 811 |
-
"portfolio": portfolio_state,
|
| 812 |
-
"open_trades": open_trades,
|
| 813 |
-
"timestamp": datetime.now().isoformat()
|
| 814 |
-
}
|
| 815 |
-
except Exception as e:
|
| 816 |
-
raise HTTPException(status_code=500, detail=f"خطأ في جلب بيانات المحفظة: {str(e)}")
|
| 817 |
-
|
| 818 |
@application.get("/system-status")
|
| 819 |
-
async def get_system_status():
|
| 820 |
-
"""الحصول على حالة النظام التفصيلية"""
|
| 821 |
-
monitoring_status = trade_manager_global.get_monitoring_status() if trade_manager_global else {}
|
| 822 |
-
|
| 823 |
-
return {
|
| 824 |
-
"initialization_complete": state_manager.initialization_complete,
|
| 825 |
-
"services_initialized": state_manager.services_initialized,
|
| 826 |
-
"initialization_error": state_manager.initialization_error,
|
| 827 |
-
"market_state_ok": state.MARKET_STATE_OK,
|
| 828 |
-
"monitoring_status": monitoring_status,
|
| 829 |
-
"timestamp": datetime.now().isoformat()
|
| 830 |
-
}
|
| 831 |
|
| 832 |
async def cleanup_on_shutdown():
|
| 833 |
-
"""تنظيف الموارد عند الإغلاق"""
|
| 834 |
global r2_service_global, data_manager_global, trade_manager_global, learning_engine_global
|
| 835 |
-
|
| 836 |
print("🛑 Shutdown signal received. Cleaning up...")
|
| 837 |
-
|
| 838 |
-
if trade_manager_global:
|
| 839 |
-
trade_manager_global.stop_monitoring()
|
| 840 |
-
print("✅ Trade monitoring stopped")
|
| 841 |
-
|
| 842 |
if learning_engine_global and learning_engine_global.initialized:
|
| 843 |
-
try:
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
print("✅ Learning engine data saved")
|
| 847 |
-
except Exception as e:
|
| 848 |
-
print(f"❌ Failed to save learning engine data: {e}")
|
| 849 |
-
|
| 850 |
-
if data_manager_global:
|
| 851 |
-
await data_manager_global.close()
|
| 852 |
-
print("✅ Data manager closed")
|
| 853 |
-
|
| 854 |
if r2_service_global:
|
| 855 |
-
try:
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
except Exception as e:
|
| 859 |
-
print(f"❌ Failed to save shutdown log: {e}")
|
| 860 |
-
|
| 861 |
-
if r2_service_global.lock_acquired:
|
| 862 |
-
r2_service_global.release_lock()
|
| 863 |
-
print("✅ R2 lock released")
|
| 864 |
-
|
| 865 |
-
def signal_handler(signum, frame):
|
| 866 |
-
"""معالج إشارات الإغلاق"""
|
| 867 |
-
print(f"🛑 Received signal {signum}. Initiating shutdown...")
|
| 868 |
-
asyncio.create_task(cleanup_on_shutdown())
|
| 869 |
-
sys.exit(0)
|
| 870 |
|
| 871 |
-
|
| 872 |
-
signal.signal(signal.SIGINT, signal_handler)
|
| 873 |
-
signal.signal(signal.SIGTERM, signal_handler)
|
| 874 |
|
| 875 |
if __name__ == "__main__":
|
| 876 |
-
print("🚀 Starting AI Trading Bot with 3-Layer Analysis System (
|
| 877 |
-
uvicorn.run(
|
| 878 |
-
application,
|
| 879 |
-
host="0.0.0.0",
|
| 880 |
-
port=7860,
|
| 881 |
-
log_level="info",
|
| 882 |
-
access_log=True
|
| 883 |
-
)
|
|
|
|
| 16 |
from r2 import R2Service
|
| 17 |
from LLM import LLMService
|
| 18 |
from data_manager import DataManager
|
| 19 |
+
from ml_engine.processor import MLProcessor
|
| 20 |
from learning_engine import LearningEngine
|
| 21 |
from sentiment_news import SentimentAnalyzer
|
| 22 |
from trade_manager import TradeManager
|
|
|
|
| 26 |
print(f"❌ خطأ في استيراد الوحدات: {e}")
|
| 27 |
sys.exit(1)
|
| 28 |
|
| 29 |
+
# (المتغيرات العالمية و StateManager كما هي)
|
| 30 |
+
# ...
|
| 31 |
r2_service_global = None
|
| 32 |
data_manager_global = None
|
| 33 |
llm_service_global = None
|
|
|
|
| 43 |
self.initialization_complete = False
|
| 44 |
self.initialization_error = None
|
| 45 |
self.services_initialized = {
|
| 46 |
+
'r2_service': False, 'data_manager': False, 'llm_service': False,
|
| 47 |
+
'learning_engine': False, 'trade_manager': False, 'sentiment_analyzer': False,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
'symbol_whale_monitor': False
|
| 49 |
}
|
| 50 |
|
| 51 |
async def wait_for_initialization(self, timeout=60):
|
| 52 |
start_time = time.time()
|
| 53 |
while not self.initialization_complete and (time.time() - start_time) < timeout:
|
| 54 |
+
if self.initialization_error: raise Exception(f"فشل التهيئة: {self.initialization_error}")
|
|
|
|
| 55 |
await asyncio.sleep(2)
|
| 56 |
+
if not self.initialization_complete: raise Exception(f"انتهت مهلة التهيئة ({timeout} ثانية)")
|
|
|
|
|
|
|
|
|
|
| 57 |
return self.initialization_complete
|
| 58 |
|
| 59 |
def set_service_initialized(self, service_name):
|
|
|
|
| 68 |
|
| 69 |
state_manager = StateManager()
|
| 70 |
|
| 71 |
+
# (initialize_services و monitor_market_async كما هي)
|
| 72 |
+
# ...
|
| 73 |
async def initialize_services():
|
| 74 |
"""تهيئة جميع الخدمات بشكل منفصل"""
|
| 75 |
global r2_service_global, data_manager_global, llm_service_global
|
| 76 |
global learning_engine_global, trade_manager_global, sentiment_analyzer_global
|
| 77 |
global symbol_whale_monitor_global
|
|
|
|
| 78 |
try:
|
| 79 |
print("🚀 بدء تهيئة الخدمات...")
|
| 80 |
+
print(" 🔄 تهيئة R2Service..."); r2_service_global = R2Service(); state_manager.set_service_initialized('r2_service'); print(" ✅ R2Service مهيأة")
|
| 81 |
+
print(" 🔄 جلب قاعدة بيانات العقود..."); contracts_database = await r2_service_global.load_contracts_db_async(); print(f" ✅ تم تحميل {len(contracts_database)} عقد")
|
| 82 |
+
print(" 🔄 تهيئة مراقب الحيتان...");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
try:
|
| 84 |
from whale_news_data import EnhancedWhaleMonitor
|
| 85 |
symbol_whale_monitor_global = EnhancedWhaleMonitor(contracts_database, r2_service_global)
|
| 86 |
+
state_manager.set_service_initialized('symbol_whale_monitor'); print(" ✅ مراقب الحيتان مهيأ")
|
| 87 |
+
except Exception as e: print(f" ⚠️ فشل تهيئة مراقب الحيتان: {e}"); symbol_whale_monitor_global = None
|
| 88 |
+
print(" 🔄 تهيئة DataManager..."); data_manager_global = DataManager(contracts_database, symbol_whale_monitor_global); await data_manager_global.initialize(); state_manager.set_service_initialized('data_manager'); print(" ✅ DataManager مهيأة")
|
| 89 |
+
print(" 🔄 تهيئة LLMService..."); llm_service_global = LLMService(); llm_service_global.r2_service = r2_service_global; state_manager.set_service_initialized('llm_service'); print(" ✅ LLMService مهيأة")
|
| 90 |
+
print(" 🔄 تهيئة محلل المشاعر..."); sentiment_analyzer_global = SentimentAnalyzer(data_manager_global); state_manager.set_service_initialized('sentiment_analyzer'); print(" ✅ محلل المشاعر مهيأ")
|
| 91 |
+
print(" 🔄 تهيئة محرك التعلم..."); learning_engine_global = LearningEngine(r2_service_global, data_manager_global); await learning_engine_global.initialize_enhanced(); state_manager.set_service_initialized('learning_engine'); print(" ✅ محرك التعلم مهيأ")
|
| 92 |
+
print(" 🔄 تهيئة مدير الصفقات..."); trade_manager_global = TradeManager(r2_service_global, learning_engine_global, data_manager_global); state_manager.set_service_initialized('trade_manager'); print(" ✅ مدير الصفقات مهيأ")
|
| 93 |
+
print("🎯 اكتملت تهيئة جميع الخدمات بنجاح"); return True
|
| 94 |
+
except Exception as e: error_msg = f"فشل تهيئة الخدمات: {str(e)}"; print(f"❌ {error_msg}"); state_manager.set_initialization_error(error_msg); return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
async def monitor_market_async():
|
| 97 |
"""مراقبة السوق"""
|
| 98 |
global data_manager_global, sentiment_analyzer_global
|
|
|
|
| 99 |
try:
|
| 100 |
+
if not await state_manager.wait_for_initialization(): print("❌ فشل تهيئة الخدمات - إيقاف مراقبة السوق"); return
|
|
|
|
|
|
|
|
|
|
| 101 |
while True:
|
| 102 |
try:
|
| 103 |
async with state_manager.market_analysis_lock:
|
| 104 |
market_context = await sentiment_analyzer_global.get_market_sentiment()
|
| 105 |
+
if not market_context: state.MARKET_STATE_OK = True; await asyncio.sleep(60); continue
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
bitcoin_sentiment = market_context.get('btc_sentiment')
|
| 107 |
fear_greed_index = market_context.get('fear_and_greed_index')
|
|
|
|
| 108 |
should_halt_trading, halt_reason = False, ""
|
| 109 |
+
if bitcoin_sentiment == 'BEARISH' and (fear_greed_index is not None and fear_greed_index < 30): should_halt_trading, halt_reason = True, "ظروف سوق هابطة"
|
| 110 |
+
if should_halt_trading: state.MARKET_STATE_OK = False; await r2_service_global.save_system_logs_async({"market_halt": True, "reason": halt_reason})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
else:
|
| 112 |
+
if not state.MARKET_STATE_OK: print("✅ تحسنت ظروف السوق. استئناف العمليات العادية.")
|
|
|
|
| 113 |
state.MARKET_STATE_OK = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
await asyncio.sleep(60)
|
| 115 |
+
except Exception as error: print(f"❌ خطأ أثناء مراقبة السوق: {error}"); state.MARKET_STATE_OK = True; await asyncio.sleep(60)
|
| 116 |
+
except Exception as e: print(f"❌ فشل تشغيل مراقبة السوق: {e}")
|
| 117 |
|
| 118 |
|
| 119 |
+
# 🔴 --- تعديل: إزالة Semaphore من هنا --- 🔴
|
| 120 |
+
# منظم السرعة الآن داخل مهمة جلب الحيتان ومهمة معالجة ML
|
| 121 |
+
async def process_batch_parallel(batch, ml_processor, batch_num, total_batches, preloaded_whale_data):
|
|
|
|
| 122 |
"""
|
| 123 |
(معدلة) معالجة دفعة من الرموز بشكل متوازي وإرجاع نتائج مفصلة
|
| 124 |
+
- تستخدم بيانات الحيتان المحملة مسبقًا
|
| 125 |
+
- لا تحتوي على Semaphore خاص بها (يعتمد على Semaphore داخل MLProcessor)
|
| 126 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
try:
|
| 128 |
+
# Reduced logging for clarity
|
| 129 |
+
# print(f" 🔄 [المستهلك] بدء معالجة الدفعة {batch_num}/{total_batches} ({len(batch)} عملة)...")
|
| 130 |
|
| 131 |
batch_tasks = []
|
| 132 |
for symbol_data in batch:
|
| 133 |
+
# 🔴 تمرير بيانات الحيتان المحملة مسبقًا
|
| 134 |
+
task = asyncio.create_task(ml_processor.process_multiple_symbols_parallel([symbol_data], preloaded_whale_data)) # Pass whale data
|
| 135 |
batch_tasks.append(task)
|
| 136 |
|
| 137 |
+
# انتظار النتائج (process_multiple_symbols_parallel يعيد قائمة)
|
| 138 |
+
batch_results_list_of_lists = await asyncio.gather(*batch_tasks, return_exceptions=True)
|
| 139 |
|
| 140 |
successful_results = []
|
| 141 |
low_score_results = []
|
| 142 |
failed_results = []
|
| 143 |
|
| 144 |
+
# Flatten the results and handle errors
|
| 145 |
+
for i, result_list in enumerate(batch_results_list_of_lists):
|
| 146 |
symbol = batch[i].get('symbol', 'unknown')
|
| 147 |
+
if isinstance(result_list, Exception):
|
| 148 |
+
failed_results.append({"symbol": symbol, "error": f"Task Execution Error: {str(result_list)}"})
|
| 149 |
+
continue
|
| 150 |
|
| 151 |
+
# Since we process one symbol at a time in the task, result_list should contain 0 or 1 item
|
| 152 |
+
if result_list:
|
| 153 |
+
result = result_list[0] # Get the actual result dictionary
|
| 154 |
+
if isinstance(result, dict): # Check if it's a valid dict
|
| 155 |
+
if result.get('enhanced_final_score', 0) > 0.4:
|
| 156 |
+
successful_results.append(result)
|
| 157 |
+
else:
|
| 158 |
+
low_score_results.append(result)
|
| 159 |
+
else:
|
| 160 |
+
# Handle cases where process_multiple_symbols_parallel might return non-dict
|
| 161 |
+
failed_results.append({"symbol": symbol, "error": f"ML processor returned invalid type: {type(result)}"})
|
| 162 |
else:
|
| 163 |
+
# Handle cases where processing returned None or empty list
|
| 164 |
+
failed_results.append({"symbol": symbol, "error": "ML processing returned None or empty list"})
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# print(f" ✅ [المستهلك] اكتملت معالجة الدفعة {batch_num}: {len(successful_results)} نجاح | {len(low_score_results)} منخفض | {len(failed_results)} فشل") # Reduced logging
|
| 168 |
|
| 169 |
+
return {'success': successful_results, 'low_score': low_score_results, 'failures': failed_results}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
except Exception as error:
|
| 172 |
print(f"❌ [المستهلك] خطأ في معالجة الدفعة {batch_num}: {error}")
|
| 173 |
return {'success': [], 'low_score': [], 'failures': []}
|
|
|
|
| 174 |
|
| 175 |
|
| 176 |
+
# 🔴 --- بدء التعديل الجوهري --- 🔴
|
| 177 |
+
# تم إعادة هيكلة هذه الدالة بالكامل
|
| 178 |
async def run_3_layer_analysis():
|
| 179 |
"""
|
| 180 |
+
(معدلة) تشغيل النظام الطبقي (مع فصل جلب بيانات الحيتان)
|
| 181 |
الطبقة 1: data_manager - الفحص السريع
|
| 182 |
+
الطبقة 1.5: جلب بيانات الحيتان بشكل منفصل (غير معرقل)
|
| 183 |
+
الطبقة 2: MLProcessor - التحليل المتدفق (يستخدم بيانات الحيتان المحملة)
|
| 184 |
الطبقة 3: LLMService - النموذج الضخم
|
| 185 |
"""
|
| 186 |
|
|
|
|
| 190 |
all_failed_candidates = []
|
| 191 |
final_layer2_candidates = []
|
| 192 |
final_opportunities = []
|
| 193 |
+
preloaded_whale_data_dict = {} # لتخزين بيانات الحيتان
|
| 194 |
|
| 195 |
try:
|
| 196 |
+
print("🎯 بدء النظام الطبقي المكون من 3 طبقات (مع فصل جلب الحيتان)...")
|
| 197 |
|
| 198 |
+
if not await state_manager.wait_for_initialization(): print("❌ الخدمات غير مهيأة بالكامل"); return None
|
|
|
|
|
|
|
| 199 |
|
| 200 |
+
# الطبقة 1: الفحص السريع (لا تغيير)
|
| 201 |
print("\n🔍 الطبقة 1: الفحص السريع (data_manager)...")
|
| 202 |
layer1_candidates = await data_manager_global.layer1_rapid_screening()
|
| 203 |
+
if not layer1_candidates: print("❌ لم يتم العثور على مرشحين في الطبقة 1"); return None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
print(f"✅ تم اختيار {len(layer1_candidates)} عملة للطبقة 2")
|
| 205 |
+
layer1_symbols = [c['symbol'] for c in layer1_candidates]
|
| 206 |
+
|
| 207 |
+
# 🔴 --- الطبقة 1.5: جلب بيانات الحيتان بشكل منفصل وغير معرقل --- 🔴
|
| 208 |
+
start_whale_fetch = time.time()
|
| 209 |
+
print(f"\n🐋 الطبقة 1.5: بدء جلب بيانات الحيتان لـ {len(layer1_symbols)} عملة (بشكل غير معرقل)...")
|
| 210 |
+
|
| 211 |
+
# مهمة جلب بيانات الحيتان
|
| 212 |
+
async def fetch_whale_data_task(symbols, results_dict):
|
| 213 |
+
# استخدام منظم سرعة خاص لهذه المهمة (يمكن تعديل القيمة حسب الحاجة)
|
| 214 |
+
WHALE_FETCH_CONCURRENCY = 3 # عدد طلبات الح��تان المتزامنة
|
| 215 |
+
semaphore = asyncio.Semaphore(WHALE_FETCH_CONCURRENCY)
|
| 216 |
+
tasks = []
|
| 217 |
+
|
| 218 |
+
async def get_data_with_semaphore(symbol):
|
| 219 |
+
async with semaphore:
|
| 220 |
+
try:
|
| 221 |
+
data = await data_manager_global.get_whale_data_for_symbol(symbol)
|
| 222 |
+
if data:
|
| 223 |
+
results_dict[symbol] = data
|
| 224 |
+
# else: # Optional: Log if data is None
|
| 225 |
+
# print(f" ⚠️ [Whale Fetch] No whale data returned for {symbol}")
|
| 226 |
+
except Exception as e:
|
| 227 |
+
print(f" ❌ [Whale Fetch] فشل جلب بيانات الحيتان لـ {symbol}: {e}")
|
| 228 |
+
results_dict[symbol] = {'data_available': False, 'error': str(e)} # Store error
|
| 229 |
+
|
| 230 |
+
for symbol in symbols:
|
| 231 |
+
tasks.append(asyncio.create_task(get_data_with_semaphore(symbol)))
|
| 232 |
+
|
| 233 |
+
await asyncio.gather(*tasks) # انتظار اكتمال جميع مهام جلب الحيتان
|
| 234 |
|
| 235 |
+
# تشغيل مهمة جلب الحيتان في الخلفية (لا ننتظرها هنا)
|
| 236 |
+
whale_fetcher_task = asyncio.create_task(fetch_whale_data_task(layer1_symbols, preloaded_whale_data_dict))
|
| 237 |
+
print(" ⏳ مهمة جلب بيانات الحيتان تعمل في الخلفية...")
|
| 238 |
+
# 🔴 --- نهاية الطبقة 1.5 --- 🔴
|
| 239 |
|
| 240 |
+
# --- إعداد نموذج المنتج والمستهلك لبيانات OHLCV والتحليل ---
|
| 241 |
DATA_QUEUE_MAX_SIZE = 2
|
| 242 |
ohlcv_data_queue = asyncio.Queue(maxsize=DATA_QUEUE_MAX_SIZE)
|
|
|
|
|
|
|
| 243 |
ml_results_list = []
|
|
|
|
|
|
|
| 244 |
market_context = await data_manager_global.get_market_context_async()
|
| 245 |
ml_processor = MLProcessor(market_context, data_manager_global, learning_engine_global)
|
| 246 |
+
batch_size = 15
|
|
|
|
|
|
|
| 247 |
total_batches = (len(layer1_candidates) + batch_size - 1) // batch_size
|
| 248 |
+
print(f" 🚀 إعداد المنتج/المستهلك (OHLCV/ML): {total_batches} دفعة متوقعة (بحجم {batch_size})")
|
|
|
|
| 249 |
|
| 250 |
+
# وظيفة المستهلك (ML Consumer) - معدلة لتمرير بيانات الحيتان
|
| 251 |
+
async def ml_consumer_task(queue: asyncio.Queue, results_list: list, whale_data_store: dict):
|
| 252 |
batch_num = 0
|
| 253 |
while True:
|
| 254 |
try:
|
|
|
|
| 255 |
batch_data = await queue.get()
|
| 256 |
+
if batch_data is None: queue.task_done(); print(" 🛑 [ML Consumer] تلقى إشارة التوقف."); break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
batch_num += 1
|
| 259 |
+
print(f" 📬 [ML Consumer] استلم دفعة OHLCV {batch_num}/{total_batches} ({len(batch_data)} عملة)")
|
| 260 |
|
| 261 |
+
# 🔴 تمرير قاموس بيانات الحيتان إلى دالة المعالجة
|
| 262 |
batch_results_dict = await process_batch_parallel(
|
| 263 |
+
batch_data, ml_processor, batch_num, total_batches, whale_data_store
|
| 264 |
)
|
| 265 |
|
| 266 |
results_list.append(batch_results_dict)
|
|
|
|
|
|
|
| 267 |
queue.task_done()
|
| 268 |
+
print(f" ✅ [ML Consumer] أكمل معالجة الدفعة {batch_num}/{total_batches}") # Added completion log
|
| 269 |
|
| 270 |
except Exception as e:
|
| 271 |
+
print(f"❌ [ML Consumer] خطأ فادح: {e}"); traceback.print_exc(); queue.task_done()
|
|
|
|
|
|
|
| 272 |
|
| 273 |
+
# تشغيل المستهلك (ML Consumer)
|
| 274 |
+
print(" ▶️ [ML Consumer] بدء تشغيل مهمة المستهلك...")
|
| 275 |
+
consumer_task = asyncio.create_task(ml_consumer_task(ohlcv_data_queue, ml_results_list, preloaded_whale_data_dict))
|
| 276 |
|
| 277 |
+
# تشغيل المنتج (OHLCV Producer)
|
| 278 |
+
print(" ▶️ [OHLCV Producer] بدء تشغيل مهمة المنتج (تدفق بيانات OHLCV)...")
|
|
|
|
| 279 |
producer_task = asyncio.create_task(
|
| 280 |
data_manager_global.stream_ohlcv_data(layer1_symbols, ohlcv_data_queue)
|
| 281 |
)
|
| 282 |
|
| 283 |
+
# انتظار انتهاء المنتج (OHLCV Producer)
|
| 284 |
await producer_task
|
| 285 |
+
print(" ✅ [OHLCV Producer] أنهى جلب جميع بيانات OHLCV.")
|
| 286 |
|
| 287 |
+
# إرسال إشارة التوقف للمستهلك (ML Consumer)
|
| 288 |
await ohlcv_data_queue.put(None)
|
| 289 |
|
| 290 |
+
# انتظار انتهاء المستهلك (ML Consumer)
|
| 291 |
+
await ohlcv_data_queue.join()
|
| 292 |
+
await consumer_task
|
| 293 |
+
print(" ✅ [ML Consumer] أنهى معالجة جميع الدفعات.")
|
| 294 |
+
|
| 295 |
+
# 🔴 انتظار انتهاء مهمة جلب بيانات الحيتان (التي كانت تعمل في الخلفية)
|
| 296 |
+
print(" ⏳ انتظار اكتمال مهمة جلب بيانات الحيتان...")
|
| 297 |
+
await whale_fetcher_task
|
| 298 |
+
end_whale_fetch = time.time()
|
| 299 |
+
print(f" ✅ اكتمل جلب بيانات الحيتان في {end_whale_fetch - start_whale_fetch:.2f} ثانية. تم جلب بيانات لـ {len(preloaded_whale_data_dict)} عملة.")
|
| 300 |
+
# --- نهاية نموذج المنتج والمستهلك ---
|
| 301 |
|
| 302 |
+
# 9. تجميع النتائج (كما كان، لكن بيانات الحيتان موجودة الآن)
|
| 303 |
print("🔄 تجميع جميع النتائج...")
|
| 304 |
+
# ... (الكود لتجميع layer2_candidates, all_low_score_candidates, all_failed_candidates كما هو) ...
|
| 305 |
for batch_result in ml_results_list:
|
|
|
|
| 306 |
for success_item in batch_result['success']:
|
| 307 |
symbol = success_item['symbol']
|
| 308 |
l1_data = next((c for c in layer1_candidates if c['symbol'] == symbol), None)
|
| 309 |
if l1_data:
|
| 310 |
success_item['reasons_for_candidacy'] = l1_data.get('reasons', [])
|
| 311 |
success_item['layer1_score'] = l1_data.get('layer1_score', 0)
|
| 312 |
+
# Ensure whale data from preloading is in the final result item
|
| 313 |
+
if symbol in preloaded_whale_data_dict:
|
| 314 |
+
success_item['whale_data'] = preloaded_whale_data_dict[symbol]
|
| 315 |
+
elif 'whale_data' not in success_item: # If ML processor didn't add a default
|
| 316 |
+
success_item['whale_data'] = {'data_available': False, 'reason': 'Failed during preload'}
|
| 317 |
layer2_candidates.append(success_item)
|
|
|
|
| 318 |
all_low_score_candidates.extend(batch_result['low_score'])
|
| 319 |
all_failed_candidates.extend(batch_result['failures'])
|
| 320 |
+
|
| 321 |
+
|
| 322 |
print(f"✅ اكتمل التحليل المتقدم: {len(layer2_candidates)} نجاح (عالي) | {len(all_low_score_candidates)} نجاح (منخفض) | {len(all_failed_candidates)} فشل")
|
| 323 |
|
| 324 |
+
if not layer2_candidates: print("❌ لم يتم العثور على مرشحين في الطبقة 2")
|
|
|
|
|
|
|
| 325 |
|
| 326 |
+
# 10. الترتيب والفلترة (كما كان)
|
| 327 |
layer2_candidates.sort(key=lambda x: x.get('enhanced_final_score', 0), reverse=True)
|
| 328 |
target_count = min(10, len(layer2_candidates))
|
| 329 |
final_layer2_candidates = layer2_candidates[:target_count]
|
|
|
|
| 330 |
print(f"🎯 تم اختيار {len(final_layer2_candidates)} عملة للطبقة 3 (الأقوى فقط)")
|
|
|
|
| 331 |
await r2_service_global.save_candidates_async(final_layer2_candidates)
|
|
|
|
| 332 |
print("\n🏆 أفضل 10 عملات من الطبقة 2:")
|
| 333 |
+
# ... (كود عرض أفضل 10 كما هو، سيشمل بيانات الحيتان الآن) ...
|
| 334 |
for i, candidate in enumerate(final_layer2_candidates):
|
| 335 |
score = candidate.get('enhanced_final_score', 0)
|
| 336 |
strategy = candidate.get('target_strategy', 'GENERIC')
|
| 337 |
+
mc_score = candidate.get('monte_carlo_probability')
|
| 338 |
pattern = candidate.get('pattern_analysis', {}).get('pattern_detected', 'no_pattern')
|
| 339 |
timeframes = candidate.get('successful_timeframes', 0)
|
| 340 |
+
symbol = candidate.get('symbol', 'UNKNOWN')
|
| 341 |
+
|
| 342 |
+
print(f" {i+1}. {symbol}: 📊 {score:.3f} | الأطر: {timeframes}/6")
|
| 343 |
+
if mc_score is not None: print(f" 🎯 مونت كارلو: {mc_score:.3f}")
|
|
|
|
| 344 |
print(f" 🎯 استراتيجية: {strategy} | نمط: {pattern}")
|
| 345 |
+
whale_data = candidate.get('whale_data')
|
| 346 |
+
if whale_data and whale_data.get('data_available'):
|
| 347 |
+
signal = whale_data.get('trading_signal', {})
|
| 348 |
+
print(f" 🐋 حيتان: {signal.get('action', 'HOLD')} (ثقة: {signal.get('confidence', 0):.2f}){' ⚠️' if signal.get('critical_alert') else ''}")
|
| 349 |
+
elif whale_data and whale_data.get('error'):
|
| 350 |
+
print(f" 🐋 حيتان: خطأ ({whale_data.get('error')[:50]}...)")
|
| 351 |
+
# else:
|
| 352 |
+
# print(f" 🐋 حيتان: غير متاحة")
|
| 353 |
+
|
| 354 |
|
| 355 |
+
# 11. الطبقة 3: التحليل بالنموذج الضخم (كما كان)
|
| 356 |
print("\n🧠 الطبقة 3: التحليل بالنموذج الضخم (LLMService)...")
|
| 357 |
+
# ... (كود الطبقة 3 كما هو) ...
|
| 358 |
for candidate in final_layer2_candidates:
|
| 359 |
try:
|
| 360 |
symbol = candidate['symbol']
|
| 361 |
print(f" 🤔 تحليل {symbol} بالنموذج الضخم...")
|
|
|
|
| 362 |
ohlcv_data = candidate.get('ohlcv')
|
| 363 |
+
if not ohlcv_data: print(f" ⚠️ لا توجد بيانات شموع لـ {symbol}"); continue
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
candidate['raw_ohlcv'] = ohlcv_data
|
|
|
|
| 365 |
timeframes_count = candidate.get('successful_timeframes', 0)
|
| 366 |
total_candles = sum(len(data) for data in ohlcv_data.values()) if ohlcv_data else 0
|
| 367 |
+
if total_candles < 30: print(f" ⚠️ بيانات شموع غير كافية لـ {symbol}: {total_candles} شمعة فقط"); continue
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
print(f" 📊 إرسال {symbol} للنموذج: {total_candles} شمعة في {timeframes_count} إطار زمني")
|
| 369 |
+
llm_analysis = await llm_service_global.get_trading_decision(candidate) # candidate now includes whale_data
|
| 370 |
+
if llm_analysis and llm_analysis.get('action') in ['BUY']: # Adjusted for SPOT only
|
|
|
|
|
|
|
| 371 |
opportunity = {
|
| 372 |
+
'symbol': symbol, 'current_price': candidate.get('current_price', 0),
|
| 373 |
+
'decision': llm_analysis, 'enhanced_score': candidate.get('enhanced_final_score', 0),
|
|
|
|
|
|
|
| 374 |
'llm_confidence': llm_analysis.get('confidence_level', 0),
|
| 375 |
'strategy': llm_analysis.get('strategy', 'GENERIC'),
|
| 376 |
'analysis_timestamp': datetime.now().isoformat(),
|
| 377 |
+
'timeframes_count': timeframes_count, 'total_candles': total_candles
|
|
|
|
| 378 |
}
|
| 379 |
final_opportunities.append(opportunity)
|
|
|
|
| 380 |
print(f" ✅ {symbol}: {llm_analysis.get('action')} - ثقة: {llm_analysis.get('confidence_level', 0):.2f}")
|
| 381 |
else:
|
| 382 |
action = llm_analysis.get('action', 'NO_DECISION') if llm_analysis else 'NO_RESPONSE'
|
| 383 |
print(f" ⚠️ {symbol}: لا يوجد قرار تداول من النموذج الضخم ({action})")
|
| 384 |
+
except Exception as e: print(f"❌ خطأ في تحليل النموذج الضخم لـ {candidate.get('symbol')}: {e}"); continue
|
| 385 |
+
|
| 386 |
+
|
|
|
|
|
|
|
| 387 |
if final_opportunities:
|
| 388 |
final_opportunities.sort(key=lambda x: (x['llm_confidence'] + x['enhanced_score']) / 2, reverse=True)
|
| 389 |
print(f"\n🏆 النظام الطبقي اكتمل: {len(final_opportunities)} فرصة تداول")
|
| 390 |
for i, opportunity in enumerate(final_opportunities[:5]):
|
| 391 |
print(f" {i+1}. {opportunity['symbol']}: {opportunity['decision'].get('action')} - ثقة: {opportunity['llm_confidence']:.2f} - أطر: {opportunity['timeframes_count']}")
|
| 392 |
|
| 393 |
+
# 12. سجل التدقيق (كما كان)
|
| 394 |
try:
|
| 395 |
+
# ... (كود سجل التدقيق كما هو، سيستخدم البيانات المجمعة الآن) ...
|
| 396 |
top_10_detailed_summary = []
|
| 397 |
for c in final_layer2_candidates:
|
| 398 |
whale_summary = "Not Available"
|
| 399 |
+
whale_data = c.get('whale_data') # Already preloaded
|
| 400 |
if whale_data and whale_data.get('data_available'):
|
| 401 |
signal = whale_data.get('trading_signal', {})
|
| 402 |
action = signal.get('action', 'HOLD')
|
| 403 |
confidence = signal.get('confidence', 0)
|
| 404 |
reason_preview = signal.get('reason', 'N/A')[:75] + "..." if signal.get('reason') else 'N/A'
|
| 405 |
whale_summary = f"Action: {action}, Conf: {confidence:.2f}, Alert: {signal.get('critical_alert', False)}, Reason: {reason_preview}"
|
| 406 |
+
elif whale_data and whale_data.get('error'):
|
| 407 |
+
whale_summary = f"Error: {whale_data['error'][:50]}..."
|
| 408 |
+
|
| 409 |
top_10_detailed_summary.append({
|
| 410 |
+
"symbol": c.get('symbol'), "score": c.get('enhanced_final_score', 0),
|
|
|
|
| 411 |
"timeframes": f"{c.get('successful_timeframes', 'N/A')}/6",
|
| 412 |
+
"whale_data_summary": whale_summary, "strategy": c.get('target_strategy', 'N/A'),
|
|
|
|
| 413 |
"pattern": c.get('pattern_analysis', {}).get('pattern_detected', 'N/A'),
|
| 414 |
})
|
|
|
|
| 415 |
other_successful_candidates = layer2_candidates[target_count:]
|
| 416 |
+
other_success_summary = [{"symbol": c['symbol'], "score": c.get('enhanced_final_score', 0), "timeframes": f"{c.get('successful_timeframes', 'N/A')}/6", "whale_data": "Available" if c.get('whale_data', {}).get('data_available') else ("Error" if c.get('whale_data', {}).get('error') else "Not Available")} for c in other_successful_candidates]
|
| 417 |
+
low_score_summary = [{"symbol": c['symbol'], "score": c.get('enhanced_final_score', 0), "timeframes": f"{c.get('successful_timeframes', 'N/A')}/6", "whale_data": "Available" if c.get('whale_data', {}).get('data_available') else ("Error" if c.get('whale_data', {}).get('error') else "Not Available")} for c in all_low_score_candidates]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
audit_data = {
|
| 419 |
+
"timestamp": datetime.now().isoformat(), "total_layer1_candidates": len(layer1_candidates),
|
|
|
|
| 420 |
"total_processed_in_layer2": len(layer2_candidates) + len(all_low_score_candidates) + len(all_failed_candidates),
|
| 421 |
+
"counts": {"sent_to_llm": len(final_layer2_candidates), "success_not_top_10": len(other_successful_candidates), "success_low_score": len(all_low_score_candidates), "failures": len(all_failed_candidates)},
|
| 422 |
+
"top_candidates_for_llm": top_10_detailed_summary, "other_successful_candidates": other_success_summary,
|
| 423 |
+
"low_score_candidates": low_score_summary, "failed_candidates": all_failed_candidates,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
}
|
|
|
|
| 425 |
await r2_service_global.save_analysis_audit_log_async(audit_data)
|
| 426 |
print(f"✅ تم حفظ سجل تدقيق التحليل في R2.")
|
| 427 |
+
except Exception as audit_error: print(f"❌ فشل حفظ سجل تدقيق التحليل: {audit_error}"); traceback.print_exc()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
|
| 429 |
+
if not final_opportunities: print("❌ لم يتم العثور على فرص تداول مناسبة"); return None
|
| 430 |
return final_opportunities[0] if final_opportunities else None
|
| 431 |
|
| 432 |
except Exception as error:
|
| 433 |
+
print(f"❌ خطأ فادح في النظام الطبقي: {error}"); traceback.print_exc()
|
| 434 |
+
try: # Log partial audit on failure
|
| 435 |
+
audit_data = { "timestamp": datetime.now().isoformat(), "status": "FAILED", "error": str(error), "traceback": traceback.format_exc(), "total_layer1_candidates": len(layer1_candidates), "counts": {"sent_to_llm": 0, "success_not_top_10": 0, "success_low_score": len(all_low_score_candidates), "failures": len(all_failed_candidates)}, "failed_candidates": all_failed_candidates }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
await r2_service_global.save_analysis_audit_log_async(audit_data)
|
| 437 |
print("⚠️ تم حفظ سجل تدقيق جزئي بعد الفشل.")
|
| 438 |
+
except Exception as audit_fail_error: print(f"❌ فشل حفظ سجل التدقيق أثناء معالجة خطأ آخر: {audit_fail_error}")
|
|
|
|
|
|
|
| 439 |
return None
|
| 440 |
# 🔴 --- نهاية التعديل الجوهري --- 🔴
|
| 441 |
|
| 442 |
+
# (بقية الملف: re_analyze_open_trade_async, run_bot_cycle_async, lifespan, endpoints, cleanup, etc. كما هي)
|
| 443 |
+
# ...
|
| 444 |
async def re_analyze_open_trade_async(trade_data):
|
| 445 |
"""إعادة تحليل الصفقة المفتوحة"""
|
| 446 |
symbol = trade_data.get('symbol')
|
| 447 |
try:
|
| 448 |
async with state_manager.trade_analysis_lock:
|
|
|
|
| 449 |
market_context = await data_manager_global.get_market_context_async()
|
|
|
|
|
|
|
| 450 |
ohlcv_data_list = []
|
| 451 |
temp_queue = asyncio.Queue()
|
|
|
|
| 452 |
await data_manager_global.stream_ohlcv_data([symbol], temp_queue)
|
|
|
|
| 453 |
while not temp_queue.empty():
|
| 454 |
+
batch = await temp_queue.get(); temp_queue.task_done() # Need task_done here too
|
| 455 |
+
if batch: ohlcv_data_list.extend(batch)
|
|
|
|
| 456 |
|
| 457 |
+
if not ohlcv_data_list: print(f"⚠️ فشل جلب بيانات إعادة التحليل لـ {symbol}"); return None
|
|
|
|
|
|
|
|
|
|
| 458 |
ohlcv_data = ohlcv_data_list[0]
|
| 459 |
|
|
|
|
| 460 |
l1_data = await data_manager_global._get_detailed_symbol_data(symbol)
|
| 461 |
+
if l1_data: ohlcv_data.update(l1_data); ohlcv_data['reasons_for_candidacy'] = ['re-analysis']
|
|
|
|
|
|
|
| 462 |
|
| 463 |
+
# 🔴 جلب بيانات الحيتان بشكل منفصل لإعادة التحليل
|
| 464 |
+
re_analysis_whale_data = await data_manager_global.get_whale_data_for_symbol(symbol)
|
| 465 |
+
|
| 466 |
ml_processor = MLProcessor(market_context, data_manager_global, learning_engine_global)
|
| 467 |
+
# 🔴 تمرير بيانات الحيتان للمعالج
|
| 468 |
+
processed_data = await ml_processor.process_and_score_symbol_enhanced(ohlcv_data, {symbol: re_analysis_whale_data} if re_analysis_whale_data else {})
|
| 469 |
|
| 470 |
+
if not processed_data: return None
|
|
|
|
| 471 |
|
| 472 |
processed_data['raw_ohlcv'] = ohlcv_data.get('raw_ohlcv') or ohlcv_data.get('ohlcv')
|
| 473 |
processed_data['ohlcv'] = processed_data['raw_ohlcv']
|
| 474 |
|
|
|
|
| 475 |
re_analysis_decision = await llm_service_global.re_analyze_trade_async(trade_data, processed_data)
|
| 476 |
|
| 477 |
if re_analysis_decision:
|
| 478 |
+
await r2_service_global.save_system_logs_async({ "trade_reanalyzed": True, "symbol": symbol, "action": re_analysis_decision.get('action'), 'strategy': re_analysis_decision.get('strategy', 'GENERIC') })
|
| 479 |
+
return {"symbol": symbol, "decision": re_analysis_decision, "current_price": processed_data.get('current_price')}
|
| 480 |
+
else: return None
|
| 481 |
+
except Exception as error: await r2_service_global.save_system_logs_async({ "reanalysis_error": True, "symbol": symbol, "error": str(error) }); return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
|
| 483 |
async def run_bot_cycle_async():
|
| 484 |
"""دورة التداول الرئيسية"""
|
| 485 |
try:
|
| 486 |
+
if not await state_manager.wait_for_initialization(): print("❌ الخدمات غير مهيأة بالكامل - تخطي الدورة"); return
|
| 487 |
+
print("🔄 بدء دورة التداول..."); await r2_service_global.save_system_logs_async({"cycle_started": True})
|
| 488 |
+
if not r2_service_global.acquire_lock(): print("❌ فشل الحصول على القفل - تخطي الدورة"); return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
try:
|
| 490 |
+
open_trades = await trade_manager_global.get_open_trades(); print(f"📋 الصفقات المفتوحة: {len(open_trades)}")
|
|
|
|
|
|
|
| 491 |
should_look_for_new_trade = len(open_trades) == 0
|
|
|
|
|
|
|
| 492 |
if open_trades:
|
| 493 |
now = datetime.now()
|
| 494 |
+
trades_to_reanalyze = [t for t in open_trades if now >= datetime.fromisoformat(t.get('expected_target_time', now.isoformat()))]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 495 |
if trades_to_reanalyze:
|
| 496 |
print(f"🔄 إعادة تحليل {len(trades_to_reanalyze)} صفقة")
|
| 497 |
for trade in trades_to_reanalyze:
|
| 498 |
result = await re_analyze_open_trade_async(trade)
|
| 499 |
+
if result and result['decision'].get('action') == "CLOSE_TRADE": await trade_manager_global.close_trade(trade, result['current_price'], 'CLOSED_BY_REANALYSIS'); should_look_for_new_trade = True
|
| 500 |
+
elif result and result['decision'].get('action') == "UPDATE_TRADE": await trade_manager_global.update_trade(trade, result['decision'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 501 |
if should_look_for_new_trade:
|
| 502 |
+
portfolio_state = await r2_service_global.get_portfolio_state_async(); current_capital = portfolio_state.get("current_capital_usd", 0)
|
|
|
|
|
|
|
| 503 |
if current_capital > 1:
|
| 504 |
+
print("🎯 البحث عن فرص تداول جديدة (فصل الحيتان)...")
|
| 505 |
best_opportunity = await run_3_layer_analysis()
|
| 506 |
+
if best_opportunity: print(f"✅ فتح صفقة جديدة: {best_opportunity['symbol']}"); await trade_manager_global.open_trade( best_opportunity['symbol'], best_opportunity['decision'], best_opportunity['current_price'])
|
| 507 |
+
else: print("❌ لم يتم العثور على فرص تداول مناسبة")
|
| 508 |
+
else: print("❌ رأس المال غير كافي لفتح صفقات جديدة")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 509 |
finally:
|
| 510 |
+
r2_service_global.release_lock(); await r2_service_global.save_system_logs_async({ "cycle_completed": True, "open_trades": len(open_trades) if 'open_trades' in locals() else 0 }); print("✅ اكتملت دورة التداول")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 511 |
except Exception as error:
|
| 512 |
+
print(f"❌ Unhandled error in main cycle: {error}"); await r2_service_global.save_system_logs_async({ "cycle_error": True, "error": str(error) });
|
| 513 |
+
if r2_service_global and r2_service_global.lock_acquired: r2_service_global.release_lock() # Ensure lock release on error
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 514 |
|
| 515 |
@asynccontextmanager
|
| 516 |
async def lifespan(application: FastAPI):
|
| 517 |
"""إدارة دورة حياة التطبيق"""
|
| 518 |
print("🚀 بدء تهيئة التطبيق...")
|
|
|
|
| 519 |
try:
|
|
|
|
| 520 |
success = await initialize_services()
|
| 521 |
+
if not success: print("❌ فشل تهيئة التطبيق - إغلاق..."); yield; return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 522 |
asyncio.create_task(monitor_market_async())
|
| 523 |
asyncio.create_task(trade_manager_global.start_trade_monitoring())
|
|
|
|
| 524 |
await r2_service_global.save_system_logs_async({"application_started": True})
|
| 525 |
+
print("🎯 التطبيق جاهز للعمل - نظام الطبقات 3 فعال (فصل الحيتان)")
|
|
|
|
| 526 |
yield
|
| 527 |
+
except Exception as error: print(f"❌ Application startup failed: {error}"); traceback.print_exc();
|
| 528 |
+
if r2_service_global: await r2_service_global.save_system_logs_async({ "application_startup_failed": True, "error": str(error) }); raise
|
| 529 |
+
finally: await cleanup_on_shutdown()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 530 |
|
| 531 |
+
application = FastAPI(lifespan=lifespan, title="AI Trading Bot", description="نظام تداول ذكي بثلاث طبقات تحليلية (فصل الحيتان)", version="3.2.0")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 532 |
|
| 533 |
+
@application.get("/")
|
| 534 |
+
async def root(): return {"message": "مرحباً بك في نظام التداول الذكي", "system": "3-Layer Analysis System (Whale Fetch Decoupled)", "status": "running" if state_manager.initialization_complete else "initializing", "timestamp": datetime.now().isoformat()}
|
| 535 |
@application.get("/run-cycle")
|
| 536 |
async def run_cycle_api():
|
| 537 |
+
if not state_manager.initialization_complete: raise HTTPException(status_code=503, detail="الخدمات غير مهيأة بالكامل")
|
|
|
|
|
|
|
| 538 |
asyncio.create_task(run_bot_cycle_async())
|
| 539 |
+
return {"message": "Bot cycle initiated (Whale Fetch Decoupled)", "system": "3-Layer Analysis"}
|
|
|
|
| 540 |
@application.get("/health")
|
| 541 |
+
async def health_check(): return {"status": "healthy" if state_manager.initialization_complete else "initializing", "initialization_complete": state_manager.initialization_complete, "services_initialized": state_manager.services_initialized, "initialization_error": state_manager.initialization_error, "timestamp": datetime.now().isoformat(), "system_architecture": "3-Layer Analysis System (Whale Fetch Decoupled)", "layers": {"layer1": "Data Manager - Rapid Screening", "layer1.5": "Whale Data Fetcher (Async)", "layer2": "ML Processor - Streaming Consumer", "layer3": "LLM Service - Deep Analysis"}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 542 |
@application.get("/analyze-market")
|
| 543 |
async def analyze_market_api():
|
| 544 |
+
if not state_manager.initialization_complete: raise HTTPException(status_code=503, detail="الخدمات غير مهيأة بالكامل")
|
|
|
|
|
|
|
|
|
|
| 545 |
result = await run_3_layer_analysis()
|
| 546 |
+
if result: return {"opportunity_found": True, "symbol": result['symbol'], "action": result['decision'].get('action'), "confidence": result['llm_confidence'], "strategy": result['strategy']}
|
| 547 |
+
else: return {"opportunity_found": False, "message": "No suitable opportunities found"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
@application.get("/portfolio")
|
| 549 |
async def get_portfolio_api():
|
| 550 |
+
if not state_manager.initialization_complete: raise HTTPException(status_code=503, detail="الخدمات غير مهيأة بالكامل")
|
| 551 |
+
try: portfolio_state = await r2_service_global.get_portfolio_state_async(); open_trades = await trade_manager_global.get_open_trades(); return {"portfolio": portfolio_state, "open_trades": open_trades, "timestamp": datetime.now().isoformat()}
|
| 552 |
+
except Exception as e: raise HTTPException(status_code=500, detail=f"خطأ في جلب بيانات المحفظة: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
@application.get("/system-status")
|
| 554 |
+
async def get_system_status(): monitoring_status = trade_manager_global.get_monitoring_status() if trade_manager_global else {}; return {"initialization_complete": state_manager.initialization_complete, "services_initialized": state_manager.services_initialized, "initialization_error": state_manager.initialization_error, "market_state_ok": state.MARKET_STATE_OK, "monitoring_status": monitoring_status, "timestamp": datetime.now().isoformat()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 555 |
|
| 556 |
async def cleanup_on_shutdown():
|
|
|
|
| 557 |
global r2_service_global, data_manager_global, trade_manager_global, learning_engine_global
|
|
|
|
| 558 |
print("🛑 Shutdown signal received. Cleaning up...")
|
| 559 |
+
if trade_manager_global: trade_manager_global.stop_monitoring(); print("✅ Trade monitoring stopped")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 560 |
if learning_engine_global and learning_engine_global.initialized:
|
| 561 |
+
try: await learning_engine_global.save_weights_to_r2(); await learning_engine_global.save_performance_history(); print("✅ Learning engine data saved")
|
| 562 |
+
except Exception as e: print(f"❌ Failed to save learning engine data: {e}")
|
| 563 |
+
if data_manager_global: await data_manager_global.close(); print("✅ Data manager closed")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 564 |
if r2_service_global:
|
| 565 |
+
try: await r2_service_global.save_system_logs_async({"application_shutdown": True}); print("✅ Shutdown log saved")
|
| 566 |
+
except Exception as e: print(f"❌ Failed to save shutdown log: {e}")
|
| 567 |
+
if r2_service_global.lock_acquired: r2_service_global.release_lock(); print("✅ R2 lock released")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
|
| 569 |
+
def signal_handler(signum, frame): print(f"🛑 Received signal {signum}. Initiating shutdown..."); asyncio.create_task(cleanup_on_shutdown()); sys.exit(0)
|
| 570 |
+
signal.signal(signal.SIGINT, signal_handler); signal.signal(signal.SIGTERM, signal_handler)
|
|
|
|
| 571 |
|
| 572 |
if __name__ == "__main__":
|
| 573 |
+
print("🚀 Starting AI Trading Bot with 3-Layer Analysis System (Whale Fetch Decoupled)...")
|
| 574 |
+
uvicorn.run( application, host="0.0.0.0", port=7860, log_level="info", access_log=True )
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|