Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app.py (V15.
|
| 2 |
import os
|
| 3 |
import sys
|
| 4 |
import traceback
|
|
@@ -23,8 +23,13 @@ try:
|
|
| 23 |
from whale_monitor.core import EnhancedWhaleMonitor
|
| 24 |
from sentiment_news import NewsFetcher
|
| 25 |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
except ImportError as e:
|
| 29 |
# إيقاف فوري للنظام في حال فقدان أي مكون حيوي
|
| 30 |
sys.exit(f"❌ [FATAL ERROR] Failed to import core modules: {e}")
|
|
@@ -40,378 +45,255 @@ llm_service: LLMService = None
|
|
| 40 |
learning_hub: LearningHubManager = None
|
| 41 |
whale_monitor: EnhancedWhaleMonitor = None
|
| 42 |
news_fetcher: NewsFetcher = None
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
|
|
|
|
|
|
|
|
|
| 46 |
class SystemState:
|
| 47 |
def __init__(self):
|
| 48 |
self.ready = False
|
| 49 |
self.cycle_running = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
sys_state = SystemState()
|
| 52 |
|
| 53 |
# ==============================================================================
|
| 54 |
-
#
|
| 55 |
# ==============================================================================
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
global r2, data_manager, ml_processor, trade_manager, llm_service, learning_hub
|
| 58 |
-
global whale_monitor, news_fetcher,
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
print("\n🔌 [System V15.1] Starting Full Initialization Sequence (with Guard V2)...")
|
| 64 |
|
| 65 |
try:
|
| 66 |
-
# 1.
|
|
|
|
| 67 |
r2 = R2Service()
|
| 68 |
-
|
| 69 |
-
print(f" ✅ R2 Service connected (Contracts loaded: {len(contracts_db)})")
|
| 70 |
|
| 71 |
-
|
| 72 |
-
data_manager = DataManager(contracts_db, whale_monitor, r2)
|
| 73 |
-
await data_manager.
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
# 2.
|
|
|
|
|
|
|
| 77 |
news_fetcher = NewsFetcher()
|
| 78 |
-
|
| 79 |
-
print(" ✅ NewsFetcher & VADER initialized.")
|
| 80 |
|
| 81 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
llm_service = LLMService()
|
| 83 |
-
llm_service.r2_service = r2 # لربط حفظ السجلات
|
| 84 |
|
| 85 |
-
|
|
|
|
| 86 |
await learning_hub.initialize()
|
| 87 |
-
llm_service.learning_hub = learning_hub # الربط العكسي للعقل بمركز التعلم
|
| 88 |
-
print(" ✅ LLM Brain & Learning Hub connected.")
|
| 89 |
|
| 90 |
-
# 4. محركات ال
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
await ml_processor.initialize()
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
#
|
| 96 |
-
|
|
|
|
|
|
|
| 97 |
await guard_engine.initialize()
|
| 98 |
-
print(" ✅ Guard Engine V2 (Exit Protector) ready.")
|
| 99 |
|
| 100 |
-
# [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
trade_manager = TradeManager(
|
| 102 |
-
r2,
|
| 103 |
-
data_manager,
|
| 104 |
-
|
| 105 |
-
ml_processor.
|
| 106 |
-
|
|
|
|
|
|
|
| 107 |
)
|
|
|
|
|
|
|
| 108 |
await trade_manager.initialize_sentry_exchanges()
|
| 109 |
-
# بدء
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
print("
|
|
|
|
| 115 |
|
|
|
|
|
|
|
| 116 |
except Exception as e:
|
| 117 |
-
print(f"
|
| 118 |
traceback.print_exc()
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
# ==============================================================================
|
| 122 |
-
#
|
| 123 |
# ==============================================================================
|
| 124 |
async def run_unified_cycle():
|
| 125 |
"""
|
| 126 |
-
|
|
|
|
| 127 |
"""
|
| 128 |
-
# فحوصات الأمان مع طباعة واضحة لسبب التخطي
|
| 129 |
-
if not sys_state.ready:
|
| 130 |
-
print("⏳ [Cycle Skipped] System is not fully initialized yet.")
|
| 131 |
-
return
|
| 132 |
if sys_state.cycle_running:
|
| 133 |
-
print("
|
| 134 |
return
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
print("🔒 [Cycle Skipped] Could not acquire execution lock (system busy).")
|
| 139 |
return
|
| 140 |
|
| 141 |
-
sys_state.
|
| 142 |
-
|
| 143 |
|
| 144 |
try:
|
| 145 |
-
#
|
| 146 |
-
|
| 147 |
-
await trade_manager.sync_internal_state()
|
| 148 |
-
|
| 149 |
-
open_trades = list(trade_manager.open_positions.values())
|
| 150 |
-
|
| 151 |
-
if len(open_trades) > 0:
|
| 152 |
-
print(f"\n⚔️ [Unified Cycle] Active trades detected: {len(open_trades)} {[t['symbol'] for t in open_trades]}. Engaging RE-ANALYSIS Mode.")
|
| 153 |
-
await _run_reanalysis_mode_full(open_trades)
|
| 154 |
-
else:
|
| 155 |
-
print("\n🔭 [Unified Cycle] No active trades found. Engaging FULL EXPLORER Mode.")
|
| 156 |
-
await _run_explorer_mode_full()
|
| 157 |
-
|
| 158 |
-
except Exception as e:
|
| 159 |
-
print(f"❌ [CYCLE ERROR] Unexpected error during unified cycle: {e}")
|
| 160 |
-
traceback.print_exc()
|
| 161 |
-
finally:
|
| 162 |
-
# ضمان تحرير الموارد والقفل في جميع الحالات
|
| 163 |
-
r2.release_lock()
|
| 164 |
-
sys_state.cycle_running = False
|
| 165 |
-
gc.collect() # تنظيف الذاكرة العشوائية
|
| 166 |
-
duration = (datetime.now() - start_time).total_seconds()
|
| 167 |
-
print(f"🏁 [Cycle Completed] Execution time: {duration:.2f} seconds.")
|
| 168 |
-
|
| 169 |
-
# ==============================================================================
|
| 170 |
-
# ⚔️ المسار 1: وضع إعادة التقييم الكامل (Full Re-analysis Mode)
|
| 171 |
-
# ==============================================================================
|
| 172 |
-
async def _run_reanalysis_mode_full(open_trades):
|
| 173 |
-
"""يقوم بإعادة تقييم كل صفقة مفتوحة باستخدام العقل الكلي"""
|
| 174 |
-
for trade in open_trades:
|
| 175 |
-
symbol = trade.get('symbol')
|
| 176 |
-
if not symbol: continue
|
| 177 |
-
|
| 178 |
-
print(f" ⚖️ [Re-eval] Consulting Omniscient Brain for {symbol}...")
|
| 179 |
-
|
| 180 |
-
try:
|
| 181 |
-
# 1. جمع أحدث البيانات من السوق (Fresh Data Snapshot)
|
| 182 |
-
current_price = await data_manager.get_latest_price_async(symbol)
|
| 183 |
-
whale_data = await whale_monitor.get_symbol_whale_activity(symbol)
|
| 184 |
-
news_text = await news_fetcher.get_news_for_symbol(symbol)
|
| 185 |
-
|
| 186 |
-
# محاولة الحصول على درجة تيتان سريعة
|
| 187 |
-
titan_score_now = 0.0
|
| 188 |
-
|
| 189 |
-
current_data_packet = {
|
| 190 |
-
'symbol': symbol,
|
| 191 |
-
'current_price': current_price,
|
| 192 |
-
'titan_score': titan_score_now,
|
| 193 |
-
'whale_data': whale_data,
|
| 194 |
-
'news_text': news_text
|
| 195 |
-
}
|
| 196 |
-
|
| 197 |
-
# 2. استدعاء العقل الكلي للتقييم
|
| 198 |
-
decision = await llm_service.re_analyze_trade_async(trade, current_data_packet)
|
| 199 |
-
|
| 200 |
-
# 3. تنفيذ القرار فوراً
|
| 201 |
-
if decision:
|
| 202 |
-
action = decision.get('action', 'HOLD')
|
| 203 |
-
reason = decision.get('reasoning', 'No reasoning provided')
|
| 204 |
-
|
| 205 |
-
if action == 'EMERGENCY_EXIT':
|
| 206 |
-
print(f" 🚨 [EXECUTE] BRAIN COMMAND: EMERGENCY EXIT for {symbol}!")
|
| 207 |
-
await trade_manager.execute_emergency_exit(symbol, f"Brain: {reason}")
|
| 208 |
-
|
| 209 |
-
elif action == 'UPDATE_TARGETS':
|
| 210 |
-
new_tp = decision.get('new_tp')
|
| 211 |
-
new_sl = decision.get('new_sl')
|
| 212 |
-
print(f" 🎯 [EXECUTE] BRAIN COMMAND: Update Targets for {symbol} (TP:{new_tp}, SL:{new_sl})")
|
| 213 |
-
await trade_manager.update_trade_targets(symbol, new_tp, new_sl, f"Brain: {reason}")
|
| 214 |
-
|
| 215 |
-
else:
|
| 216 |
-
# HOLD أو أي قرار آخر غير حرج
|
| 217 |
-
print(f" ✅ [MAINTAIN] Brain verdict for {symbol}: HOLD. ({reason[:60]}...)")
|
| 218 |
-
else:
|
| 219 |
-
print(f" ⚠️ [WARNING] Brain returned no valid decision for {symbol}. Holding position.")
|
| 220 |
-
|
| 221 |
-
except Exception as e:
|
| 222 |
-
print(f" ❌ [ERROR] Failed to re-evaluate {symbol}: {e}")
|
| 223 |
-
traceback.print_exc()
|
| 224 |
-
|
| 225 |
-
# ==============================================================================
|
| 226 |
-
# 🔭 المسار 2: وضع المستكشف الكامل (Full 4-Layer Explorer Mode)
|
| 227 |
-
# ==============================================================================
|
| 228 |
-
async def _run_explorer_mode_full():
|
| 229 |
-
"""تنفيذ دورة البحث الكاملة عبر الطبقات الأربع بدون أي اختصارات"""
|
| 230 |
-
|
| 231 |
-
# ----------------------------------------------------------------------
|
| 232 |
-
# LAYER 1: Rapid Hybrid Screening (Titan + Patterns + Simple MC)
|
| 233 |
-
# ----------------------------------------------------------------------
|
| 234 |
-
print("\n--- 🛡️ Layer 1: Rapid Hybrid Screening ---")
|
| 235 |
-
raw_candidates = await data_manager.layer1_rapid_screening()
|
| 236 |
-
if not raw_candidates:
|
| 237 |
-
print(" ⚠️ Layer 1 yielded no initial candidates from DataManager.")
|
| 238 |
-
return
|
| 239 |
-
|
| 240 |
-
print(f" Running ML Processor on {len(raw_candidates)} candidates...")
|
| 241 |
-
l1_passed_candidates = []
|
| 242 |
-
|
| 243 |
-
# استخدام طابور لمعالجة البيانات المتدفقة بشكل غير متزامن
|
| 244 |
-
data_queue = asyncio.Queue()
|
| 245 |
-
producer_task = asyncio.create_task(data_manager.stream_ohlcv_data(raw_candidates, data_queue))
|
| 246 |
-
|
| 247 |
-
while True:
|
| 248 |
-
batch_data = await data_queue.get()
|
| 249 |
-
if batch_data is None:
|
| 250 |
-
data_queue.task_done()
|
| 251 |
-
break
|
| 252 |
-
|
| 253 |
-
for raw_symbol_data in batch_data:
|
| 254 |
-
# المعالجة الكاملة لكل عملة
|
| 255 |
-
analysis_result = await ml_processor.process_and_score_symbol_enhanced(raw_symbol_data)
|
| 256 |
-
|
| 257 |
-
if analysis_result:
|
| 258 |
-
score = analysis_result.get('enhanced_final_score', 0.0)
|
| 259 |
-
# عتبة المرور الأولية (يمكن تعديلها من الإعدادات)
|
| 260 |
-
if score >= 0.50:
|
| 261 |
-
l1_passed_candidates.append(analysis_result)
|
| 262 |
-
|
| 263 |
-
data_queue.task_done()
|
| 264 |
-
|
| 265 |
-
await producer_task # انتظار انتهاء تدفق البيانات بالكامل
|
| 266 |
-
|
| 267 |
-
# ترتيب النتائج واختيار أفضل 10
|
| 268 |
-
l1_passed_candidates.sort(key=lambda x: x['enhanced_final_score'], reverse=True)
|
| 269 |
-
layer2_input_candidates = l1_passed_candidates[:10]
|
| 270 |
-
|
| 271 |
-
print(f"✅ Layer 1 Complete. {len(layer2_input_candidates)} candidates advanced to Layer 2.")
|
| 272 |
-
if not layer2_input_candidates:
|
| 273 |
-
return
|
| 274 |
-
|
| 275 |
-
# ----------------------------------------------------------------------
|
| 276 |
-
# LAYER 2: Deep Analysis (Whales + News + Advanced Scoring)
|
| 277 |
-
# ----------------------------------------------------------------------
|
| 278 |
-
print("\n--- 🐳 Layer 2: Deep Multi-Factor Analysis ---")
|
| 279 |
-
l2_scored_candidates = []
|
| 280 |
-
|
| 281 |
-
for cand in layer2_input_candidates:
|
| 282 |
-
symbol = cand['symbol']
|
| 283 |
-
print(f" 🔎 Performing deep scan on {symbol}...")
|
| 284 |
|
| 285 |
-
#
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
|
| 288 |
-
#
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
# ج. حساب النقاط المعززة (Enhanced Layer 2 Score)
|
| 296 |
-
l1_score = cand['enhanced_final_score']
|
| 297 |
|
| 298 |
-
#
|
| 299 |
-
|
| 300 |
-
whale_bonus = 0.15 if whale_signal in ['BUY', 'STRONG_BUY'] else 0.0
|
| 301 |
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
news_bonus = 0.10
|
| 307 |
-
news_status = "POSITIVE"
|
| 308 |
-
elif news_score_raw < -0.25:
|
| 309 |
-
news_bonus = -0.10
|
| 310 |
-
news_status = "NEGATIVE"
|
| 311 |
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
# تحديث بيانات المرشح
|
| 316 |
-
cand.update({
|
| 317 |
-
'layer2_score': final_l2_score,
|
| 318 |
-
'whale_data': whale_data,
|
| 319 |
-
'news_text': news_text,
|
| 320 |
-
'news_score_raw': news_score_raw,
|
| 321 |
-
'l2_bonuses': {
|
| 322 |
-
'whale': whale_bonus,
|
| 323 |
-
'whale_signal': whale_signal,
|
| 324 |
-
'news': news_bonus,
|
| 325 |
-
'news_status': news_status
|
| 326 |
-
}
|
| 327 |
-
})
|
| 328 |
-
l2_scored_candidates.append(cand)
|
| 329 |
-
|
| 330 |
-
# ترتيب واختيار أفضل 5 للطبقة الثالثة
|
| 331 |
-
l2_scored_candidates.sort(key=lambda x: x['layer2_score'], reverse=True)
|
| 332 |
-
layer3_input_candidates = l2_scored_candidates[:5]
|
| 333 |
-
|
| 334 |
-
print(f"✅ Layer 2 Complete. {len(layer3_input_candidates)} candidates selected for Brain validation.")
|
| 335 |
-
|
| 336 |
-
# ----------------------------------------------------------------------
|
| 337 |
-
# LAYER 3: Omniscient Brain Validation (LLM)
|
| 338 |
-
# ----------------------------------------------------------------------
|
| 339 |
-
print("\n--- 🧠 Layer 3: Omniscient Brain Validation ---")
|
| 340 |
-
|
| 341 |
-
if layer3_input_candidates:
|
| 342 |
-
print("📋 [L3 Qualification] The following candidates are advancing to Omniscient Brain:")
|
| 343 |
-
# رأس الجدول المحسن (تمت استعادته بالكامل)
|
| 344 |
-
print(f" {'#':<2} {'SYMBOL':<10} | {'L1':<6} | {'Whale Info':<16} | {'News Info':<16} | {'FINAL L2':<8}")
|
| 345 |
-
print("-" * 70)
|
| 346 |
-
for i, cand in enumerate(layer3_input_candidates, 1):
|
| 347 |
-
l1 = cand.get('enhanced_final_score', 0)
|
| 348 |
-
l2 = cand.get('layer2_score', 0)
|
| 349 |
-
bonuses = cand.get('l2_bonuses', {})
|
| 350 |
-
|
| 351 |
-
w_signal = bonuses.get('whale_signal', 'HOLD')
|
| 352 |
-
w_bonus = bonuses.get('whale', 0.0)
|
| 353 |
-
w_info = f"{w_signal[:4]}.. ({w_bonus:+.2f})" if w_signal != 'HOLD' else "No Impact"
|
| 354 |
-
|
| 355 |
-
n_status = bonuses.get('news_status', 'NEUTRAL')
|
| 356 |
-
n_bonus = bonuses.get('news', 0.0)
|
| 357 |
-
n_info = f"{n_status[:4]}.. ({n_bonus:+.2f})" if n_bonus != 0 else "Neutral"
|
| 358 |
|
| 359 |
-
|
| 360 |
-
print("
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
for cand in layer3_input_candidates:
|
| 364 |
-
symbol = cand['symbol']
|
| 365 |
-
print(f" ⚖️ Submitting {symbol} to Omniscient Brain for final verdict...")
|
| 366 |
-
|
| 367 |
-
decision = await llm_service.get_trading_decision(cand)
|
| 368 |
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
except (ValueError, TypeError):
|
| 373 |
-
confidence = 0.0
|
| 374 |
-
|
| 375 |
-
print(f" 🎉 BRAIN APPROVED: {symbol} | Confidence: {confidence:.2f}")
|
| 376 |
-
cand['llm_decision'] = decision
|
| 377 |
-
approved_targets.append(cand)
|
| 378 |
-
else:
|
| 379 |
-
reason = decision.get('reasoning', 'Unknown reason') if decision else 'No response from Brain'
|
| 380 |
-
print(f" 🛑 BRAIN REJECTED: {symbol} | Reason: {reason[:60]}...")
|
| 381 |
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
if approved_targets:
|
| 387 |
-
print(f"🚀 Handing over {len(approved_targets)} elite targets to TradeManager Sentry.")
|
| 388 |
-
await trade_manager.update_sentry_watchlist(approved_targets)
|
| 389 |
-
else:
|
| 390 |
-
print("😴 Cycle ended with NO targets passing all 4 layers. Sentry remains on standby.")
|
| 391 |
|
| 392 |
# ==============================================================================
|
| 393 |
-
#
|
|
|
|
| 394 |
# ==============================================================================
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
# عند الإيقاف
|
| 401 |
-
print("\n🛑 [System] Initiating shutdown sequence...")
|
| 402 |
-
if trade_manager: await trade_manager.stop_sentry_loops()
|
| 403 |
-
if data_manager: await data_manager.close()
|
| 404 |
-
print("👋 [System] Shutdown complete.")
|
| 405 |
-
|
| 406 |
-
app = FastAPI(lifespan=lifespan, title="Titan Hybrid System V15.1 (Full Production + Guard V2)")
|
| 407 |
|
| 408 |
@app.get("/")
|
| 409 |
-
async def
|
| 410 |
"""فحص حالة النظام الأساسية"""
|
| 411 |
return {
|
| 412 |
"system_status": "ONLINE",
|
| 413 |
"initialized": sys_state.ready,
|
| 414 |
-
"guard_v2_active": guard_engine.initialized if guard_engine else False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
"current_mode": "RE-ANALYSIS" if trade_manager and trade_manager.open_positions else "EXPLORER"
|
| 416 |
}
|
| 417 |
|
|
@@ -436,8 +318,9 @@ async def get_full_status():
|
|
| 436 |
"sentry_watchlist": list(trade_manager.watchlist.keys()) if trade_manager else []
|
| 437 |
}
|
| 438 |
|
| 439 |
-
# نقطة الدخول
|
|
|
|
| 440 |
if __name__ == "__main__":
|
| 441 |
import uvicorn
|
| 442 |
-
print("
|
| 443 |
-
uvicorn.run(app, host="0.0.0.0", port=
|
|
|
|
| 1 |
+
# app.py (V15.2 - Full Production - Sniper V3 + Guard V2 Integrated)
|
| 2 |
import os
|
| 3 |
import sys
|
| 4 |
import traceback
|
|
|
|
| 23 |
from whale_monitor.core import EnhancedWhaleMonitor
|
| 24 |
from sentiment_news import NewsFetcher
|
| 25 |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 26 |
+
|
| 27 |
+
# [ 🚀 🚀 🚀 ]
|
| 28 |
+
# [ 💡 💡 💡 ] التعديل: استيراد كلا المحركين
|
| 29 |
+
from ml_engine.guard_engine import GuardEngine # (هذا هو حارس الخروج V1.0)
|
| 30 |
+
from ml_engine.sniper_engine import SniperEngine # (هذا هو قناص الدخول V3.0)
|
| 31 |
+
# [ 🚀 🚀 🚀 ]
|
| 32 |
+
|
| 33 |
except ImportError as e:
|
| 34 |
# إيقاف فوري للنظام في حال فقدان أي مكون حيوي
|
| 35 |
sys.exit(f"❌ [FATAL ERROR] Failed to import core modules: {e}")
|
|
|
|
| 45 |
learning_hub: LearningHubManager = None
|
| 46 |
whale_monitor: EnhancedWhaleMonitor = None
|
| 47 |
news_fetcher: NewsFetcher = None
|
| 48 |
+
senti_analyzer: SentimentIntensityAnalyzer = None
|
| 49 |
+
sys_state: 'SystemState' = None
|
| 50 |
+
|
| 51 |
+
# [ 🚀 🚀 🚀 ]
|
| 52 |
+
# [ 💡 💡 💡 ] التعديل: تعريف كلا المحركين
|
| 53 |
+
guard_engine: GuardEngine = None # (حارس الخروج)
|
| 54 |
+
sniper_engine: SniperEngine = None # (قناص الدخول)
|
| 55 |
+
# [ 🚀 🚀 🚀 ]
|
| 56 |
+
|
| 57 |
+
# (تحديد المسارات الأساسية - نفترض أن هذا الملف يعمل من المجلد الجذري)
|
| 58 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 59 |
+
|
| 60 |
+
# [ 🚀 🚀 🚀 ]
|
| 61 |
+
# [ 💡 💡 💡 ] [هام جداً]: تحديد مسار مشروع Guard_Project
|
| 62 |
+
# هذا هو المسار الذي يحتوي على مجلد 'Models_V3'
|
| 63 |
+
# (هذا مسار كولاب كمثال، قم بتغييره إلى مسار الخادم الحقيقي)
|
| 64 |
+
GUARD_PROJECT_PATH = "/content/drive/MyDrive/Guard_Project"
|
| 65 |
+
# في الخادم الحقيقي، قد يكون:
|
| 66 |
+
# GUARD_PROJECT_PATH = "/app/Guard_Project"
|
| 67 |
+
# [ 🚀 🚀 🚀 ]
|
| 68 |
|
| 69 |
+
# ==============================================================================
|
| 70 |
+
# 🔄 حالة النظام (System State)
|
| 71 |
+
# ==============================================================================
|
| 72 |
class SystemState:
|
| 73 |
def __init__(self):
|
| 74 |
self.ready = False
|
| 75 |
self.cycle_running = False
|
| 76 |
+
self.last_cycle_time: datetime = None
|
| 77 |
+
self.last_cycle_error = None
|
| 78 |
+
self.app_start_time = datetime.now()
|
| 79 |
+
|
| 80 |
+
def set_ready(self): self.ready = True
|
| 81 |
+
def set_cycle_start(self): self.cycle_running = True
|
| 82 |
+
def set_cycle_end(self, error=None):
|
| 83 |
+
self.cycle_running = False
|
| 84 |
+
self.last_cycle_time = datetime.now()
|
| 85 |
+
self.last_cycle_error = str(error) if error else None
|
| 86 |
|
| 87 |
sys_state = SystemState()
|
| 88 |
|
| 89 |
# ==============================================================================
|
| 90 |
+
# 🚀 تهيئة التطبيق ودورة الحياة (App Initialization & Lifecycle)
|
| 91 |
# ==============================================================================
|
| 92 |
+
@asynccontextmanager
|
| 93 |
+
async def lifespan(app: FastAPI):
|
| 94 |
+
"""
|
| 95 |
+
دالة دورة حياة التطبيق (لـ FastAPI)
|
| 96 |
+
يتم تشغيل الكود قبل 'yield' عند بدء التشغيل.
|
| 97 |
+
يتم تشغيل الكود بعد 'yield' عند إيقاف التشغيل.
|
| 98 |
+
"""
|
| 99 |
global r2, data_manager, ml_processor, trade_manager, llm_service, learning_hub
|
| 100 |
+
global whale_monitor, news_fetcher, senti_analyzer, guard_engine, sniper_engine, sys_state
|
| 101 |
|
| 102 |
+
print("🚀 [FastAPI] بدء التشغيل (Startup Event)...")
|
| 103 |
+
print("------------------------------------------------------")
|
|
|
|
|
|
|
| 104 |
|
| 105 |
try:
|
| 106 |
+
# --- 1. تهيئة الخدمات الأساسية (R2 & DataManager) ---
|
| 107 |
+
print(" [1/8] تهيئة R2Service...")
|
| 108 |
r2 = R2Service()
|
| 109 |
+
await r2.initialize_buckets()
|
|
|
|
| 110 |
|
| 111 |
+
print(" [2/8] تهيئة DataManager...")
|
| 112 |
+
data_manager = DataManager(contracts_db={}, whale_monitor=None, r2_service=r2)
|
| 113 |
+
await data_manager.initialize_exchange()
|
| 114 |
+
await data_manager.load_contracts_from_r2()
|
| 115 |
+
|
| 116 |
+
# --- 2. تهيئة خدمات الطبقة الثانية (L2 Services) ---
|
| 117 |
+
print(" [3/8] تهيئة L2 Services (Whales, News, Sentiment)...")
|
| 118 |
+
whale_monitor = EnhancedWhaleMonitor(r2, data_manager.get_contracts_db())
|
| 119 |
news_fetcher = NewsFetcher()
|
| 120 |
+
senti_analyzer = SentimentIntensityAnalyzer() # (هذا متزامن)
|
|
|
|
| 121 |
|
| 122 |
+
# (تحديث DataManager بالخدمات)
|
| 123 |
+
data_manager.whale_monitor = whale_monitor
|
| 124 |
+
|
| 125 |
+
# --- 3. تهيئة الخدمات المعرفية (Cognitive Services) ---
|
| 126 |
+
print(" [4/8] تهيئة LLMService...")
|
| 127 |
llm_service = LLMService()
|
|
|
|
| 128 |
|
| 129 |
+
print(" [5/8] تهيئة LearningHub...")
|
| 130 |
+
learning_hub = LearningHubManager(r2)
|
| 131 |
await learning_hub.initialize()
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
# --- 4. تهيئة محركات الذكاء الاصطناعي (ML Engines) ---
|
| 134 |
+
print(" [6/8] تهيئة MLProcessor (L1 Engine)...")
|
| 135 |
+
ml_processor = MLProcessor(
|
| 136 |
+
market_context=None, # (تحتاج لتمرير هذا إذا كان مطلوباً)
|
| 137 |
+
data_manager=data_manager,
|
| 138 |
+
learning_hub=learning_hub
|
| 139 |
+
)
|
| 140 |
await ml_processor.initialize()
|
| 141 |
+
|
| 142 |
+
print(" [7/8] تهيئة GuardEngine (L2 Exit Protector)...")
|
| 143 |
+
# (نفترض أن مسار نماذج الحارس V1/V2 موجود في 'ml_models/guard_v2')
|
| 144 |
+
# [تنبيه]: تأكد من أن هذا المسار صحيح في الخادم
|
| 145 |
+
guard_engine_models_dir = os.path.join(BASE_DIR, "ml_models", "guard_v2")
|
| 146 |
+
guard_engine = GuardEngine(models_dir=guard_engine_models_dir)
|
| 147 |
await guard_engine.initialize()
|
|
|
|
| 148 |
|
| 149 |
+
# [ 🚀 🚀 🚀 ]
|
| 150 |
+
# [ 💡 💡 💡 ] التعديل: تهيئة قناص الدخول (L2 Entry Sniper)
|
| 151 |
+
print(" [8/8] تهيئة SniperEngine (L2 Entry Sniper)...")
|
| 152 |
+
# (نمرر المسار الكامل لمجلد Guard_Project)
|
| 153 |
+
sniper_engine = SniperEngine(base_project_dir=GUARD_PROJECT_PATH)
|
| 154 |
+
await sniper_engine.initialize()
|
| 155 |
+
|
| 156 |
+
# [ 🚀 🚀 🚀 ]
|
| 157 |
+
# [ 💡 💡 💡 ] تعديل العتبة بناءً على طلبك
|
| 158 |
+
# (ينسى عتبة المحاكاة 0.35 ويستخدم 0.60)
|
| 159 |
+
sniper_engine.set_entry_threshold(0.60)
|
| 160 |
+
# [ 🚀 🚀 🚀 ]
|
| 161 |
+
|
| 162 |
+
# --- 5. تهيئة مدير التداول (TradeManager) ---
|
| 163 |
+
print(" [FINAL] تهيئة TradeManager...")
|
| 164 |
+
|
| 165 |
+
# [ 🚀 🚀 🚀 ]
|
| 166 |
+
# [ 💡 💡 💡 ] التعديل: تمرير كلا المحركين إلى مدير التداول
|
| 167 |
trade_manager = TradeManager(
|
| 168 |
+
r2_service=r2,
|
| 169 |
+
data_manager=data_manager,
|
| 170 |
+
# (نمرر المحركات الفرعية من المعالج كما في V15.1)
|
| 171 |
+
titan_engine=ml_processor.titan,
|
| 172 |
+
pattern_engine=ml_processor.pattern_engine,
|
| 173 |
+
guard_engine=guard_engine, # (حارس الخروج)
|
| 174 |
+
sniper_engine=sniper_engine # (قناص الدخول)
|
| 175 |
)
|
| 176 |
+
# [ 🚀 🚀 🚀 ]
|
| 177 |
+
|
| 178 |
await trade_manager.initialize_sentry_exchanges()
|
| 179 |
+
await trade_manager.start_sentry_loops() # بدء الحراسة للصفقات المفتوحة
|
| 180 |
+
|
| 181 |
+
# --- 6. النظام جاهز ---
|
| 182 |
+
sys_state.set_ready()
|
| 183 |
+
print("------------------------------------------------------")
|
| 184 |
+
print("✅ [System READY] جميع الوحدات تم تهيئتها بنجاح.")
|
| 185 |
+
print("------------------------------------------------------")
|
| 186 |
|
| 187 |
+
yield # (نقطة فصل دورة حياة التطبيق)
|
| 188 |
+
|
| 189 |
except Exception as e:
|
| 190 |
+
print(f"❌ [FATAL STARTUP ERROR] فشل فادح أثناء بدء التشغيل: {e}")
|
| 191 |
traceback.print_exc()
|
| 192 |
+
# (اختياري: إيقاف التطبيق إذا فشلت التهيئة)
|
| 193 |
+
# sys_state.ready = False
|
| 194 |
+
# yield # (نسمح بالاستمرار ولكن 'ready' ستكون False)
|
| 195 |
+
|
| 196 |
+
finally:
|
| 197 |
+
# --- كود إيقاف التشغيل (Shutdown) ---
|
| 198 |
+
print("\n🛑 [FastAPI] بدء إيقاف التشغيل (Shutdown Event)...")
|
| 199 |
+
sys_state.ready = False
|
| 200 |
+
if trade_manager:
|
| 201 |
+
await trade_manager.stop_sentry_loops()
|
| 202 |
+
if data_manager:
|
| 203 |
+
await data_manager.close_exchange_session()
|
| 204 |
+
if r2:
|
| 205 |
+
await r2.close_client_session()
|
| 206 |
+
print("✅ [System SHUTDOWN] تم إغلاق جميع الاتصالات.")
|
| 207 |
|
| 208 |
# ==============================================================================
|
| 209 |
+
# 🌀 الدورة الموحدة (Unified Cycle)
|
| 210 |
# ==============================================================================
|
| 211 |
async def run_unified_cycle():
|
| 212 |
"""
|
| 213 |
+
هذه هي الدورة الرئيسية التي تجمع كل شيء معاً.
|
| 214 |
+
(يتم تشغيلها في الخلفية)
|
| 215 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
if sys_state.cycle_running:
|
| 217 |
+
print("⚠️ [Cycle] الدورة الحالية لا تزال قيد التشغيل. تم تجاهل الطلب.")
|
| 218 |
return
|
| 219 |
|
| 220 |
+
if not sys_state.ready:
|
| 221 |
+
print("⚠️ [Cycle] تم تجاهل الدورة، النظام لم يكتمل تهيئته.")
|
|
|
|
| 222 |
return
|
| 223 |
|
| 224 |
+
sys_state.set_cycle_start()
|
| 225 |
+
print(f"\n🌀 [Cycle START] {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 226 |
|
| 227 |
try:
|
| 228 |
+
# --- 1. تحديث العقود والبيانات (Data Refresh) ---
|
| 229 |
+
# (يتم تحديث العقود بشكل دوري داخل DataManager)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
+
# --- 2. التحليل (L1 Analysis) ---
|
| 232 |
+
print(" [Cycle 1/3] 🧠 تشغيل دورة تحليل L1 (Processor)...")
|
| 233 |
+
analysis_start_time = time.time()
|
| 234 |
+
# (المعالج يقوم بمسح السوق وإيجاد إشارات L1)
|
| 235 |
+
analysis_results = await ml_processor.run_analysis_cycle()
|
| 236 |
+
print(f" -> 🧠 انتهى تحليل L1 في {time.time() - analysis_start_time:.2f} ثانية. {len(analysis_results)} إشارة مرشحة.")
|
| 237 |
+
|
| 238 |
+
# --- 3. التنفيذ (L2 Confirmation & Execution) ---
|
| 239 |
+
print(" [Cycle 2/3] 🎯 تمرير النتائج إلى TradeManager (L2 Sniper)...")
|
| 240 |
+
execution_start_time = time.time()
|
| 241 |
|
| 242 |
+
# [ 🚀 🚀 🚀 ]
|
| 243 |
+
# [ 💡 💡 💡 ] التعديل: استدعاء الدالة الصحيحة في TradeManager
|
| 244 |
+
# (نفترض أن `trade_manager` لديه دالة `process_analysis_results` أو ما شابهها)
|
| 245 |
+
# بناءً على ملفك الكامل، الدالة التي يجب استدعاؤها هي `_handle_new_signal`
|
| 246 |
+
# لكن `_handle_new_signal` تتوقع (symbol, data) وليس قائمة
|
| 247 |
+
# لذا، سنقوم باللف هنا وتمرير الإشارات واحدة تلو الأخرى
|
|
|
|
|
|
|
|
|
|
| 248 |
|
| 249 |
+
# (فرز النتائج حسب الدرجة، من الأعلى للأدنى)
|
| 250 |
+
sorted_results = sorted(analysis_results, key=lambda x: x.get('enhanced_final_score', 0.0), reverse=True)
|
|
|
|
| 251 |
|
| 252 |
+
for signal in sorted_results:
|
| 253 |
+
# (نحن نمرر الإشارة فقط إذا كانت أعلى من العتبة)
|
| 254 |
+
if signal.get('enhanced_final_score', 0.0) >= data_manager.HYBRID_ENTRY_THRESHOLD:
|
| 255 |
+
await trade_manager._handle_new_signal(signal['symbol'], signal)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
|
| 257 |
+
# [ 🚀 🚀 🚀 ]
|
| 258 |
+
print(f" -> 🎯 انتهى فحص/تنفيذ L2 في {time.time() - execution_start_time:.2f} ثانية.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
+
# --- 4. التعلم (Learning) ---
|
| 261 |
+
print(" [Cycle 3/3] 📚 تحديث مركز التعلم (Learning Hub)...")
|
| 262 |
+
# (هذه الدالة تحتاج للتصميم)
|
| 263 |
+
# await learning_hub.process_new_trade_data(...)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
+
gc.collect() # تنظيف الذاكرة
|
| 266 |
+
print(f"🌀 [Cycle END] {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 267 |
+
sys_state.set_cycle_end()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
|
| 269 |
+
except Exception as e:
|
| 270 |
+
print(f"❌ [Cycle ERROR] فشلت الدورة الموحدة: {e}")
|
| 271 |
+
traceback.print_exc()
|
| 272 |
+
sys_state.set_cycle_end(error=e)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
# ==============================================================================
|
| 275 |
+
# 🚦 نقاط النهاية (API Endpoints)
|
| 276 |
+
# (هذا هو الجزء الذي كان ناقصاً)
|
| 277 |
# ==============================================================================
|
| 278 |
+
app = FastAPI(
|
| 279 |
+
lifespan=lifespan,
|
| 280 |
+
title="Titan V15.2 (Sniper + Guard)",
|
| 281 |
+
description="نظام تداول آلي هجين"
|
| 282 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
@app.get("/")
|
| 285 |
+
async def root_status():
|
| 286 |
"""فحص حالة النظام الأساسية"""
|
| 287 |
return {
|
| 288 |
"system_status": "ONLINE",
|
| 289 |
"initialized": sys_state.ready,
|
| 290 |
+
"guard_v2_active": guard_engine.initialized if guard_engine else False,
|
| 291 |
+
|
| 292 |
+
# [ 🚀 🚀 🚀 ]
|
| 293 |
+
# [ 💡 💡 💡 ] التعديل: إضافة حالة القناص
|
| 294 |
+
"sniper_v3_active": sniper_engine.initialized if sniper_engine else False,
|
| 295 |
+
# [ 🚀 🚀 🚀 ]
|
| 296 |
+
|
| 297 |
"current_mode": "RE-ANALYSIS" if trade_manager and trade_manager.open_positions else "EXPLORER"
|
| 298 |
}
|
| 299 |
|
|
|
|
| 318 |
"sentry_watchlist": list(trade_manager.watchlist.keys()) if trade_manager else []
|
| 319 |
}
|
| 320 |
|
| 321 |
+
# نقطة الدخول (للتشغيل المباشر)
|
| 322 |
+
# (للتشغيل في الخادم، استخدم: uvicorn app:app --host 0.0.0.0 --port 8000)
|
| 323 |
if __name__ == "__main__":
|
| 324 |
import uvicorn
|
| 325 |
+
print("⚠️ [Debug Mode] تشغيل الخادم مباشرة (للتطوير فقط)...")
|
| 326 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|