Riy777 commited on
Commit
a55ec18
·
verified ·
1 Parent(s): 972bc0e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -22
app.py CHANGED
@@ -1,5 +1,6 @@
1
- # app.py (V25.2 - GEM-Architect: Bulletproof Gradio UI)
2
- # تم إزالة جميع معاملات التنسيق (theme, css) من Constructor لضمان العمل على أي إصدار.
 
3
 
4
  import os
5
  import sys
@@ -155,7 +156,7 @@ async def auto_pilot_loop():
155
  @asynccontextmanager
156
  async def lifespan(app: FastAPI):
157
  global r2, data_manager, ml_processor, hub_manager, trade_manager, whale_monitor, news_fetcher, senti_analyzer, sys_state
158
- logger.info("\n🚀 [System] Startup Sequence Initiated (Titan V25.2)...")
159
  try:
160
  logger.info(" [1/7] Initializing R2 & Data Services...")
161
  r2 = R2Service()
@@ -164,10 +165,8 @@ async def lifespan(app: FastAPI):
164
  await data_manager.load_contracts_from_r2()
165
 
166
  logger.info(" [2/7] Starting Auxiliary Services (Whale & News)...")
167
- # 1. تهيئة مراقب الحيتان
168
  whale_monitor = EnhancedWhaleMonitor(contracts_db=data_manager.get_contracts_db(), r2_service=r2)
169
 
170
- # 2. تهيئة وحقن مدير الاتصالات (RPC Manager)
171
  rpc_mgr = AdaptiveRpcManager(data_manager.http_client)
172
  whale_monitor.set_rpc_manager(rpc_mgr)
173
  logger.info(" ✅ [System] RPC Manager injected into Whale Monitor.")
@@ -233,7 +232,7 @@ async def _analyze_symbol_task(symbol: str) -> Dict[str, Any]:
233
  # ==============================================================================
234
  async def run_unified_cycle():
235
  """
236
- الدورة الموحدة الكاملة (6 طبقات)
237
  """
238
  log_buffer = StringIO()
239
  def log_and_print(message):
@@ -288,7 +287,7 @@ async def run_unified_cycle():
288
  log_and_print("⚠️ No valid L2 candidates.")
289
  sys_state.set_cycle_end(logs=log_buffer.getvalue()); return
290
 
291
- # 4. 🔥 L2.5 Enrichment & Boosting (Numeric) 🔥
292
  log_and_print(f" [3/5] 🚀 L2.5 Boosting (Whales & News)...")
293
  boosted_candidates = []
294
 
@@ -296,20 +295,34 @@ async def run_unified_cycle():
296
  symbol = cand['symbol']
297
  current_score = cand['enhanced_final_score']
298
 
299
- # [CRITICAL] استخراج السعر المعروف لتمريره لمراقب الحيتان
300
  known_price = cand.get('current_price', 0.0)
301
  if known_price == 0.0:
302
  known_price = await data_manager.get_latest_price_async(symbol)
303
 
304
- # أ. تعزيز الحيتان
305
  whale_score = 0.0
306
  try:
307
  w_data = await whale_monitor.get_symbol_whale_activity(symbol, known_price=known_price)
 
 
308
  net_flow = w_data.get('accumulation_analysis_24h', {}).get('net_flow_usd', 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
 
310
- if net_flow > 1_000_000: whale_score = 0.15
311
- elif net_flow > 250_000: whale_score = 0.08
312
- elif net_flow < -1_000_000: whale_score = -0.10
313
  except Exception: pass
314
 
315
  # ب. تعزيز الأخبار
@@ -321,6 +334,7 @@ async def run_unified_cycle():
321
  if sentiment['compound'] > 0.2: news_score = 0.05
322
  except: pass
323
 
 
324
  new_final = current_score + whale_score + news_score
325
  cand['enhanced_final_score'] = new_final
326
  cand['whale_score'] = whale_score
@@ -330,11 +344,16 @@ async def run_unified_cycle():
330
 
331
  final_top_10 = sorted(boosted_candidates, key=lambda x: x['enhanced_final_score'], reverse=True)
332
 
333
- log_and_print(f"{'SYMBOL':<10} | {'FINAL':<6} | {'BASE':<6} | {'BOOST (W/N)'}")
334
- log_and_print("-" * 45)
 
335
  for c in final_top_10:
336
- base_s = c['enhanced_final_score'] - c.get('whale_score', 0.0) - c.get('news_score', 0.0)
337
- log_and_print(f"{c['symbol']:<10} | {c['enhanced_final_score']:.3f} | {base_s:.3f} | {c['boost_info']}")
 
 
 
 
338
 
339
  # 5. L3 Oracle
340
  log_and_print(f" [4/5] 🔮 L3 Oracle Check...")
@@ -536,17 +555,15 @@ async def check_live_pnl_and_status(selected_view="Hybrid System"):
536
  return "Error", "Error", empty_chart, "0", "0", "0", "0", "0%", wl_df_empty, "Err", "Err", "Err"
537
 
538
  # ==============================================================================
539
- # 🎨 Gradio UI (Bulletproof Style Injection)
540
  # ==============================================================================
541
  def create_gradio_ui():
542
  custom_css = ".gradio-container {background:#0b0f19} .dataframe {background:#1a1a1a!important} .html-box {min-height:180px}"
543
 
544
- # [CRITICAL FIX] إزالة جميع المعاملات الاختيارية من Blocks()
545
- with gr.Blocks(title="Titan V25.2") as demo:
546
- # حقن الـ CSS هنا
547
  gr.HTML(f"<style>{custom_css}</style>")
548
 
549
- gr.Markdown("# 🚀 Titan V25.2 (Full Architecture - Web3 Enabled)")
550
 
551
  with gr.Row():
552
  with gr.Column(scale=3):
@@ -595,7 +612,7 @@ def create_gradio_ui():
595
  # ==============================================================================
596
  # 🏁 Server
597
  # ==============================================================================
598
- fast_api_server = FastAPI(lifespan=lifespan, title="Titan V25.2 Pro", description="Titan Enterprise Trading System")
599
  gradio_dashboard = create_gradio_ui()
600
  app = gr.mount_gradio_app(app=fast_api_server, blocks=gradio_dashboard, path="/")
601
 
 
1
+ # app.py (V25.3 - GEM-Architect: Full Stats Table & Sensitive Whale Scoring)
2
+ # - تم استعادة الجدول التفصيلي (Titan, Pattern, MC).
3
+ # - تم تعديل حساسية الحيتان لتعطي نقاطاً حتى على التحركات المتوسطة.
4
 
5
  import os
6
  import sys
 
156
  @asynccontextmanager
157
  async def lifespan(app: FastAPI):
158
  global r2, data_manager, ml_processor, hub_manager, trade_manager, whale_monitor, news_fetcher, senti_analyzer, sys_state
159
+ logger.info("\n🚀 [System] Startup Sequence Initiated (Titan V25.3)...")
160
  try:
161
  logger.info(" [1/7] Initializing R2 & Data Services...")
162
  r2 = R2Service()
 
165
  await data_manager.load_contracts_from_r2()
166
 
167
  logger.info(" [2/7] Starting Auxiliary Services (Whale & News)...")
 
168
  whale_monitor = EnhancedWhaleMonitor(contracts_db=data_manager.get_contracts_db(), r2_service=r2)
169
 
 
170
  rpc_mgr = AdaptiveRpcManager(data_manager.http_client)
171
  whale_monitor.set_rpc_manager(rpc_mgr)
172
  logger.info(" ✅ [System] RPC Manager injected into Whale Monitor.")
 
232
  # ==============================================================================
233
  async def run_unified_cycle():
234
  """
235
+ الدورة الموحدة الكاملة (Enterprise Logic)
236
  """
237
  log_buffer = StringIO()
238
  def log_and_print(message):
 
287
  log_and_print("⚠️ No valid L2 candidates.")
288
  sys_state.set_cycle_end(logs=log_buffer.getvalue()); return
289
 
290
+ # 4. 🔥 L2.5 Enrichment & Boosting (Whales & News) 🔥
291
  log_and_print(f" [3/5] 🚀 L2.5 Boosting (Whales & News)...")
292
  boosted_candidates = []
293
 
 
295
  symbol = cand['symbol']
296
  current_score = cand['enhanced_final_score']
297
 
298
+ # استخراج السعر
299
  known_price = cand.get('current_price', 0.0)
300
  if known_price == 0.0:
301
  known_price = await data_manager.get_latest_price_async(symbol)
302
 
303
+ # أ. تعزيز الحيتان (Scoring Update)
304
  whale_score = 0.0
305
  try:
306
  w_data = await whale_monitor.get_symbol_whale_activity(symbol, known_price=known_price)
307
+
308
+ # استخدام بيانات التراكم 24س
309
  net_flow = w_data.get('accumulation_analysis_24h', {}).get('net_flow_usd', 0)
310
+ whale_count = w_data.get('summary', {}).get('total_transfers_scanned', 0)
311
+
312
+ # [UPDATED] منطق أكثر حساسية:
313
+ # - يكافئ العدد (Activity)
314
+ # - يكافئ صافي التدفق الإيجابي حتى لو كان صغيراً
315
+
316
+ # 1. مكافأة النشاط (Activity Boost)
317
+ if whale_count >= 10: whale_score += 0.05
318
+ elif whale_count >= 3: whale_score += 0.02
319
+
320
+ # 2. مكافأة التدفق (Flow Boost)
321
+ if net_flow > 500_000: whale_score += 0.10 # حوت قوي
322
+ elif net_flow > 50_000: whale_score += 0.05 # تجميع متوسط
323
+ elif net_flow < -500_000: whale_score -= 0.10 # بيع قوي
324
+ elif net_flow < -50_000: whale_score -= 0.05 # تصريف
325
 
 
 
 
326
  except Exception: pass
327
 
328
  # ب. تعزيز الأخبار
 
334
  if sentiment['compound'] > 0.2: news_score = 0.05
335
  except: pass
336
 
337
+ # تحديث الدرجة وتخزين القيم
338
  new_final = current_score + whale_score + news_score
339
  cand['enhanced_final_score'] = new_final
340
  cand['whale_score'] = whale_score
 
344
 
345
  final_top_10 = sorted(boosted_candidates, key=lambda x: x['enhanced_final_score'], reverse=True)
346
 
347
+ # [RESTORED] عرض الجدول التفصيلي الكامل
348
+ log_and_print(f"{'SYMBOL':<10} | {'FINAL':<6} | {'TITAN':<5} | {'PATT':<5} | {'MC':<5} | {'BOOST (W/N)'}")
349
+ log_and_print("-" * 65)
350
  for c in final_top_10:
351
+ # استخراج الدرجات الفرعية (مع التحقق من وجودها)
352
+ titan_s = c.get('titan_score', 0.0)
353
+ patt_s = c.get('pattern_score', 0.0)
354
+ mc_s = c.get('monte_carlo_score', 0.0)
355
+
356
+ log_and_print(f"{c['symbol']:<10} | {c['enhanced_final_score']:.3f} | {titan_s:.2f} | {patt_s:.2f} | {mc_s:.2f} | {c['boost_info']}")
357
 
358
  # 5. L3 Oracle
359
  log_and_print(f" [4/5] 🔮 L3 Oracle Check...")
 
555
  return "Error", "Error", empty_chart, "0", "0", "0", "0", "0%", wl_df_empty, "Err", "Err", "Err"
556
 
557
  # ==============================================================================
558
+ # 🎨 Gradio UI (Bulletproof)
559
  # ==============================================================================
560
  def create_gradio_ui():
561
  custom_css = ".gradio-container {background:#0b0f19} .dataframe {background:#1a1a1a!important} .html-box {min-height:180px}"
562
 
563
+ with gr.Blocks(title="Titan V25.3") as demo:
 
 
564
  gr.HTML(f"<style>{custom_css}</style>")
565
 
566
+ gr.Markdown("# 🚀 Titan V25.3 (Full Architecture - Web3 Enabled)")
567
 
568
  with gr.Row():
569
  with gr.Column(scale=3):
 
612
  # ==============================================================================
613
  # 🏁 Server
614
  # ==============================================================================
615
+ fast_api_server = FastAPI(lifespan=lifespan, title="Titan V25.3 Pro", description="Titan Enterprise Trading System")
616
  gradio_dashboard = create_gradio_ui()
617
  app = gr.mount_gradio_app(app=fast_api_server, blocks=gradio_dashboard, path="/")
618