Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app.py (V17.
|
| 2 |
import os
|
| 3 |
import sys
|
| 4 |
import traceback
|
|
@@ -12,15 +12,15 @@ from io import StringIO
|
|
| 12 |
from fastapi import FastAPI, HTTPException, BackgroundTasks
|
| 13 |
from typing import List, Dict, Any
|
| 14 |
|
| 15 |
-
# [
|
| 16 |
import gradio as gr
|
| 17 |
import pandas as pd
|
| 18 |
import matplotlib.pyplot as plt
|
| 19 |
import matplotlib.dates as mdates
|
| 20 |
-
plt.switch_backend('Agg')
|
| 21 |
|
| 22 |
# ==============================================================================
|
| 23 |
-
# 📥 استيراد الوحدات الأساسية
|
| 24 |
# ==============================================================================
|
| 25 |
try:
|
| 26 |
from r2 import R2Service
|
|
@@ -34,22 +34,22 @@ try:
|
|
| 34 |
from ml_engine.guard_engine import GuardEngine
|
| 35 |
from ml_engine.sniper_engine import SniperEngine
|
| 36 |
except ImportError as e:
|
| 37 |
-
|
| 38 |
|
| 39 |
# ==============================================================================
|
| 40 |
-
# 🌐 المتغيرات العامة
|
| 41 |
# ==============================================================================
|
| 42 |
-
r2
|
| 43 |
-
data_manager
|
| 44 |
-
ml_processor
|
| 45 |
-
trade_manager
|
| 46 |
-
whale_monitor
|
| 47 |
-
news_fetcher
|
| 48 |
-
senti_analyzer
|
| 49 |
-
sys_state
|
| 50 |
-
guard_engine
|
| 51 |
-
sniper_engine
|
| 52 |
-
oracle_engine
|
| 53 |
|
| 54 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 55 |
SHARED_GUARD_MODELS_DIR = os.path.join(BASE_DIR, "ml_models", "guard_v2")
|
|
@@ -62,81 +62,83 @@ class SystemState:
|
|
| 62 |
def __init__(self):
|
| 63 |
self.ready = False
|
| 64 |
self.cycle_running = False
|
| 65 |
-
self.
|
| 66 |
-
self.
|
| 67 |
-
self.app_start_time = datetime.now()
|
| 68 |
-
# مخزن مؤقت لآخر سجلات الدورة
|
| 69 |
-
self.last_cycle_logs = "النظام قيد التهيئة... يرجى الانتظار."
|
| 70 |
|
| 71 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
self.ready = True
|
| 73 |
-
self.
|
| 74 |
-
|
| 75 |
-
def set_cycle_start(self):
|
| 76 |
-
self.cycle_running = True
|
| 77 |
-
self.last_cycle_logs = "🌀 [Cycle START] جاري العمل..."
|
| 78 |
|
| 79 |
-
def
|
| 80 |
-
self.
|
| 81 |
-
self.
|
| 82 |
-
self.
|
| 83 |
-
if logs:
|
| 84 |
-
self.last_cycle_logs = logs
|
| 85 |
-
elif error:
|
| 86 |
-
self.last_cycle_logs = f"❌ [Cycle ERROR] {error}"
|
| 87 |
-
else:
|
| 88 |
-
self.last_cycle_logs = f"✅ [Cycle END] {datetime.now().strftime('%H:%M:%S')}. الدورة انتهت."
|
| 89 |
|
| 90 |
sys_state = SystemState()
|
| 91 |
|
| 92 |
# ==============================================================================
|
| 93 |
-
#
|
| 94 |
# ==============================================================================
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
| 97 |
global r2, data_manager, ml_processor, trade_manager, oracle_engine
|
| 98 |
global whale_monitor, news_fetcher, senti_analyzer, guard_engine, sniper_engine, sys_state
|
| 99 |
-
|
| 100 |
-
print("🚀 [System] Starting Up (V17.6 Full)...")
|
| 101 |
-
print("------------------------------------------------------")
|
| 102 |
-
|
| 103 |
try:
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
r2 = R2Service()
|
| 106 |
|
| 107 |
-
|
|
|
|
| 108 |
data_manager = DataManager(contracts_db={}, whale_monitor=None, r2_service=r2)
|
| 109 |
-
await data_manager.initialize()
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
|
|
|
|
| 113 |
whale_monitor = EnhancedWhaleMonitor(contracts_db=data_manager.get_contracts_db(), r2_service=r2)
|
| 114 |
news_fetcher = NewsFetcher()
|
| 115 |
senti_analyzer = SentimentIntensityAnalyzer()
|
| 116 |
data_manager.whale_monitor = whale_monitor
|
| 117 |
|
| 118 |
-
|
|
|
|
| 119 |
oracle_engine = OracleEngine(model_dir=UNIFIED_MODELS_DIR)
|
| 120 |
await oracle_engine.initialize()
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
print(" [6/8] تهيئة MLProcessor (L1 Engine)...")
|
| 125 |
ml_processor = MLProcessor(market_context=None, data_manager=data_manager, learning_hub=None)
|
| 126 |
await ml_processor.initialize()
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
print(" [7/8] تهيئة GuardEngine (L2 Exit Protector)...")
|
| 131 |
guard_engine = GuardEngine(models_dir=SHARED_GUARD_MODELS_DIR)
|
| 132 |
await guard_engine.initialize()
|
| 133 |
|
| 134 |
-
|
|
|
|
| 135 |
sniper_engine = SniperEngine(models_dir=SHARED_GUARD_MODELS_DIR)
|
| 136 |
await sniper_engine.initialize()
|
| 137 |
-
sniper_engine.set_entry_threshold(0.35)
|
| 138 |
|
| 139 |
-
|
|
|
|
| 140 |
trade_manager = TradeManager(
|
| 141 |
r2_service=r2,
|
| 142 |
data_manager=data_manager,
|
|
@@ -145,30 +147,31 @@ async def lifespan(app: FastAPI):
|
|
| 145 |
guard_engine=guard_engine,
|
| 146 |
sniper_engine=sniper_engine
|
| 147 |
)
|
| 148 |
-
# تحميل الحالة فوراً من R2
|
| 149 |
await trade_manager.initialize_sentry_exchanges()
|
| 150 |
await trade_manager.start_sentry_loops()
|
| 151 |
|
| 152 |
sys_state.set_ready()
|
| 153 |
-
|
| 154 |
-
print("✅ [System READY] جميع الوحدات تم تهيئتها بنجاح.")
|
| 155 |
-
print("------------------------------------------------------")
|
| 156 |
-
|
| 157 |
-
yield
|
| 158 |
-
|
| 159 |
except Exception as e:
|
| 160 |
-
|
| 161 |
traceback.print_exc()
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
# ==============================================================================
|
| 171 |
-
# 🧠
|
| 172 |
# ==============================================================================
|
| 173 |
async def _analyze_symbol_task(symbol: str) -> Dict[str, Any]:
|
| 174 |
global data_manager, ml_processor
|
|
@@ -176,153 +179,134 @@ async def _analyze_symbol_task(symbol: str) -> Dict[str, Any]:
|
|
| 176 |
required_tfs = ["5m", "15m", "1h", "4h", "1d"]
|
| 177 |
data_tasks = [data_manager.get_latest_ohlcv(symbol, tf, limit=250) for tf in required_tfs]
|
| 178 |
all_data = await asyncio.gather(*data_tasks)
|
| 179 |
-
|
| 180 |
ohlcv_data = {}
|
| 181 |
for tf, data in zip(required_tfs, all_data):
|
| 182 |
if data and len(data) > 0: ohlcv_data[tf] = data
|
| 183 |
-
|
| 184 |
-
if '5m' not in ohlcv_data or '
|
| 185 |
-
|
| 186 |
-
|
| 187 |
current_price = await data_manager.get_latest_price_async(symbol)
|
| 188 |
raw_data = {'symbol': symbol, 'ohlcv': ohlcv_data, 'current_price': current_price}
|
| 189 |
return await ml_processor.process_and_score_symbol_enhanced(raw_data)
|
| 190 |
-
except
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
# ==============================================================================
|
| 194 |
-
#
|
| 195 |
# ==============================================================================
|
| 196 |
async def run_unified_cycle():
|
| 197 |
-
"""
|
| 198 |
-
دورة التحليل الكاملة: L1 -> L2 -> L3 -> L4.
|
| 199 |
-
- تتحقق أولاً من وجود صفقات مفتوحة.
|
| 200 |
-
- إذا وجدت، تقوم بفحص صحي (Health Check) وتتوقف.
|
| 201 |
-
- إذا لم تجد، تبدأ البحث الكامل (Full Scan).
|
| 202 |
-
"""
|
| 203 |
-
|
| 204 |
-
# (إعداد التقاط السجلات)
|
| 205 |
log_buffer = StringIO()
|
| 206 |
-
|
| 207 |
def log_and_print(message):
|
| 208 |
-
"""دالة مساعدة للطباعة في السجل الفعلي وفي الواجهة"""
|
| 209 |
print(message)
|
| 210 |
log_buffer.write(message + '\n')
|
| 211 |
|
| 212 |
-
if sys_state.cycle_running:
|
| 213 |
-
log_and_print("⚠️ [Cycle] الدورة الحالية لا تزال قيد التشغيل. تم تجاهل الطلب.")
|
| 214 |
-
return
|
| 215 |
-
|
| 216 |
if not sys_state.ready:
|
| 217 |
-
log_and_print("⚠️
|
| 218 |
return
|
| 219 |
|
| 220 |
-
sys_state.
|
|
|
|
|
|
|
|
|
|
| 221 |
log_and_print(f"\n🌀 [Cycle START] {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 222 |
|
| 223 |
try:
|
| 224 |
-
#
|
| 225 |
-
# 1.
|
| 226 |
-
#
|
| 227 |
if trade_manager.open_positions:
|
| 228 |
symbol = list(trade_manager.open_positions.keys())[0]
|
| 229 |
-
log_and_print(f"⚠️ [
|
| 230 |
-
log_and_print(f" ->
|
| 231 |
-
log_and_print(f" -> 🩺 جاري تشغيل 'إعادة التحليل' (Health Check) للصفقة الحالية...")
|
| 232 |
|
| 233 |
-
# --- إعادة تحليل الصفقة المفتوحة ---
|
| 234 |
analysis = await _analyze_symbol_task(symbol)
|
| 235 |
if analysis:
|
| 236 |
score = analysis.get('enhanced_final_score', 0.0)
|
| 237 |
comps = analysis.get('components', {})
|
|
|
|
|
|
|
| 238 |
|
| 239 |
-
log_and_print(f"\n📊 [Health Report] {symbol}")
|
| 240 |
-
log_and_print(f" - Current L1 Score: {score:.2f}")
|
| 241 |
-
log_and_print(f" - Titan: {comps.get('titan_score', 0):.2f} | Patterns: {comps.get('patterns_score', 0):.2f} | MC: {comps.get('mc_score', 0):.2f}")
|
| 242 |
-
|
| 243 |
-
# فحص العقل
|
| 244 |
-
log_and_print(" -> 🧠 استشارة Oracle للصفقة المفتوحة...")
|
| 245 |
oracle_res = await oracle_engine.predict(analysis)
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
reason = oracle_res.get('analysis_summary') or oracle_res.get('reason')
|
| 249 |
-
log_and_print(f" -> Oracle Says: {action} (Conf: {conf:.2f})")
|
| 250 |
-
log_and_print(f" Reason: {reason}")
|
| 251 |
|
| 252 |
-
# فحص الحارس
|
| 253 |
-
log_and_print(" -> 🛡️ استشارة Guard V2 للخروج...")
|
| 254 |
if '5m' in analysis['ohlcv']:
|
| 255 |
guard_res = await guard_engine.check_exit_signal_async(analysis['ohlcv']['5m'])
|
| 256 |
-
log_and_print(f" -> Guard
|
| 257 |
-
|
| 258 |
else:
|
| 259 |
-
log_and_print(f"⚠️ فشل تحليل
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
sys_state.
|
| 263 |
return
|
| 264 |
|
| 265 |
-
#
|
| 266 |
-
# 2.
|
| 267 |
-
#
|
|
|
|
| 268 |
|
| 269 |
-
# ---
|
| 270 |
-
log_and_print(" [
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
log_and_print(f" -> 🧠 بدء تحليل L1 المعمق لـ {len(candidates_to_analyze)} عملة...")
|
| 278 |
analysis_start_time = time.time()
|
| 279 |
|
| 280 |
-
tasks = [_analyze_symbol_task(
|
| 281 |
results = await asyncio.gather(*tasks)
|
|
|
|
| 282 |
|
| 283 |
-
|
| 284 |
top_10_l1 = sorted(valid_l1_results, key=lambda x: x.get('enhanced_final_score', 0.0), reverse=True)[:10]
|
| 285 |
|
| 286 |
log_and_print(f" -> 🧠 انتهى تحليل L1 في {time.time() - analysis_start_time:.2f} ثانية.")
|
| 287 |
log_and_print(f" - ✅ نجح: {len(valid_l1_results)} إشارة مرشحة.")
|
| 288 |
|
| 289 |
-
if top_10_l1:
|
| 290 |
-
log_and_print(
|
| 291 |
-
for i, res in enumerate(top_10_l1):
|
| 292 |
-
components = res.get('components', {})
|
| 293 |
-
titan_s = components.get('titan_score', 0.0)
|
| 294 |
-
pattern_s = components.get('patterns_score', 0.0)
|
| 295 |
-
mc_s = components.get('mc_score', 0.0)
|
| 296 |
-
log_and_print(f" {i+1}. {res.get('symbol'):<10}: {res.get('enhanced_final_score', 0.0):.4f} [T: {titan_s:.2f} | P: {pattern_s:.2f} | M: {mc_s:.2f}]")
|
| 297 |
-
else:
|
| 298 |
-
log_and_print(" -> ⚠️ لم يتم العثور على أي عملات صالحة.")
|
| 299 |
-
sys_state.set_cycle_end(logs=log_buffer.getvalue()); return
|
| 300 |
|
| 301 |
-
# ---
|
| 302 |
-
# [ تم استعادة الكو�� الكامل هنا ]
|
| 303 |
log_and_print(f"\n [Cycle 2/5] 🚀 بدء تعزيز النقاط (L2 Boosting) لأفضل 10 عملات...")
|
| 304 |
l2_enriched_candidates = []
|
| 305 |
|
| 306 |
for candidate in top_10_l1:
|
| 307 |
symbol = candidate['symbol']
|
| 308 |
l1_score = candidate['enhanced_final_score']
|
|
|
|
| 309 |
whale_score = 0.0; whale_raw_str = "No Data"
|
| 310 |
news_score = 0.0; news_raw_str = "No Data"
|
| 311 |
adv_mc_score = 0.0; mc_raw_str = "No Data"
|
| 312 |
-
|
| 313 |
# (أ. بيانات الحيتان)
|
|
|
|
| 314 |
try:
|
| 315 |
whale_data = await whale_monitor.get_symbol_whale_activity(symbol)
|
| 316 |
net_flow = whale_data.get('accumulation_analysis_24h', {}).get('net_flow_usd', 0.0)
|
| 317 |
whale_raw_str = f"${net_flow:,.0f}"
|
| 318 |
if net_flow <= -500000: whale_score = 0.10
|
| 319 |
elif net_flow < 0: whale_score = 0.05
|
| 320 |
-
except Exception as e:
|
| 321 |
-
|
|
|
|
| 322 |
|
| 323 |
# (ب. الأخبار)
|
|
|
|
| 324 |
try:
|
| 325 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
if news_item:
|
| 327 |
news_text = news_item.get('summary', 'No news')
|
| 328 |
sentiment = senti_analyzer.polarity_scores(news_text)
|
|
@@ -330,28 +314,39 @@ async def run_unified_cycle():
|
|
| 330 |
news_raw_str = f"{compound:.2f}"
|
| 331 |
if compound >= 0.5: news_score = 0.05
|
| 332 |
elif compound >= 0.1: news_score = 0.02
|
| 333 |
-
except Exception as e:
|
| 334 |
-
|
|
|
|
| 335 |
|
| 336 |
# (ج. مونت كارلو المتقدمة)
|
| 337 |
try:
|
| 338 |
full_ohlcv_1h = await data_manager.get_latest_ohlcv(symbol, '1h', limit=100)
|
| 339 |
-
if full_ohlcv_1h
|
|
|
|
|
|
|
| 340 |
mc_data = {'1h': full_ohlcv_1h}
|
| 341 |
mc_res = await ml_processor.mc_analyzer.generate_1h_distribution_advanced(mc_data)
|
| 342 |
if mc_res and not mc_res.get('error', False):
|
| 343 |
prob_gain = mc_res.get('probability_of_gain', 0.5)
|
| 344 |
mc_raw_str = f"{prob_gain:.2f}"
|
| 345 |
-
if prob_gain > 0.5:
|
| 346 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
|
|
|
|
| 348 |
final_score = l1_score + whale_score + news_score + adv_mc_score
|
| 349 |
candidate['final_total_score'] = final_score
|
| 350 |
candidate['l2_scores'] = {'whale': whale_score, 'news': news_score, 'adv_mc': adv_mc_score}
|
| 351 |
candidate['l2_raw_values'] = {'whale': whale_raw_str, 'news': news_raw_str, 'adv_mc': mc_raw_str}
|
| 352 |
l2_enriched_candidates.append(candidate)
|
| 353 |
|
| 354 |
-
# --- 3. إعادة الترتيب وطباعة الجدول ---
|
| 355 |
log_and_print(f" [Cycle 3/5] 📊 إعادة ترتيب المرشحين حسب الدرجة النهائية (L1 + L2)...")
|
| 356 |
sorted_finalists = sorted(l2_enriched_candidates, key=lambda x: x['final_total_score'], reverse=True)
|
| 357 |
|
|
@@ -359,12 +354,18 @@ async def run_unified_cycle():
|
|
| 359 |
header = f"{'SYMBOL':<10} | {'L1 SCORE':<8} | {'WHALE (Flow)':<22} | {'NEWS (Sent)':<18} | {'ADV MC (Prob)':<18} | {'FINAL':<8}"
|
| 360 |
log_and_print(header)
|
| 361 |
log_and_print("-" * 135)
|
|
|
|
| 362 |
for cand in sorted_finalists:
|
| 363 |
-
sym = cand['symbol']
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
whale_cell = f"{l2['whale']:.2f} ({l2_raw['whale']})"
|
| 365 |
news_cell = f"{l2['news']:.2f} ({l2_raw['news']})"
|
| 366 |
mc_cell = f"{l2['adv_mc']:.2f} ({l2_raw['adv_mc']})"
|
| 367 |
log_and_print(f"{sym:<10} | {l1:.4f} | {whale_cell:<22} | {news_cell:<18} | {mc_cell:<18} | {final:.4f}")
|
|
|
|
| 368 |
log_and_print("="*135 + "\n")
|
| 369 |
|
| 370 |
# --- 4. اختيار أفضل 5 للنموذج الضخم (Oracle) ---
|
|
@@ -379,13 +380,16 @@ async def run_unified_cycle():
|
|
| 379 |
if signal['final_total_score'] < 0.60:
|
| 380 |
log_and_print(f" -> 🛑 {symbol} تم استبعاده (الدرجة النهائية {signal['final_total_score']:.2f} < 0.60)")
|
| 381 |
continue
|
|
|
|
| 382 |
log_and_print(f" -> 🧠 [Oracle Scan] جاري فحص {symbol}...")
|
|
|
|
| 383 |
try:
|
| 384 |
oracle_decision = await oracle_engine.predict(signal)
|
| 385 |
-
action = oracle_decision.get('action')
|
|
|
|
| 386 |
reason = oracle_decision.get('analysis_summary') or oracle_decision.get('reason', 'No summary provided')
|
| 387 |
-
|
| 388 |
-
#
|
| 389 |
if "SHORT" in str(reason).upper() or "SHORT" in str(oracle_decision.get('strategy')).upper():
|
| 390 |
log_and_print(f" 🛑 [Oracle SKIP] {symbol} تم تجاهلها (إشارة بيع SHORT).")
|
| 391 |
continue
|
|
@@ -398,7 +402,8 @@ async def run_unified_cycle():
|
|
| 398 |
oracle_approved_signals.append(signal)
|
| 399 |
else:
|
| 400 |
log_and_print(f" 🛑 [Oracle REJECTED] {symbol} (Conf: {confidence:.2f})")
|
| 401 |
-
log_and_print(f" 📝 Reason: {reason[:200]}...")
|
|
|
|
| 402 |
except Exception as e:
|
| 403 |
log_and_print(f" ⚠️ [Oracle Error] فشل تحليل Oracle لـ {symbol}: {e}")
|
| 404 |
traceback.print_exc(file=log_buffer)
|
|
@@ -406,184 +411,152 @@ async def run_unified_cycle():
|
|
| 406 |
|
| 407 |
log_and_print(f" -> 🧠 انتهى فحص Oracle في {time.time() - oracle_start_time:.2f} ثانية. (تمت الموافقة على {len(oracle_approved_signals)} إشارة)")
|
| 408 |
|
| 409 |
-
#
|
| 410 |
if oracle_approved_signals:
|
| 411 |
log_and_print(f" -> 🎯 [L4 Sniper Batch] إرسال {len(oracle_approved_signals)} إشارة للقناص للفرز النهائي واختيار الأفضل...")
|
| 412 |
|
| 413 |
-
# التقاط سجلات TradeManager
|
| 414 |
tm_log_buffer = StringIO()
|
| 415 |
with redirect_stdout(tm_log_buffer), redirect_stderr(tm_log_buffer):
|
| 416 |
await trade_manager.select_and_execute_best_signal(oracle_approved_signals)
|
| 417 |
|
| 418 |
tm_logs = tm_log_buffer.getvalue()
|
| 419 |
-
print(tm_logs)
|
| 420 |
-
log_buffer.write(tm_logs + '\n')
|
| 421 |
else:
|
| 422 |
log_and_print(" -> 🎯 [L4 Sniper Batch] لا توجد إشارات معتمدة من العقل لإرسالها للقناص.")
|
| 423 |
-
|
| 424 |
-
# --- 5. الصيانة والتعلم ---
|
| 425 |
-
log_and_print(f" [Cycle 5/5] 🧹 تنظيف الذاكرة...")
|
| 426 |
-
gc.collect()
|
| 427 |
-
log_and_print(f"🌀 [Cycle END] {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 428 |
-
sys_state.set_cycle_end(logs=log_buffer.getvalue())
|
| 429 |
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
sys_state.set_cycle_end(error=e, logs=log_buffer.getvalue())
|
| 434 |
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
if price is None or price == 0: return "0.00"
|
| 441 |
-
if price < 1.0: return f"{price:.8f}" # للعملات مثل SHIB
|
| 442 |
-
if price < 100: return f"{price:.4f}"
|
| 443 |
-
return f"{price:.2f}"
|
| 444 |
|
| 445 |
# ==============================================================================
|
| 446 |
-
# 📊 واجهة Gradio
|
| 447 |
# ==============================================================================
|
| 448 |
-
async def
|
|
|
|
|
|
|
| 449 |
if not sys_state.ready:
|
| 450 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 451 |
|
| 452 |
-
# 1. الحالة العامة
|
| 453 |
-
log_text = sys_state.last_cycle_logs
|
| 454 |
n_trades = len(trade_manager.open_positions)
|
| 455 |
-
status_md = f"""
|
| 456 |
-
**الحالة:** {'<span style="color:green;">جاهز</span>' if not sys_state.cycle_running else '<span style="color:orange;">يحلل...</span>'} |
|
| 457 |
-
**الصفقات:** {n_trades} |
|
| 458 |
-
**المراقبة:** {len(trade_manager.watchlist)}
|
| 459 |
-
"""
|
| 460 |
df_watch = pd.DataFrame(list(trade_manager.watchlist.keys()), columns=["Watchlist"])
|
| 461 |
|
| 462 |
-
# 2. لا توجد صفقات
|
| 463 |
if n_trades == 0:
|
| 464 |
-
return log_text,
|
| 465 |
|
| 466 |
-
#
|
| 467 |
try:
|
| 468 |
symbol = list(trade_manager.open_positions.keys())[0]
|
| 469 |
trade = trade_manager.open_positions[symbol]
|
| 470 |
-
|
| 471 |
-
curr_price = await data_manager.get_latest_price_async(symbol)
|
| 472 |
entry = trade['entry_price']
|
| 473 |
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
pnl = 0.0
|
| 478 |
-
|
| 479 |
-
color = "green" if pnl >= 0 else "red"
|
| 480 |
-
pnl_html = f"<h2 style='color:{color}; text-align:center;'>{pnl:.2f}%</h2>"
|
| 481 |
|
| 482 |
-
# [ إصلاح التنسيق ] استخدام fmt_price
|
| 483 |
details = f"""
|
| 484 |
**Entry:** {fmt_price(entry)}
|
| 485 |
-
**Current:** {fmt_price(
|
| 486 |
**TP:** {fmt_price(trade['tp_price'])}
|
| 487 |
**SL:** {fmt_price(trade['sl_price'])}
|
| 488 |
"""
|
| 489 |
-
|
| 490 |
-
symbol_md = f"### {symbol}"
|
| 491 |
|
| 492 |
-
#
|
| 493 |
-
fig = plt.figure(figsize=(10,
|
| 494 |
try:
|
| 495 |
ohlcv = await data_manager.get_latest_ohlcv(symbol, '5m', 100)
|
| 496 |
if ohlcv:
|
| 497 |
df = pd.DataFrame(ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
|
| 498 |
df['dt'] = pd.to_datetime(df['ts'], unit='ms')
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
|
|
|
|
|
|
| 508 |
plt.tight_layout()
|
| 509 |
else:
|
| 510 |
-
plt.text(0.5, 0.5, "No Data",
|
|
|
|
| 511 |
except:
|
| 512 |
plt.close()
|
| 513 |
fig = None
|
| 514 |
|
| 515 |
-
return log_text,
|
| 516 |
-
|
| 517 |
except Exception as e:
|
| 518 |
-
return log_text,
|
| 519 |
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
#
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
|
|
|
| 526 |
|
| 527 |
with gr.Row():
|
| 528 |
with gr.Column(scale=3):
|
| 529 |
-
chart = gr.Plot(label="Chart")
|
| 530 |
with gr.Column(scale=1):
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
|
| 535 |
with gr.Row():
|
| 536 |
-
btn = gr.Button("🚀
|
| 537 |
-
stat = gr.Markdown("**
|
| 538 |
|
| 539 |
with gr.Row():
|
| 540 |
-
logs = gr.Textbox(label="Logs", lines=
|
| 541 |
watch = gr.DataFrame(label="Watchlist")
|
| 542 |
|
| 543 |
# Events
|
| 544 |
-
async def
|
| 545 |
-
if sys_state.cycle_running: return
|
| 546 |
await run_unified_cycle()
|
| 547 |
-
return sys_state.
|
| 548 |
|
| 549 |
-
btn.click(
|
| 550 |
|
| 551 |
-
#
|
| 552 |
-
timer = gr.Timer(
|
| 553 |
-
timer.tick(
|
| 554 |
-
check_live_pnl_and_status,
|
| 555 |
-
outputs=[logs, stat, sym_lbl, pnl_lbl, det_lbl, chart, watch]
|
| 556 |
-
)
|
| 557 |
|
| 558 |
-
#
|
| 559 |
-
demo.load(
|
| 560 |
-
check_live_pnl_and_status,
|
| 561 |
-
outputs=[logs, stat, sym_lbl, pnl_lbl, det_lbl, chart, watch]
|
| 562 |
-
)
|
| 563 |
|
| 564 |
return demo
|
| 565 |
|
| 566 |
# ==============================================================================
|
| 567 |
-
# 🔥
|
| 568 |
# ==============================================================================
|
| 569 |
app = FastAPI()
|
|
|
|
|
|
|
| 570 |
|
| 571 |
-
# نقاط النهاية للخادم الخارجي (Cron Jobs)
|
| 572 |
@app.get("/run-cycle")
|
| 573 |
-
async def
|
| 574 |
-
if sys_state.cycle_running: return {"status": "Busy"}
|
| 575 |
bg.add_task(run_unified_cycle)
|
| 576 |
-
return {"status": "
|
| 577 |
-
|
| 578 |
-
@app.get("/status")
|
| 579 |
-
async def api_status():
|
| 580 |
-
return {"trades": len(trade_manager.open_positions) if trade_manager else 0}
|
| 581 |
-
|
| 582 |
-
# دمج واجهة Gradio
|
| 583 |
-
ui = create_ui()
|
| 584 |
-
app = gr.mount_gradio_app(app, ui, path="/")
|
| 585 |
|
| 586 |
if __name__ == "__main__":
|
| 587 |
import uvicorn
|
| 588 |
-
# --no-access-log لإخفاء إزعاج الطلبات
|
| 589 |
uvicorn.run(app, host="0.0.0.0", port=7860, access_log=False)
|
|
|
|
| 1 |
+
# app.py (V17.9 - The Ultimate: Non-Blocking UI + FULL 100% Logic Restored)
|
| 2 |
import os
|
| 3 |
import sys
|
| 4 |
import traceback
|
|
|
|
| 12 |
from fastapi import FastAPI, HTTPException, BackgroundTasks
|
| 13 |
from typing import List, Dict, Any
|
| 14 |
|
| 15 |
+
# [ واجهة Gradio ومكتبات الرسم ]
|
| 16 |
import gradio as gr
|
| 17 |
import pandas as pd
|
| 18 |
import matplotlib.pyplot as plt
|
| 19 |
import matplotlib.dates as mdates
|
| 20 |
+
plt.switch_backend('Agg')
|
| 21 |
|
| 22 |
# ==============================================================================
|
| 23 |
+
# 📥 استيراد الوحدات الأساسية
|
| 24 |
# ==============================================================================
|
| 25 |
try:
|
| 26 |
from r2 import R2Service
|
|
|
|
| 34 |
from ml_engine.guard_engine import GuardEngine
|
| 35 |
from ml_engine.sniper_engine import SniperEngine
|
| 36 |
except ImportError as e:
|
| 37 |
+
print(f"❌ Critical Import Error: {e}")
|
| 38 |
|
| 39 |
# ==============================================================================
|
| 40 |
+
# 🌐 المتغيرات العامة
|
| 41 |
# ==============================================================================
|
| 42 |
+
r2 = None
|
| 43 |
+
data_manager = None
|
| 44 |
+
ml_processor = None
|
| 45 |
+
trade_manager = None
|
| 46 |
+
whale_monitor = None
|
| 47 |
+
news_fetcher = None
|
| 48 |
+
senti_analyzer = None
|
| 49 |
+
sys_state = None
|
| 50 |
+
guard_engine = None
|
| 51 |
+
sniper_engine = None
|
| 52 |
+
oracle_engine = None
|
| 53 |
|
| 54 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 55 |
SHARED_GUARD_MODELS_DIR = os.path.join(BASE_DIR, "ml_models", "guard_v2")
|
|
|
|
| 62 |
def __init__(self):
|
| 63 |
self.ready = False
|
| 64 |
self.cycle_running = False
|
| 65 |
+
self.startup_error = None
|
| 66 |
+
self.logs = "⏳ بدء تشغيل النظام... (الواجهة تعمل، التحميل في الخلفية)\n"
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
def log(self, msg):
|
| 69 |
+
print(msg)
|
| 70 |
+
timestamp = datetime.now().strftime('%H:%M:%S')
|
| 71 |
+
self.logs += f"[{timestamp}] {msg}\n"
|
| 72 |
+
|
| 73 |
+
def set_ready(self):
|
| 74 |
self.ready = True
|
| 75 |
+
self.log("✅ النظام جاهز تماماً للعمل.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
def set_error(self, err):
|
| 78 |
+
self.ready = False
|
| 79 |
+
self.startup_error = str(err)
|
| 80 |
+
self.log(f"❌ فشل التشغيل: {err}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
sys_state = SystemState()
|
| 83 |
|
| 84 |
# ==============================================================================
|
| 85 |
+
# 🏗️ عملية التحميل في الخلفية (Non-Blocking Startup)
|
| 86 |
# ==============================================================================
|
| 87 |
+
async def background_initialization():
|
| 88 |
+
"""
|
| 89 |
+
تحميل النظام بالكامل في الخلفية لضمان ظهور الواجهة فوراً.
|
| 90 |
+
"""
|
| 91 |
global r2, data_manager, ml_processor, trade_manager, oracle_engine
|
| 92 |
global whale_monitor, news_fetcher, senti_analyzer, guard_engine, sniper_engine, sys_state
|
| 93 |
+
|
|
|
|
|
|
|
|
|
|
| 94 |
try:
|
| 95 |
+
await asyncio.sleep(1) # مهلة قصيرة جداً
|
| 96 |
+
sys_state.log("🚀 بدء تحميل الوحدات (Background Task)...")
|
| 97 |
+
|
| 98 |
+
# 1. R2
|
| 99 |
+
sys_state.log(" [1/8] الاتصال بـ Cloudflare R2...")
|
| 100 |
r2 = R2Service()
|
| 101 |
|
| 102 |
+
# 2. Data Manager
|
| 103 |
+
sys_state.log(" [2/8] تهيئة DataManager...")
|
| 104 |
data_manager = DataManager(contracts_db={}, whale_monitor=None, r2_service=r2)
|
| 105 |
+
await data_manager.initialize()
|
| 106 |
+
try:
|
| 107 |
+
await data_manager.load_contracts_from_r2()
|
| 108 |
+
sys_state.log(" -> تم تحميل قاعدة عقود العملات.")
|
| 109 |
+
except Exception as e:
|
| 110 |
+
sys_state.log(f" ⚠️ تحذير: فشل تحميل العقود ({e})")
|
| 111 |
|
| 112 |
+
# 3. Services
|
| 113 |
+
sys_state.log(" [3/8] تهيئة خدمات الحيتان والأخبار...")
|
| 114 |
whale_monitor = EnhancedWhaleMonitor(contracts_db=data_manager.get_contracts_db(), r2_service=r2)
|
| 115 |
news_fetcher = NewsFetcher()
|
| 116 |
senti_analyzer = SentimentIntensityAnalyzer()
|
| 117 |
data_manager.whale_monitor = whale_monitor
|
| 118 |
|
| 119 |
+
# 4. Oracle
|
| 120 |
+
sys_state.log(f" [4/8] تحميل نماذج Oracle L3 من {UNIFIED_MODELS_DIR}...")
|
| 121 |
oracle_engine = OracleEngine(model_dir=UNIFIED_MODELS_DIR)
|
| 122 |
await oracle_engine.initialize()
|
| 123 |
|
| 124 |
+
# 5. ML Processor
|
| 125 |
+
sys_state.log(" [5/8] تهيئة Titan Engine L1...")
|
|
|
|
| 126 |
ml_processor = MLProcessor(market_context=None, data_manager=data_manager, learning_hub=None)
|
| 127 |
await ml_processor.initialize()
|
| 128 |
|
| 129 |
+
# 6. Guard
|
| 130 |
+
sys_state.log(" [6/8] تهيئة Guard Engine L2...")
|
|
|
|
| 131 |
guard_engine = GuardEngine(models_dir=SHARED_GUARD_MODELS_DIR)
|
| 132 |
await guard_engine.initialize()
|
| 133 |
|
| 134 |
+
# 7. Sniper
|
| 135 |
+
sys_state.log(" [7/8] تهيئة Sniper Engine L2...")
|
| 136 |
sniper_engine = SniperEngine(models_dir=SHARED_GUARD_MODELS_DIR)
|
| 137 |
await sniper_engine.initialize()
|
| 138 |
+
sniper_engine.set_entry_threshold(0.35)
|
| 139 |
|
| 140 |
+
# 8. Trade Manager
|
| 141 |
+
sys_state.log(" [8/8] تهيئة Trade Manager واستعادة الصفقات...")
|
| 142 |
trade_manager = TradeManager(
|
| 143 |
r2_service=r2,
|
| 144 |
data_manager=data_manager,
|
|
|
|
| 147 |
guard_engine=guard_engine,
|
| 148 |
sniper_engine=sniper_engine
|
| 149 |
)
|
|
|
|
| 150 |
await trade_manager.initialize_sentry_exchanges()
|
| 151 |
await trade_manager.start_sentry_loops()
|
| 152 |
|
| 153 |
sys_state.set_ready()
|
| 154 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
except Exception as e:
|
| 156 |
+
sys_state.set_error(e)
|
| 157 |
traceback.print_exc()
|
| 158 |
|
| 159 |
+
# ==============================================================================
|
| 160 |
+
# 🚀 دورة الحياة (FastAPI Lifespan)
|
| 161 |
+
# ==============================================================================
|
| 162 |
+
@asynccontextmanager
|
| 163 |
+
async def lifespan(app: FastAPI):
|
| 164 |
+
asyncio.create_task(background_initialization())
|
| 165 |
+
print("✅ [FastAPI] Server Started (Initialization running in background).")
|
| 166 |
+
yield
|
| 167 |
+
print("\n🛑 [FastAPI] Shutting down...")
|
| 168 |
+
sys_state.ready = False
|
| 169 |
+
if trade_manager: await trade_manager.stop_sentry_loops()
|
| 170 |
+
if data_manager: await data_manager.close()
|
| 171 |
+
print("✅ [FastAPI] Shutdown complete.")
|
| 172 |
|
| 173 |
# ==============================================================================
|
| 174 |
+
# 🧠 وظائف التحليل
|
| 175 |
# ==============================================================================
|
| 176 |
async def _analyze_symbol_task(symbol: str) -> Dict[str, Any]:
|
| 177 |
global data_manager, ml_processor
|
|
|
|
| 179 |
required_tfs = ["5m", "15m", "1h", "4h", "1d"]
|
| 180 |
data_tasks = [data_manager.get_latest_ohlcv(symbol, tf, limit=250) for tf in required_tfs]
|
| 181 |
all_data = await asyncio.gather(*data_tasks)
|
|
|
|
| 182 |
ohlcv_data = {}
|
| 183 |
for tf, data in zip(required_tfs, all_data):
|
| 184 |
if data and len(data) > 0: ohlcv_data[tf] = data
|
| 185 |
+
|
| 186 |
+
if '5m' not in ohlcv_data or '1h' not in ohlcv_data: 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}
|
| 190 |
return await ml_processor.process_and_score_symbol_enhanced(raw_data)
|
| 191 |
+
except: return None
|
| 192 |
+
|
| 193 |
+
def fmt_price(price):
|
| 194 |
+
if price is None or price == 0: return "0.00"
|
| 195 |
+
if price < 1.0: return f"{price:.8f}"
|
| 196 |
+
if price < 100: return f"{price:.4f}"
|
| 197 |
+
return f"{price:.2f}"
|
| 198 |
|
| 199 |
# ==============================================================================
|
| 200 |
+
# 🧬 الدورة الموحدة (Full Logic Restored)
|
| 201 |
# ==============================================================================
|
| 202 |
async def run_unified_cycle():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
log_buffer = StringIO()
|
|
|
|
| 204 |
def log_and_print(message):
|
|
|
|
| 205 |
print(message)
|
| 206 |
log_buffer.write(message + '\n')
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
if not sys_state.ready:
|
| 209 |
+
log_and_print(f"⚠️ النظام غير جاهز بعد. انتظر انتهاء التحميل.")
|
| 210 |
return
|
| 211 |
|
| 212 |
+
if sys_state.cycle_running:
|
| 213 |
+
log_and_print("⚠️ الدورة تعمل حالياً."); return
|
| 214 |
+
|
| 215 |
+
sys_state.cycle_running = True
|
| 216 |
log_and_print(f"\n🌀 [Cycle START] {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 217 |
|
| 218 |
try:
|
| 219 |
+
# ---------------------------------------------------------
|
| 220 |
+
# 1. فحص الصفقات المفتوحة (R2 Priority)
|
| 221 |
+
# ---------------------------------------------------------
|
| 222 |
if trade_manager.open_positions:
|
| 223 |
symbol = list(trade_manager.open_positions.keys())[0]
|
| 224 |
+
log_and_print(f"⚠️ [Limit] توجد صفقة نشطة: {symbol}. تم إلغاء البحث.")
|
| 225 |
+
log_and_print(f" -> 🩺 تشغيل الفحص الصحي (Re-Analysis)...")
|
|
|
|
| 226 |
|
|
|
|
| 227 |
analysis = await _analyze_symbol_task(symbol)
|
| 228 |
if analysis:
|
| 229 |
score = analysis.get('enhanced_final_score', 0.0)
|
| 230 |
comps = analysis.get('components', {})
|
| 231 |
+
log_and_print(f"\n📊 [Report] {symbol} | L1 Score: {score:.2f}")
|
| 232 |
+
log_and_print(f" - Titan: {comps.get('titan_score', 0):.2f} | Patterns: {comps.get('patterns_score', 0):.2f}")
|
| 233 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
oracle_res = await oracle_engine.predict(analysis)
|
| 235 |
+
act = oracle_res.get('action'); conf = oracle_res.get('confidence', 0)
|
| 236 |
+
log_and_print(f" -> Oracle: {act} (Conf: {conf:.2f})")
|
|
|
|
|
|
|
|
|
|
| 237 |
|
|
|
|
|
|
|
| 238 |
if '5m' in analysis['ohlcv']:
|
| 239 |
guard_res = await guard_engine.check_exit_signal_async(analysis['ohlcv']['5m'])
|
| 240 |
+
log_and_print(f" -> Guard V2: {guard_res['action']} (Conf: {guard_res['confidence']:.2f})")
|
|
|
|
| 241 |
else:
|
| 242 |
+
log_and_print(f"⚠️ فشل تحليل {symbol} (بيانات ناقصة).")
|
| 243 |
+
|
| 244 |
+
sys_state.cycle_running = False
|
| 245 |
+
sys_state.logs = log_buffer.getvalue()
|
| 246 |
return
|
| 247 |
|
| 248 |
+
# ---------------------------------------------------------
|
| 249 |
+
# 2. البحث الجديد (Full Logic Restored)
|
| 250 |
+
# ---------------------------------------------------------
|
| 251 |
+
log_and_print("✅ البحث عن فرص جديدة...")
|
| 252 |
|
| 253 |
+
# --- L1 Screening ---
|
| 254 |
+
log_and_print(" [1/5] L1 Rapid Screening...")
|
| 255 |
+
candidates = await data_manager.layer1_rapid_screening()
|
| 256 |
+
if not candidates:
|
| 257 |
+
log_and_print("⚠️ لا توجد عملات."); sys_state.cycle_running = False; sys_state.logs = log_buffer.getvalue(); return
|
| 258 |
+
|
| 259 |
+
# --- L1 Deep Analysis ---
|
| 260 |
+
log_and_print(f" -> تحليل معمق لـ {len(candidates)} عملة...")
|
|
|
|
| 261 |
analysis_start_time = time.time()
|
| 262 |
|
| 263 |
+
tasks = [_analyze_symbol_task(c['symbol']) for c in candidates if c.get('symbol')]
|
| 264 |
results = await asyncio.gather(*tasks)
|
| 265 |
+
valid_l1_results = [r for r in results if r]
|
| 266 |
|
| 267 |
+
# ترتيب حسب L1
|
| 268 |
top_10_l1 = sorted(valid_l1_results, key=lambda x: x.get('enhanced_final_score', 0.0), reverse=True)[:10]
|
| 269 |
|
| 270 |
log_and_print(f" -> 🧠 انتهى تحليل L1 في {time.time() - analysis_start_time:.2f} ثانية.")
|
| 271 |
log_and_print(f" - ✅ نجح: {len(valid_l1_results)} إشارة مرشحة.")
|
| 272 |
|
| 273 |
+
if not top_10_l1:
|
| 274 |
+
log_and_print("⚠️ لا توجد نتائج L1 صالحة."); sys_state.cycle_running = False; sys_state.logs = log_buffer.getvalue(); return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
|
| 276 |
+
# --- L2 Boosting (Full Detailed Logic) ---
|
|
|
|
| 277 |
log_and_print(f"\n [Cycle 2/5] 🚀 بدء تعزيز النقاط (L2 Boosting) لأفضل 10 عملات...")
|
| 278 |
l2_enriched_candidates = []
|
| 279 |
|
| 280 |
for candidate in top_10_l1:
|
| 281 |
symbol = candidate['symbol']
|
| 282 |
l1_score = candidate['enhanced_final_score']
|
| 283 |
+
|
| 284 |
whale_score = 0.0; whale_raw_str = "No Data"
|
| 285 |
news_score = 0.0; news_raw_str = "No Data"
|
| 286 |
adv_mc_score = 0.0; mc_raw_str = "No Data"
|
| 287 |
+
|
| 288 |
# (أ. بيانات الحيتان)
|
| 289 |
+
whale_data = {}
|
| 290 |
try:
|
| 291 |
whale_data = await whale_monitor.get_symbol_whale_activity(symbol)
|
| 292 |
net_flow = whale_data.get('accumulation_analysis_24h', {}).get('net_flow_usd', 0.0)
|
| 293 |
whale_raw_str = f"${net_flow:,.0f}"
|
| 294 |
if net_flow <= -500000: whale_score = 0.10
|
| 295 |
elif net_flow < 0: whale_score = 0.05
|
| 296 |
+
except Exception as e:
|
| 297 |
+
pass # (تخفيف الضوضاء، الأخطاء مسجلة في مكان آخر)
|
| 298 |
+
candidate['whale_data'] = whale_data
|
| 299 |
|
| 300 |
# (ب. الأخبار)
|
| 301 |
+
news_text = "No news available"
|
| 302 |
try:
|
| 303 |
+
if hasattr(news_fetcher, 'get_news'):
|
| 304 |
+
news_item = await news_fetcher.get_news(symbol)
|
| 305 |
+
elif hasattr(news_fetcher, 'fetch_news'):
|
| 306 |
+
news_item = await news_fetcher.fetch_news(symbol)
|
| 307 |
+
else:
|
| 308 |
+
news_item = {'summary': 'News fetcher method not found'}
|
| 309 |
+
|
| 310 |
if news_item:
|
| 311 |
news_text = news_item.get('summary', 'No news')
|
| 312 |
sentiment = senti_analyzer.polarity_scores(news_text)
|
|
|
|
| 314 |
news_raw_str = f"{compound:.2f}"
|
| 315 |
if compound >= 0.5: news_score = 0.05
|
| 316 |
elif compound >= 0.1: news_score = 0.02
|
| 317 |
+
except Exception as e:
|
| 318 |
+
pass
|
| 319 |
+
candidate['news_text'] = news_text
|
| 320 |
|
| 321 |
# (ج. مونت كارلو المتقدمة)
|
| 322 |
try:
|
| 323 |
full_ohlcv_1h = await data_manager.get_latest_ohlcv(symbol, '1h', limit=100)
|
| 324 |
+
if not full_ohlcv_1h or len(full_ohlcv_1h) < 30:
|
| 325 |
+
pass
|
| 326 |
+
else:
|
| 327 |
mc_data = {'1h': full_ohlcv_1h}
|
| 328 |
mc_res = await ml_processor.mc_analyzer.generate_1h_distribution_advanced(mc_data)
|
| 329 |
if mc_res and not mc_res.get('error', False):
|
| 330 |
prob_gain = mc_res.get('probability_of_gain', 0.5)
|
| 331 |
mc_raw_str = f"{prob_gain:.2f}"
|
| 332 |
+
if prob_gain > 0.5:
|
| 333 |
+
adv_mc_score = min(0.10, (prob_gain - 0.5) * 0.20)
|
| 334 |
+
else:
|
| 335 |
+
adv_mc_score = 0.0
|
| 336 |
+
else:
|
| 337 |
+
reason = mc_res.get('reason', 'Unknown') if mc_res else "Null Result"
|
| 338 |
+
mc_raw_str = f"Err: {reason}"
|
| 339 |
+
except Exception as e:
|
| 340 |
+
pass
|
| 341 |
|
| 342 |
+
# (د. حساب الدرجة النهائية)
|
| 343 |
final_score = l1_score + whale_score + news_score + adv_mc_score
|
| 344 |
candidate['final_total_score'] = final_score
|
| 345 |
candidate['l2_scores'] = {'whale': whale_score, 'news': news_score, 'adv_mc': adv_mc_score}
|
| 346 |
candidate['l2_raw_values'] = {'whale': whale_raw_str, 'news': news_raw_str, 'adv_mc': mc_raw_str}
|
| 347 |
l2_enriched_candidates.append(candidate)
|
| 348 |
|
| 349 |
+
# --- 3. إعادة الترتيب وطباعة الجدول (Full Detail) ---
|
| 350 |
log_and_print(f" [Cycle 3/5] 📊 إعادة ترتيب المرشحين حسب الدرجة النهائية (L1 + L2)...")
|
| 351 |
sorted_finalists = sorted(l2_enriched_candidates, key=lambda x: x['final_total_score'], reverse=True)
|
| 352 |
|
|
|
|
| 354 |
header = f"{'SYMBOL':<10} | {'L1 SCORE':<8} | {'WHALE (Flow)':<22} | {'NEWS (Sent)':<18} | {'ADV MC (Prob)':<18} | {'FINAL':<8}"
|
| 355 |
log_and_print(header)
|
| 356 |
log_and_print("-" * 135)
|
| 357 |
+
|
| 358 |
for cand in sorted_finalists:
|
| 359 |
+
sym = cand['symbol']
|
| 360 |
+
l1 = cand['enhanced_final_score']
|
| 361 |
+
l2 = cand['l2_scores']
|
| 362 |
+
l2_raw = cand['l2_raw_values']
|
| 363 |
+
final = cand['final_total_score']
|
| 364 |
whale_cell = f"{l2['whale']:.2f} ({l2_raw['whale']})"
|
| 365 |
news_cell = f"{l2['news']:.2f} ({l2_raw['news']})"
|
| 366 |
mc_cell = f"{l2['adv_mc']:.2f} ({l2_raw['adv_mc']})"
|
| 367 |
log_and_print(f"{sym:<10} | {l1:.4f} | {whale_cell:<22} | {news_cell:<18} | {mc_cell:<18} | {final:.4f}")
|
| 368 |
+
|
| 369 |
log_and_print("="*135 + "\n")
|
| 370 |
|
| 371 |
# --- 4. اختيار أفضل 5 للنموذج الضخم (Oracle) ---
|
|
|
|
| 380 |
if signal['final_total_score'] < 0.60:
|
| 381 |
log_and_print(f" -> 🛑 {symbol} تم استبعاده (الدرجة النهائية {signal['final_total_score']:.2f} < 0.60)")
|
| 382 |
continue
|
| 383 |
+
|
| 384 |
log_and_print(f" -> 🧠 [Oracle Scan] جاري فحص {symbol}...")
|
| 385 |
+
|
| 386 |
try:
|
| 387 |
oracle_decision = await oracle_engine.predict(signal)
|
| 388 |
+
action = oracle_decision.get('action')
|
| 389 |
+
confidence = oracle_decision.get('confidence', 0.0)
|
| 390 |
reason = oracle_decision.get('analysis_summary') or oracle_decision.get('reason', 'No summary provided')
|
| 391 |
+
|
| 392 |
+
# فلتر الشورت الصارم
|
| 393 |
if "SHORT" in str(reason).upper() or "SHORT" in str(oracle_decision.get('strategy')).upper():
|
| 394 |
log_and_print(f" 🛑 [Oracle SKIP] {symbol} تم تجاهلها (إشارة بيع SHORT).")
|
| 395 |
continue
|
|
|
|
| 402 |
oracle_approved_signals.append(signal)
|
| 403 |
else:
|
| 404 |
log_and_print(f" 🛑 [Oracle REJECTED] {symbol} (Conf: {confidence:.2f})")
|
| 405 |
+
log_and_print(f" 📝 Reason: {reason[:200]}...")
|
| 406 |
+
|
| 407 |
except Exception as e:
|
| 408 |
log_and_print(f" ⚠️ [Oracle Error] فشل تحليل Oracle لـ {symbol}: {e}")
|
| 409 |
traceback.print_exc(file=log_buffer)
|
|
|
|
| 411 |
|
| 412 |
log_and_print(f" -> 🧠 انتهى فحص Oracle في {time.time() - oracle_start_time:.2f} ثانية. (تمت الموافقة على {len(oracle_approved_signals)} إشارة)")
|
| 413 |
|
| 414 |
+
# --- L4 Sniper Batch ---
|
| 415 |
if oracle_approved_signals:
|
| 416 |
log_and_print(f" -> 🎯 [L4 Sniper Batch] إرسال {len(oracle_approved_signals)} إشارة للقناص للفرز النهائي واختيار الأفضل...")
|
| 417 |
|
|
|
|
| 418 |
tm_log_buffer = StringIO()
|
| 419 |
with redirect_stdout(tm_log_buffer), redirect_stderr(tm_log_buffer):
|
| 420 |
await trade_manager.select_and_execute_best_signal(oracle_approved_signals)
|
| 421 |
|
| 422 |
tm_logs = tm_log_buffer.getvalue()
|
| 423 |
+
print(tm_logs)
|
| 424 |
+
log_buffer.write(tm_logs + '\n')
|
| 425 |
else:
|
| 426 |
log_and_print(" -> 🎯 [L4 Sniper Batch] لا توجد إشارات معتمدة من العقل لإرسالها للقناص.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
|
| 428 |
+
log_and_print("✅ الدورة اكتملت.")
|
| 429 |
+
sys_state.cycle_running = False
|
| 430 |
+
sys_state.logs = log_buffer.getvalue()
|
|
|
|
| 431 |
|
| 432 |
+
except Exception as e:
|
| 433 |
+
log_and_print(f"❌ Error: {e}")
|
| 434 |
+
traceback.print_exc()
|
| 435 |
+
sys_state.cycle_running = False
|
| 436 |
+
sys_state.logs = log_buffer.getvalue()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 437 |
|
| 438 |
# ==============================================================================
|
| 439 |
+
# 📊 واجهة Gradio (UI)
|
| 440 |
# ==============================================================================
|
| 441 |
+
async def update_ui():
|
| 442 |
+
log_text = sys_state.logs
|
| 443 |
+
|
| 444 |
if not sys_state.ready:
|
| 445 |
+
return log_text, "**System:** 🟠 Loading...", "Wait...", "---", "---", None, pd.DataFrame()
|
| 446 |
+
|
| 447 |
+
status_text = f"**System:** 🟢 Ready | **Cycle:** {'Running' if sys_state.cycle_running else 'Idle'}"
|
| 448 |
+
|
| 449 |
+
if not trade_manager:
|
| 450 |
+
return log_text, status_text, "...", "---", "---", None, pd.DataFrame()
|
| 451 |
|
|
|
|
|
|
|
| 452 |
n_trades = len(trade_manager.open_positions)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
df_watch = pd.DataFrame(list(trade_manager.watchlist.keys()), columns=["Watchlist"])
|
| 454 |
|
|
|
|
| 455 |
if n_trades == 0:
|
| 456 |
+
return log_text, status_text, "### No Active Trades", "---", "---", None, df_watch
|
| 457 |
|
| 458 |
+
# عرض الصفقة
|
| 459 |
try:
|
| 460 |
symbol = list(trade_manager.open_positions.keys())[0]
|
| 461 |
trade = trade_manager.open_positions[symbol]
|
| 462 |
+
curr = await data_manager.get_latest_price_async(symbol)
|
|
|
|
| 463 |
entry = trade['entry_price']
|
| 464 |
|
| 465 |
+
pnl = ((curr - entry)/entry)*100 if entry else 0
|
| 466 |
+
col = "green" if pnl >= 0 else "red"
|
| 467 |
+
pnl_html = f"<h2 style='color:{col}; text-align:center;'>{pnl:.2f}%</h2>"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
|
|
|
|
| 469 |
details = f"""
|
| 470 |
**Entry:** {fmt_price(entry)}
|
| 471 |
+
**Current:** {fmt_price(curr)}
|
| 472 |
**TP:** {fmt_price(trade['tp_price'])}
|
| 473 |
**SL:** {fmt_price(trade['sl_price'])}
|
| 474 |
"""
|
|
|
|
|
|
|
| 475 |
|
| 476 |
+
# الرسم البياني
|
| 477 |
+
fig = plt.figure(figsize=(10, 4), dpi=100)
|
| 478 |
try:
|
| 479 |
ohlcv = await data_manager.get_latest_ohlcv(symbol, '5m', 100)
|
| 480 |
if ohlcv:
|
| 481 |
df = pd.DataFrame(ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
|
| 482 |
df['dt'] = pd.to_datetime(df['ts'], unit='ms')
|
| 483 |
+
ax = plt.gca()
|
| 484 |
+
ax.plot(df['dt'], df['c'], color='#00ffcc', label='Price')
|
| 485 |
+
ax.axhline(entry, color='gray', linestyle='--', label='Entry')
|
| 486 |
+
ax.axhline(trade['tp_price'], color='green', linestyle=':', label='TP')
|
| 487 |
+
ax.axhline(trade['sl_price'], color='red', linestyle=':', label='SL')
|
| 488 |
+
ax.set_facecolor('#0b0f19')
|
| 489 |
+
fig.patch.set_facecolor('#0b0f19')
|
| 490 |
+
ax.tick_params(colors='white')
|
| 491 |
+
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
|
| 492 |
+
plt.title(f"{symbol}", color='white')
|
| 493 |
+
plt.legend(facecolor='#1f2937', labelcolor='white')
|
| 494 |
plt.tight_layout()
|
| 495 |
else:
|
| 496 |
+
plt.text(0.5, 0.5, "No Data", color='white', ha='center')
|
| 497 |
+
plt.axis('off')
|
| 498 |
except:
|
| 499 |
plt.close()
|
| 500 |
fig = None
|
| 501 |
|
| 502 |
+
return log_text, status_text, f"### {symbol}", pnl_html, details, fig, df_watch
|
|
|
|
| 503 |
except Exception as e:
|
| 504 |
+
return log_text, status_text, f"Error: {e}", "...", "...", None, df_watch
|
| 505 |
|
| 506 |
+
def create_dashboard():
|
| 507 |
+
css = """
|
| 508 |
+
body { background-color: #0b0f19; color: white; }
|
| 509 |
+
.gradio-container { background-color: #0b0f19; }
|
| 510 |
+
"""
|
| 511 |
+
with gr.Blocks(title="Titan Trader", theme=gr.themes.Monochrome(), css=css) as demo:
|
| 512 |
+
gr.Markdown("# 🏛️ Titan Automated Trading System")
|
| 513 |
|
| 514 |
with gr.Row():
|
| 515 |
with gr.Column(scale=3):
|
| 516 |
+
chart = gr.Plot(label="Live Chart", show_label=False)
|
| 517 |
with gr.Column(scale=1):
|
| 518 |
+
sym = gr.Markdown("### Loading...")
|
| 519 |
+
pnl = gr.HTML("---")
|
| 520 |
+
det = gr.Markdown("...")
|
| 521 |
|
| 522 |
with gr.Row():
|
| 523 |
+
btn = gr.Button("🚀 Start Analysis Cycle", variant="primary")
|
| 524 |
+
stat = gr.Markdown("**System:** Starting...")
|
| 525 |
|
| 526 |
with gr.Row():
|
| 527 |
+
logs = gr.Textbox(label="System Logs", lines=12, max_lines=20, autoscroll=True)
|
| 528 |
watch = gr.DataFrame(label="Watchlist")
|
| 529 |
|
| 530 |
# Events
|
| 531 |
+
async def on_click():
|
| 532 |
+
if sys_state.cycle_running: return sys_state.logs
|
| 533 |
await run_unified_cycle()
|
| 534 |
+
return sys_state.logs
|
| 535 |
|
| 536 |
+
btn.click(on_click, outputs=logs)
|
| 537 |
|
| 538 |
+
# Auto-refresh every 5s
|
| 539 |
+
timer = gr.Timer(5)
|
| 540 |
+
timer.tick(update_ui, outputs=[logs, stat, sym, pnl, det, chart, watch])
|
|
|
|
|
|
|
|
|
|
| 541 |
|
| 542 |
+
# Initial load
|
| 543 |
+
demo.load(update_ui, outputs=[logs, stat, sym, pnl, det, chart, watch])
|
|
|
|
|
|
|
|
|
|
| 544 |
|
| 545 |
return demo
|
| 546 |
|
| 547 |
# ==============================================================================
|
| 548 |
+
# 🔥 Main Entry
|
| 549 |
# ==============================================================================
|
| 550 |
app = FastAPI()
|
| 551 |
+
dash = create_dashboard()
|
| 552 |
+
app = gr.mount_gradio_app(app, dash, path="/")
|
| 553 |
|
|
|
|
| 554 |
@app.get("/run-cycle")
|
| 555 |
+
async def cron_job(bg: BackgroundTasks):
|
| 556 |
+
if not sys_state.ready or sys_state.cycle_running: return {"status": "Busy/NotReady"}
|
| 557 |
bg.add_task(run_unified_cycle)
|
| 558 |
+
return {"status": "Triggered"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 559 |
|
| 560 |
if __name__ == "__main__":
|
| 561 |
import uvicorn
|
|
|
|
| 562 |
uvicorn.run(app, host="0.0.0.0", port=7860, access_log=False)
|