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
|
|
@@ -19,8 +19,12 @@ try:
|
|
| 19 |
from data_manager import DataManager
|
| 20 |
from ml_engine.processor import MLProcessor
|
| 21 |
from trade_manager import TradeManager
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
# وحدات الطبقة الثانية المتخصصة
|
| 25 |
from whale_monitor.core import EnhancedWhaleMonitor
|
| 26 |
from sentiment_news import NewsFetcher
|
|
@@ -40,8 +44,6 @@ r2: R2Service = None
|
|
| 40 |
data_manager: DataManager = None
|
| 41 |
ml_processor: MLProcessor = None
|
| 42 |
trade_manager: TradeManager = None
|
| 43 |
-
llm_service: LLMService = None
|
| 44 |
-
learning_hub: LearningHubManager = None
|
| 45 |
whale_monitor: EnhancedWhaleMonitor = None
|
| 46 |
news_fetcher: NewsFetcher = None
|
| 47 |
senti_analyzer: SentimentIntensityAnalyzer = None
|
|
@@ -50,8 +52,15 @@ sys_state: 'SystemState' = None
|
|
| 50 |
guard_engine: GuardEngine = None
|
| 51 |
sniper_engine: SniperEngine = None
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 54 |
SHARED_GUARD_MODELS_DIR = os.path.join(BASE_DIR, "ml_models", "guard_v2")
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
# ==============================================================================
|
| 57 |
# 🔄 حالة النظام (System State)
|
|
@@ -78,7 +87,9 @@ sys_state = SystemState()
|
|
| 78 |
# ==============================================================================
|
| 79 |
@asynccontextmanager
|
| 80 |
async def lifespan(app: FastAPI):
|
| 81 |
-
|
|
|
|
|
|
|
| 82 |
global whale_monitor, news_fetcher, senti_analyzer, guard_engine, sniper_engine, sys_state
|
| 83 |
|
| 84 |
print("🚀 [FastAPI] بدء التشغيل (Startup Event)...")
|
|
@@ -99,15 +110,18 @@ async def lifespan(app: FastAPI):
|
|
| 99 |
senti_analyzer = SentimentIntensityAnalyzer()
|
| 100 |
data_manager.whale_monitor = whale_monitor
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
| 108 |
|
| 109 |
print(" [6/8] تهيئة MLProcessor (L1 Engine)...")
|
| 110 |
-
|
|
|
|
|
|
|
| 111 |
await ml_processor.initialize()
|
| 112 |
|
| 113 |
print(f" -> [Guard Path] استخدام المسار المشترك للحارس: {SHARED_GUARD_MODELS_DIR}")
|
|
@@ -135,7 +149,7 @@ async def lifespan(app: FastAPI):
|
|
| 135 |
|
| 136 |
sys_state.set_ready()
|
| 137 |
print("------------------------------------------------------")
|
| 138 |
-
print("✅ [System READY] جميع الوحدات تم تهيئتها بنجاح.")
|
| 139 |
print("------------------------------------------------------")
|
| 140 |
|
| 141 |
yield
|
|
@@ -152,11 +166,14 @@ async def lifespan(app: FastAPI):
|
|
| 152 |
print("✅ [System SHUTDOWN] تم إغلاق جميع الاتصالات.")
|
| 153 |
|
| 154 |
# ==============================================================================
|
| 155 |
-
# 🧠 دوال التحليل المساعدة
|
| 156 |
# ==============================================================================
|
| 157 |
async def _analyze_symbol_task(symbol: str) -> Dict[str, Any]:
|
| 158 |
global data_manager, ml_processor
|
| 159 |
try:
|
|
|
|
|
|
|
|
|
|
| 160 |
required_tfs = ["5m", "15m", "1h", "4h", "1d"]
|
| 161 |
data_tasks = [data_manager.get_latest_ohlcv(symbol, tf, limit=250) for tf in required_tfs]
|
| 162 |
all_data = await asyncio.gather(*data_tasks)
|
|
@@ -165,7 +182,8 @@ async def _analyze_symbol_task(symbol: str) -> Dict[str, Any]:
|
|
| 165 |
for tf, data in zip(required_tfs, all_data):
|
| 166 |
if data and len(data) > 0: ohlcv_data[tf] = data
|
| 167 |
|
| 168 |
-
if '5m' not in ohlcv_data:
|
|
|
|
| 169 |
|
| 170 |
current_price = await data_manager.get_latest_price_async(symbol)
|
| 171 |
raw_data = {'symbol': symbol, 'ohlcv': ohlcv_data, 'current_price': current_price}
|
|
@@ -174,12 +192,11 @@ async def _analyze_symbol_task(symbol: str) -> Dict[str, Any]:
|
|
| 174 |
return None
|
| 175 |
|
| 176 |
# ==============================================================================
|
| 177 |
-
# [ 🚀 🚀 🚀 ] الدورة الموحدة (النسخة الكاملة V15.
|
| 178 |
# ==============================================================================
|
| 179 |
async def run_unified_cycle():
|
| 180 |
"""
|
| 181 |
-
دورة التحليل الكاملة: L1
|
| 182 |
-
(مع استعادة الطباعة التفصيلية L1 وإصلاح قراءة الدماغ)
|
| 183 |
"""
|
| 184 |
if sys_state.cycle_running:
|
| 185 |
print("⚠️ [Cycle] الدورة الحالية لا تزال قيد التشغيل. تم تجاهل الطلب.")
|
|
@@ -211,17 +228,14 @@ async def run_unified_cycle():
|
|
| 211 |
|
| 212 |
valid_l1_results = [res for res in results if res is not None]
|
| 213 |
|
| 214 |
-
# ترتيب واختيار أفضل 10 فقط من L1
|
| 215 |
top_10_l1 = sorted(valid_l1_results, key=lambda x: x.get('enhanced_final_score', 0.0), reverse=True)[:10]
|
| 216 |
|
| 217 |
print(f" -> 🧠 انتهى تحليل L1 في {time.time() - analysis_start_time:.2f} ثانية.")
|
| 218 |
print(f" - ✅ نجح: {len(valid_l1_results)} إشارة مرشحة.")
|
| 219 |
|
| 220 |
-
# [ 🚀 استعادة الطباعة التفصيلية للطبقة الأولى ]
|
| 221 |
if top_10_l1:
|
| 222 |
print(f"\n -> 🥇 أعلى 10 درجات في الطبقة الأولى (L1):")
|
| 223 |
for i, res in enumerate(top_10_l1):
|
| 224 |
-
# استخراج المكونات بالتفصيل
|
| 225 |
components = res.get('components', {})
|
| 226 |
titan_s = components.get('titan_score', 0.0)
|
| 227 |
pattern_s = components.get('patterns_score', 0.0)
|
|
@@ -242,34 +256,26 @@ async def run_unified_cycle():
|
|
| 242 |
symbol = candidate['symbol']
|
| 243 |
l1_score = candidate['enhanced_final_score']
|
| 244 |
|
| 245 |
-
# تهيئة متغيرات النقاط والقيم الخام
|
| 246 |
whale_score = 0.0
|
| 247 |
whale_raw_str = "No Data"
|
| 248 |
-
|
| 249 |
news_score = 0.0
|
| 250 |
news_raw_str = "No Data"
|
| 251 |
-
|
| 252 |
adv_mc_score = 0.0
|
| 253 |
mc_raw_str = "No Data"
|
| 254 |
|
| 255 |
-
# أ. بيانات الحيتان
|
| 256 |
whale_data = {}
|
| 257 |
try:
|
| 258 |
whale_data = await whale_monitor.get_symbol_whale_activity(symbol)
|
| 259 |
net_flow = whale_data.get('accumulation_analysis_24h', {}).get('net_flow_usd', 0.0)
|
| 260 |
-
|
| 261 |
-
# تسجيل القيمة الخام للعرض
|
| 262 |
whale_raw_str = f"${net_flow:,.0f}"
|
| 263 |
-
|
| 264 |
-
# منطق النقاط
|
| 265 |
if net_flow <= -500000: whale_score = 0.10
|
| 266 |
elif net_flow < 0: whale_score = 0.05
|
| 267 |
except Exception as e:
|
| 268 |
print(f" ⚠️ [Whale Error] {symbol}: {e}")
|
| 269 |
-
|
| 270 |
candidate['whale_data'] = whale_data
|
| 271 |
|
| 272 |
-
# ب. الأخبار
|
| 273 |
news_text = "No news available"
|
| 274 |
try:
|
| 275 |
if hasattr(news_fetcher, 'get_news'):
|
|
@@ -283,35 +289,26 @@ async def run_unified_cycle():
|
|
| 283 |
news_text = news_item.get('summary', 'No news')
|
| 284 |
sentiment = senti_analyzer.polarity_scores(news_text)
|
| 285 |
compound = sentiment['compound']
|
| 286 |
-
|
| 287 |
-
# تسجيل القيمة الخام للعرض
|
| 288 |
news_raw_str = f"{compound:.2f}"
|
| 289 |
-
|
| 290 |
-
# منطق النقاط
|
| 291 |
if compound >= 0.5: news_score = 0.05
|
| 292 |
elif compound >= 0.1: news_score = 0.02
|
| 293 |
except Exception as e:
|
| 294 |
print(f" ⚠️ [News Error] {symbol}: {e}")
|
| 295 |
-
|
| 296 |
candidate['news_text'] = news_text
|
| 297 |
|
| 298 |
-
# ج. مونت كارلو المتقدمة
|
| 299 |
try:
|
| 300 |
full_ohlcv_1h = await data_manager.get_latest_ohlcv(symbol, '1h', limit=100)
|
| 301 |
|
| 302 |
if not full_ohlcv_1h or len(full_ohlcv_1h) < 30:
|
| 303 |
-
|
| 304 |
else:
|
| 305 |
mc_data = {'1h': full_ohlcv_1h}
|
| 306 |
mc_res = await ml_processor.mc_analyzer.generate_1h_distribution_advanced(mc_data)
|
| 307 |
|
| 308 |
if mc_res and not mc_res.get('error', False):
|
| 309 |
prob_gain = mc_res.get('probability_of_gain', 0.5)
|
| 310 |
-
|
| 311 |
-
# تسجيل القيمة الخام للعرض (الاحتمالية الأصلية)
|
| 312 |
mc_raw_str = f"{prob_gain:.2f}"
|
| 313 |
-
|
| 314 |
-
# منطق النقاط: زيادة تدريجية إذا الاحتمال > 50%
|
| 315 |
if prob_gain > 0.5:
|
| 316 |
adv_mc_score = min(0.10, (prob_gain - 0.5) * 0.20)
|
| 317 |
else:
|
|
@@ -319,36 +316,20 @@ async def run_unified_cycle():
|
|
| 319 |
else:
|
| 320 |
reason = mc_res.get('reason', 'Unknown') if mc_res else "Null Result"
|
| 321 |
mc_raw_str = f"Err: {reason}"
|
| 322 |
-
|
| 323 |
except Exception as e:
|
| 324 |
print(f" ⚠️ [MC Exception] {symbol}: {e}")
|
| 325 |
|
| 326 |
-
#
|
| 327 |
final_score = l1_score + whale_score + news_score + adv_mc_score
|
| 328 |
-
|
| 329 |
candidate['final_total_score'] = final_score
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
candidate['l2_scores'] = {
|
| 333 |
-
'whale': whale_score,
|
| 334 |
-
'news': news_score,
|
| 335 |
-
'adv_mc': adv_mc_score
|
| 336 |
-
}
|
| 337 |
-
# تخزين القيم الأصلية للعرض (الشفافية)
|
| 338 |
-
candidate['l2_raw_values'] = {
|
| 339 |
-
'whale': whale_raw_str,
|
| 340 |
-
'news': news_raw_str,
|
| 341 |
-
'adv_mc': mc_raw_str
|
| 342 |
-
}
|
| 343 |
-
|
| 344 |
l2_enriched_candidates.append(candidate)
|
| 345 |
|
| 346 |
-
# --- 3. إعادة الترتيب وطباعة الجدول (
|
| 347 |
print(f" [Cycle 3/5] 📊 إعادة ترتيب المرشحين حسب الدرجة النهائية (L1 + L2)...")
|
| 348 |
-
|
| 349 |
sorted_finalists = sorted(l2_enriched_candidates, key=lambda x: x['final_total_score'], reverse=True)
|
| 350 |
|
| 351 |
-
# توسيع عرض الأعمدة لاستيعاب (Raw Values)
|
| 352 |
print("\n" + "="*135)
|
| 353 |
header = f"{'SYMBOL':<10} | {'L1 SCORE':<8} | {'WHALE (Flow)':<22} | {'NEWS (Sent)':<18} | {'ADV MC (Prob)':<18} | {'FINAL':<8}"
|
| 354 |
print(header)
|
|
@@ -357,26 +338,22 @@ async def run_unified_cycle():
|
|
| 357 |
for cand in sorted_finalists:
|
| 358 |
sym = cand['symbol']
|
| 359 |
l1 = cand['enhanced_final_score']
|
| 360 |
-
|
| 361 |
l2 = cand['l2_scores']
|
| 362 |
l2_raw = cand['l2_raw_values']
|
| 363 |
-
|
| 364 |
final = cand['final_total_score']
|
| 365 |
-
|
| 366 |
-
# تنسيق الخلايا: Score (Raw)
|
| 367 |
whale_cell = f"{l2['whale']:.2f} ({l2_raw['whale']})"
|
| 368 |
news_cell = f"{l2['news']:.2f} ({l2_raw['news']})"
|
| 369 |
mc_cell = f"{l2['adv_mc']:.2f} ({l2_raw['adv_mc']})"
|
| 370 |
-
|
| 371 |
print(f"{sym:<10} | {l1:.4f} | {whale_cell:<22} | {news_cell:<18} | {mc_cell:<18} | {final:.4f}")
|
| 372 |
|
| 373 |
print("="*135 + "\n")
|
| 374 |
|
|
|
|
| 375 |
# --- 4. اختيار أفضل 5 للنموذج الضخم ---
|
| 376 |
top_5_candidates = sorted_finalists[:5]
|
| 377 |
-
print(f" [Cycle 4/5] 🧠 إرسال أفضل {len(top_5_candidates)} عملة لل
|
| 378 |
|
| 379 |
-
|
| 380 |
processed_count = 0
|
| 381 |
|
| 382 |
for signal in top_5_candidates:
|
|
@@ -386,48 +363,41 @@ async def run_unified_cycle():
|
|
| 386 |
print(f" -> 🛑 {symbol} تم استبعاده (الدرجة النهائية {signal['final_total_score']:.2f} < 0.60)")
|
| 387 |
continue
|
| 388 |
|
| 389 |
-
print(f" -> 🧠 [
|
| 390 |
|
| 391 |
try:
|
| 392 |
-
# استدعاء ال
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
llm_decision.get('reasoning') or
|
| 408 |
-
llm_decision.get('reason') or
|
| 409 |
-
'No reason provided'
|
| 410 |
-
)
|
| 411 |
-
|
| 412 |
-
if action == 'WATCH':
|
| 413 |
-
print(f" 🔥 [Brain APPROVED] {symbol} (Conf: {confidence:.2f})")
|
| 414 |
-
print(f" 📝 Reason: {reason[:200]}...")
|
| 415 |
print(f" -> 🎯 تحويل إلى القناص (Sniper) للتنفيذ...")
|
| 416 |
await trade_manager._handle_new_signal(symbol, signal)
|
| 417 |
processed_count += 1
|
| 418 |
else:
|
| 419 |
-
print(f" 🛑 [
|
| 420 |
-
print(f" 📝 Reason: {reason[:200]}...")
|
| 421 |
|
| 422 |
except Exception as e:
|
| 423 |
-
print(f" ⚠️ [
|
| 424 |
traceback.print_exc()
|
| 425 |
continue
|
| 426 |
|
| 427 |
-
print(f" -> 🧠 انتهى فحص
|
|
|
|
| 428 |
|
| 429 |
# --- 5. الصيانة والتعلم ---
|
| 430 |
-
print(f" [Cycle 5/5] 🧹 تنظيف الذاكرة
|
| 431 |
gc.collect()
|
| 432 |
print(f"🌀 [Cycle END] {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 433 |
sys_state.set_cycle_end()
|
|
@@ -442,8 +412,10 @@ async def run_unified_cycle():
|
|
| 442 |
# ==============================================================================
|
| 443 |
app = FastAPI(
|
| 444 |
lifespan=lifespan,
|
| 445 |
-
|
| 446 |
-
|
|
|
|
|
|
|
| 447 |
)
|
| 448 |
|
| 449 |
@app.get("/")
|
|
@@ -451,6 +423,7 @@ async def root_status():
|
|
| 451 |
return {
|
| 452 |
"system_status": "ONLINE",
|
| 453 |
"initialized": sys_state.ready,
|
|
|
|
| 454 |
"guard_v2_active": guard_engine.initialized if guard_engine else False,
|
| 455 |
"sniper_v3_active": sniper_engine.initialized if sniper_engine else False,
|
| 456 |
"current_mode": "RE-ANALYSIS" if trade_manager and trade_manager.open_positions else "EXPLORER"
|
|
@@ -461,7 +434,7 @@ async def trigger_cycle_endpoint(background_tasks: BackgroundTasks):
|
|
| 461 |
if not sys_state.ready:
|
| 462 |
raise HTTPException(status_code=503, detail="System is still initializing.")
|
| 463 |
background_tasks.add_task(run_unified_cycle)
|
| 464 |
-
return {"status": "ACCEPTED", "message": "Unified smart cycle triggered."}
|
| 465 |
|
| 466 |
@app.get("/status")
|
| 467 |
async def get_full_status():
|
|
|
|
| 1 |
+
# app.py (V15.16 - OracleEngine Integration)
|
| 2 |
import os
|
| 3 |
import sys
|
| 4 |
import traceback
|
|
|
|
| 19 |
from data_manager import DataManager
|
| 20 |
from ml_engine.processor import MLProcessor
|
| 21 |
from trade_manager import TradeManager
|
| 22 |
+
|
| 23 |
+
# --- [ 🔴 التعديل: استبدال LLM بـ OracleEngine ] ---
|
| 24 |
+
from ml_engine.oracle_engine import OracleEngine
|
| 25 |
+
# (تمت إزالة LLMService و LearningHubManager)
|
| 26 |
+
# --- [ نهاية التعديل ] ---
|
| 27 |
+
|
| 28 |
# وحدات الطبقة الثانية المتخصصة
|
| 29 |
from whale_monitor.core import EnhancedWhaleMonitor
|
| 30 |
from sentiment_news import NewsFetcher
|
|
|
|
| 44 |
data_manager: DataManager = None
|
| 45 |
ml_processor: MLProcessor = None
|
| 46 |
trade_manager: TradeManager = None
|
|
|
|
|
|
|
| 47 |
whale_monitor: EnhancedWhaleMonitor = None
|
| 48 |
news_fetcher: NewsFetcher = None
|
| 49 |
senti_analyzer: SentimentIntensityAnalyzer = None
|
|
|
|
| 52 |
guard_engine: GuardEngine = None
|
| 53 |
sniper_engine: SniperEngine = None
|
| 54 |
|
| 55 |
+
# --- [ 🔴 التعديل: إضافة OracleEngine ] ---
|
| 56 |
+
oracle_engine: OracleEngine = None
|
| 57 |
+
# --- [ نهاية التعديل ] ---
|
| 58 |
+
|
| 59 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 60 |
SHARED_GUARD_MODELS_DIR = os.path.join(BASE_DIR, "ml_models", "guard_v2")
|
| 61 |
+
# --- [ 🔴 التعديل: إضافة مسار Oracle ] ---
|
| 62 |
+
UNIFIED_MODELS_DIR = os.path.join(BASE_DIR, "ml_models", "Unified_Models_V1")
|
| 63 |
+
# --- [ نهاية التعديل ] ---
|
| 64 |
|
| 65 |
# ==============================================================================
|
| 66 |
# 🔄 حالة النظام (System State)
|
|
|
|
| 87 |
# ==============================================================================
|
| 88 |
@asynccontextmanager
|
| 89 |
async def lifespan(app: FastAPI):
|
| 90 |
+
# --- [ 🔴 التعديل: إضافة Oracle للمتغيرات العالمية ] ---
|
| 91 |
+
global r2, data_manager, ml_processor, trade_manager, oracle_engine
|
| 92 |
+
# --- [ نهاية التعديل ] ---
|
| 93 |
global whale_monitor, news_fetcher, senti_analyzer, guard_engine, sniper_engine, sys_state
|
| 94 |
|
| 95 |
print("🚀 [FastAPI] بدء التشغيل (Startup Event)...")
|
|
|
|
| 110 |
senti_analyzer = SentimentIntensityAnalyzer()
|
| 111 |
data_manager.whale_monitor = whale_monitor
|
| 112 |
|
| 113 |
+
# --- [ 🔴 التعديل: استبدال LLM و LearningHub بـ OracleEngine ] ---
|
| 114 |
+
print(f" [4/8] تهيئة OracleEngine (L3 Brain) من {UNIFIED_MODELS_DIR}...")
|
| 115 |
+
oracle_engine = OracleEngine(model_dir=UNIFIED_MODELS_DIR)
|
| 116 |
+
await oracle_engine.initialize()
|
| 117 |
+
|
| 118 |
+
print(" [5/8] (تم تخطي LearningHub - مدمج في Oracle)")
|
| 119 |
+
# --- [ نهاية التعديل ] ---
|
| 120 |
|
| 121 |
print(" [6/8] تهيئة MLProcessor (L1 Engine)...")
|
| 122 |
+
# --- [ 🔴 التعديل: إزالة learning_hub من MLProcessor ] ---
|
| 123 |
+
ml_processor = MLProcessor(market_context=None, data_manager=data_manager, learning_hub=None)
|
| 124 |
+
# --- [ نهاية التعديل ] ---
|
| 125 |
await ml_processor.initialize()
|
| 126 |
|
| 127 |
print(f" -> [Guard Path] استخدام المسار المشترك للحارس: {SHARED_GUARD_MODELS_DIR}")
|
|
|
|
| 149 |
|
| 150 |
sys_state.set_ready()
|
| 151 |
print("------------------------------------------------------")
|
| 152 |
+
print("✅ [System READY] جميع الوحدات تم تهيئتها بنجاح (وضع Oracle).")
|
| 153 |
print("------------------------------------------------------")
|
| 154 |
|
| 155 |
yield
|
|
|
|
| 166 |
print("✅ [System SHUTDOWN] تم إغلاق جميع الاتصالات.")
|
| 167 |
|
| 168 |
# ==============================================================================
|
| 169 |
+
# 🧠 دوال التحليل المساعدة (لا تغيير هنا)
|
| 170 |
# ==============================================================================
|
| 171 |
async def _analyze_symbol_task(symbol: str) -> Dict[str, Any]:
|
| 172 |
global data_manager, ml_processor
|
| 173 |
try:
|
| 174 |
+
# (🔴 ملاحظة: OracleEngine يحتاج لأطر 15m, 1h, 4h)
|
| 175 |
+
# (L1/L2 يحتاج 5m, 15m, 1h, 4h, 1d)
|
| 176 |
+
# لذا، هذه القائمة صحيحة وتغطي كل الاحتياجات
|
| 177 |
required_tfs = ["5m", "15m", "1h", "4h", "1d"]
|
| 178 |
data_tasks = [data_manager.get_latest_ohlcv(symbol, tf, limit=250) for tf in required_tfs]
|
| 179 |
all_data = await asyncio.gather(*data_tasks)
|
|
|
|
| 182 |
for tf, data in zip(required_tfs, all_data):
|
| 183 |
if data and len(data) > 0: ohlcv_data[tf] = data
|
| 184 |
|
| 185 |
+
if '5m' not in ohlcv_data or '1h' not in ohlcv_data: # (التأكد من وجود بيانات كافية)
|
| 186 |
+
return None
|
| 187 |
|
| 188 |
current_price = await data_manager.get_latest_price_async(symbol)
|
| 189 |
raw_data = {'symbol': symbol, 'ohlcv': ohlcv_data, 'current_price': current_price}
|
|
|
|
| 192 |
return None
|
| 193 |
|
| 194 |
# ==============================================================================
|
| 195 |
+
# [ 🚀 🚀 🚀 ] الدورة الموحدة (النسخة الكاملة V15.16 - Oracle)
|
| 196 |
# ==============================================================================
|
| 197 |
async def run_unified_cycle():
|
| 198 |
"""
|
| 199 |
+
دورة التحليل الكاملة: L1 -> L2 -> L3 (Oracle) -> L4 (Sniper).
|
|
|
|
| 200 |
"""
|
| 201 |
if sys_state.cycle_running:
|
| 202 |
print("⚠️ [Cycle] الدورة الحالية لا تزال قيد التشغيل. تم تجاهل الطلب.")
|
|
|
|
| 228 |
|
| 229 |
valid_l1_results = [res for res in results if res is not None]
|
| 230 |
|
|
|
|
| 231 |
top_10_l1 = sorted(valid_l1_results, key=lambda x: x.get('enhanced_final_score', 0.0), reverse=True)[:10]
|
| 232 |
|
| 233 |
print(f" -> 🧠 انتهى تحليل L1 في {time.time() - analysis_start_time:.2f} ثانية.")
|
| 234 |
print(f" - ✅ نجح: {len(valid_l1_results)} إشارة مرشحة.")
|
| 235 |
|
|
|
|
| 236 |
if top_10_l1:
|
| 237 |
print(f"\n -> 🥇 أعلى 10 درجات في الطبقة الأولى (L1):")
|
| 238 |
for i, res in enumerate(top_10_l1):
|
|
|
|
| 239 |
components = res.get('components', {})
|
| 240 |
titan_s = components.get('titan_score', 0.0)
|
| 241 |
pattern_s = components.get('patterns_score', 0.0)
|
|
|
|
| 256 |
symbol = candidate['symbol']
|
| 257 |
l1_score = candidate['enhanced_final_score']
|
| 258 |
|
|
|
|
| 259 |
whale_score = 0.0
|
| 260 |
whale_raw_str = "No Data"
|
|
|
|
| 261 |
news_score = 0.0
|
| 262 |
news_raw_str = "No Data"
|
|
|
|
| 263 |
adv_mc_score = 0.0
|
| 264 |
mc_raw_str = "No Data"
|
| 265 |
|
| 266 |
+
# (أ. بيانات الحيتان)
|
| 267 |
whale_data = {}
|
| 268 |
try:
|
| 269 |
whale_data = await whale_monitor.get_symbol_whale_activity(symbol)
|
| 270 |
net_flow = whale_data.get('accumulation_analysis_24h', {}).get('net_flow_usd', 0.0)
|
|
|
|
|
|
|
| 271 |
whale_raw_str = f"${net_flow:,.0f}"
|
|
|
|
|
|
|
| 272 |
if net_flow <= -500000: whale_score = 0.10
|
| 273 |
elif net_flow < 0: whale_score = 0.05
|
| 274 |
except Exception as e:
|
| 275 |
print(f" ⚠️ [Whale Error] {symbol}: {e}")
|
|
|
|
| 276 |
candidate['whale_data'] = whale_data
|
| 277 |
|
| 278 |
+
# (ب. الأخبار)
|
| 279 |
news_text = "No news available"
|
| 280 |
try:
|
| 281 |
if hasattr(news_fetcher, 'get_news'):
|
|
|
|
| 289 |
news_text = news_item.get('summary', 'No news')
|
| 290 |
sentiment = senti_analyzer.polarity_scores(news_text)
|
| 291 |
compound = sentiment['compound']
|
|
|
|
|
|
|
| 292 |
news_raw_str = f"{compound:.2f}"
|
|
|
|
|
|
|
| 293 |
if compound >= 0.5: news_score = 0.05
|
| 294 |
elif compound >= 0.1: news_score = 0.02
|
| 295 |
except Exception as e:
|
| 296 |
print(f" ⚠️ [News Error] {symbol}: {e}")
|
|
|
|
| 297 |
candidate['news_text'] = news_text
|
| 298 |
|
| 299 |
+
# (ج. مونت كارلو المتقدمة)
|
| 300 |
try:
|
| 301 |
full_ohlcv_1h = await data_manager.get_latest_ohlcv(symbol, '1h', limit=100)
|
| 302 |
|
| 303 |
if not full_ohlcv_1h or len(full_ohlcv_1h) < 30:
|
| 304 |
+
pass # (تقليل الضجيج)
|
| 305 |
else:
|
| 306 |
mc_data = {'1h': full_ohlcv_1h}
|
| 307 |
mc_res = await ml_processor.mc_analyzer.generate_1h_distribution_advanced(mc_data)
|
| 308 |
|
| 309 |
if mc_res and not mc_res.get('error', False):
|
| 310 |
prob_gain = mc_res.get('probability_of_gain', 0.5)
|
|
|
|
|
|
|
| 311 |
mc_raw_str = f"{prob_gain:.2f}"
|
|
|
|
|
|
|
| 312 |
if prob_gain > 0.5:
|
| 313 |
adv_mc_score = min(0.10, (prob_gain - 0.5) * 0.20)
|
| 314 |
else:
|
|
|
|
| 316 |
else:
|
| 317 |
reason = mc_res.get('reason', 'Unknown') if mc_res else "Null Result"
|
| 318 |
mc_raw_str = f"Err: {reason}"
|
|
|
|
| 319 |
except Exception as e:
|
| 320 |
print(f" ⚠️ [MC Exception] {symbol}: {e}")
|
| 321 |
|
| 322 |
+
# (د. حساب الدرجة النهائية)
|
| 323 |
final_score = l1_score + whale_score + news_score + adv_mc_score
|
|
|
|
| 324 |
candidate['final_total_score'] = final_score
|
| 325 |
+
candidate['l2_scores'] = {'whale': whale_score, 'news': news_score, 'adv_mc': adv_mc_score}
|
| 326 |
+
candidate['l2_raw_values'] = {'whale': whale_raw_str, 'news': news_raw_str, 'adv_mc': mc_raw_str}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
l2_enriched_candidates.append(candidate)
|
| 328 |
|
| 329 |
+
# --- 3. إعادة الترتيب وطباعة الجدول (لا تغيير هنا) ---
|
| 330 |
print(f" [Cycle 3/5] 📊 إعادة ترتيب المرشحين حسب الدرجة النهائية (L1 + L2)...")
|
|
|
|
| 331 |
sorted_finalists = sorted(l2_enriched_candidates, key=lambda x: x['final_total_score'], reverse=True)
|
| 332 |
|
|
|
|
| 333 |
print("\n" + "="*135)
|
| 334 |
header = f"{'SYMBOL':<10} | {'L1 SCORE':<8} | {'WHALE (Flow)':<22} | {'NEWS (Sent)':<18} | {'ADV MC (Prob)':<18} | {'FINAL':<8}"
|
| 335 |
print(header)
|
|
|
|
| 338 |
for cand in sorted_finalists:
|
| 339 |
sym = cand['symbol']
|
| 340 |
l1 = cand['enhanced_final_score']
|
|
|
|
| 341 |
l2 = cand['l2_scores']
|
| 342 |
l2_raw = cand['l2_raw_values']
|
|
|
|
| 343 |
final = cand['final_total_score']
|
|
|
|
|
|
|
| 344 |
whale_cell = f"{l2['whale']:.2f} ({l2_raw['whale']})"
|
| 345 |
news_cell = f"{l2['news']:.2f} ({l2_raw['news']})"
|
| 346 |
mc_cell = f"{l2['adv_mc']:.2f} ({l2_raw['adv_mc']})"
|
|
|
|
| 347 |
print(f"{sym:<10} | {l1:.4f} | {whale_cell:<22} | {news_cell:<18} | {mc_cell:<18} | {final:.4f}")
|
| 348 |
|
| 349 |
print("="*135 + "\n")
|
| 350 |
|
| 351 |
+
# --- [ 🔴 🔴 🔴 التعديل: خطوة 4 - استبدال LLM بـ OracleEngine ] ---
|
| 352 |
# --- 4. اختيار أفضل 5 للنموذج الضخم ---
|
| 353 |
top_5_candidates = sorted_finalists[:5]
|
| 354 |
+
print(f" [Cycle 4/5] 🧠 إرسال أفضل {len(top_5_candidates)} عملة للعقل الاحتمالي (Oracle Engine)...")
|
| 355 |
|
| 356 |
+
oracle_start_time = time.time()
|
| 357 |
processed_count = 0
|
| 358 |
|
| 359 |
for signal in top_5_candidates:
|
|
|
|
| 363 |
print(f" -> 🛑 {symbol} تم استبعاده (الدرجة النهائية {signal['final_total_score']:.2f} < 0.60)")
|
| 364 |
continue
|
| 365 |
|
| 366 |
+
print(f" -> 🧠 [Oracle Scan] جاري فحص {symbol}...")
|
| 367 |
|
| 368 |
try:
|
| 369 |
+
# استدعاء العقل الاحتمالي (Oracle)
|
| 370 |
+
oracle_decision = await oracle_engine.predict(signal)
|
| 371 |
+
|
| 372 |
+
action = oracle_decision.get('action')
|
| 373 |
+
confidence = oracle_decision.get('confidence', 0.0)
|
| 374 |
+
reason = oracle_decision.get('analysis_summary', 'No summary')
|
| 375 |
+
|
| 376 |
+
if action == 'WATCH': # (نحن نبحث عن 'WATCH' بناءً على كود Oracle)
|
| 377 |
+
print(f" 🔥 [Oracle APPROVED] {symbol} (Conf: {confidence:.2f})")
|
| 378 |
+
print(f" 📝 Reason: {reason}")
|
| 379 |
+
|
| 380 |
+
# (إضافة الأهداف المحددة إلى الإشارة)
|
| 381 |
+
signal['tp_price'] = oracle_decision.get('tp_price')
|
| 382 |
+
signal['sl_price'] = oracle_decision.get('sl_price')
|
| 383 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
print(f" -> 🎯 تحويل إلى القناص (Sniper) للتنفيذ...")
|
| 385 |
await trade_manager._handle_new_signal(symbol, signal)
|
| 386 |
processed_count += 1
|
| 387 |
else:
|
| 388 |
+
print(f" 🛑 [Oracle REJECTED] {symbol} (Conf: {confidence:.2f})")
|
| 389 |
+
print(f" 📝 Reason: {reason[:200]}...")
|
| 390 |
|
| 391 |
except Exception as e:
|
| 392 |
+
print(f" ⚠️ [Oracle Error] فشل تحليل Oracle لـ {symbol}: {e}")
|
| 393 |
traceback.print_exc()
|
| 394 |
continue
|
| 395 |
|
| 396 |
+
print(f" -> 🧠 انتهى فحص Oracle في {time.time() - oracle_start_time:.2f} ثانية. (تمت الموافقة على {processed_count} إشارة)")
|
| 397 |
+
# --- [ 🔴 🔴 🔴 نهاية التعديل ] ---
|
| 398 |
|
| 399 |
# --- 5. الصيانة والتعلم ---
|
| 400 |
+
print(f" [Cycle 5/5] 🧹 تنظيف الذاكرة...")
|
| 401 |
gc.collect()
|
| 402 |
print(f"🌀 [Cycle END] {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 403 |
sys_state.set_cycle_end()
|
|
|
|
| 412 |
# ==============================================================================
|
| 413 |
app = FastAPI(
|
| 414 |
lifespan=lifespan,
|
| 415 |
+
# --- [ 🔴 التعديل: تحديث العنوان ] ---
|
| 416 |
+
title="Titan V16.0 (Oracle Engine - Probabilistic)",
|
| 417 |
+
description="نظام تداول آلي هجين (L1/L2/L3-ML) مع قرار احتمالي"
|
| 418 |
+
# --- [ نهاية التعديل ] ---
|
| 419 |
)
|
| 420 |
|
| 421 |
@app.get("/")
|
|
|
|
| 423 |
return {
|
| 424 |
"system_status": "ONLINE",
|
| 425 |
"initialized": sys_state.ready,
|
| 426 |
+
"brain_type": "Oracle_Engine_V2", # (تحديث الحالة)
|
| 427 |
"guard_v2_active": guard_engine.initialized if guard_engine else False,
|
| 428 |
"sniper_v3_active": sniper_engine.initialized if sniper_engine else False,
|
| 429 |
"current_mode": "RE-ANALYSIS" if trade_manager and trade_manager.open_positions else "EXPLORER"
|
|
|
|
| 434 |
if not sys_state.ready:
|
| 435 |
raise HTTPException(status_code=503, detail="System is still initializing.")
|
| 436 |
background_tasks.add_task(run_unified_cycle)
|
| 437 |
+
return {"status": "ACCEPTED", "message": "Unified smart cycle triggered (Oracle Mode)."}
|
| 438 |
|
| 439 |
@app.get("/status")
|
| 440 |
async def get_full_status():
|