Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,17 @@
|
|
| 1 |
-
# app.py (V14.
|
| 2 |
-
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from datetime import datetime
|
| 4 |
from contextlib import asynccontextmanager
|
| 5 |
from fastapi import FastAPI, HTTPException, BackgroundTasks
|
| 6 |
|
| 7 |
-
#
|
|
|
|
|
|
|
| 8 |
try:
|
| 9 |
from r2 import R2Service
|
| 10 |
from data_manager import DataManager
|
|
@@ -12,24 +19,26 @@ try:
|
|
| 12 |
from trade_manager import TradeManager
|
| 13 |
from LLM import LLMService
|
| 14 |
from learning_hub.hub_manager import LearningHubManager
|
| 15 |
-
# وحدات الطبقة الثانية
|
| 16 |
from whale_monitor.core import EnhancedWhaleMonitor
|
| 17 |
from sentiment_news import NewsFetcher
|
| 18 |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 19 |
except ImportError as e:
|
| 20 |
-
# إيقاف
|
| 21 |
-
sys.exit(f"❌
|
| 22 |
|
| 23 |
-
#
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
| 33 |
|
| 34 |
class SystemState:
|
| 35 |
def __init__(self):
|
|
@@ -39,318 +48,351 @@ class SystemState:
|
|
| 39 |
sys_state = SystemState()
|
| 40 |
|
| 41 |
# ==============================================================================
|
| 42 |
-
#
|
| 43 |
# ==============================================================================
|
| 44 |
async def initialize_system():
|
| 45 |
global r2, data_manager, ml_processor, trade_manager, llm_service, learning_hub
|
| 46 |
global whale_monitor, news_fetcher, vader
|
| 47 |
|
| 48 |
-
if sys_state.ready:
|
| 49 |
-
|
|
|
|
|
|
|
| 50 |
|
| 51 |
try:
|
| 52 |
-
# 1.
|
| 53 |
r2 = R2Service()
|
| 54 |
-
|
|
|
|
| 55 |
|
| 56 |
-
whale_monitor = EnhancedWhaleMonitor(contracts_db=
|
| 57 |
-
data_manager = DataManager(
|
| 58 |
await data_manager.initialize()
|
| 59 |
-
|
|
|
|
|
|
|
| 60 |
news_fetcher = NewsFetcher()
|
| 61 |
vader = SentimentIntensityAnalyzer()
|
|
|
|
| 62 |
|
| 63 |
-
#
|
| 64 |
llm_service = LLMService()
|
| 65 |
-
llm_service.r2_service = r2 # لربط حفظ
|
| 66 |
-
# سيتم ربط learning_hub لاحقاً لتجنب التبعية الدائرية
|
| 67 |
|
| 68 |
learning_hub = LearningHubManager(r2, llm_service, data_manager)
|
| 69 |
await learning_hub.initialize()
|
| 70 |
-
llm_service.learning_hub = learning_hub # الربط العكسي
|
|
|
|
| 71 |
|
| 72 |
-
#
|
| 73 |
ml_processor = MLProcessor(None, data_manager, learning_hub)
|
| 74 |
await ml_processor.initialize()
|
|
|
|
| 75 |
|
| 76 |
trade_manager = TradeManager(r2, data_manager, ml_processor.titan, ml_processor.pattern_engine)
|
| 77 |
await trade_manager.initialize_sentry_exchanges()
|
| 78 |
-
# بدء
|
| 79 |
asyncio.create_task(trade_manager.start_sentry_loops())
|
|
|
|
| 80 |
|
| 81 |
sys_state.ready = True
|
| 82 |
-
print("
|
| 83 |
|
| 84 |
except Exception as e:
|
| 85 |
-
print(f"❌ [
|
| 86 |
traceback.print_exc()
|
| 87 |
-
sys.exit(1)
|
| 88 |
|
| 89 |
# ==============================================================================
|
| 90 |
-
#
|
| 91 |
# ==============================================================================
|
| 92 |
async def run_unified_cycle():
|
| 93 |
"""
|
| 94 |
-
نقطة الدخول
|
| 95 |
-
|
| 96 |
"""
|
|
|
|
| 97 |
if not sys_state.ready:
|
| 98 |
-
print("⏳ [Cycle Skipped] System not
|
| 99 |
return
|
| 100 |
if sys_state.cycle_running:
|
| 101 |
-
print("⏳ [Cycle Skipped] Another cycle is already
|
| 102 |
return
|
| 103 |
-
|
| 104 |
-
# محاولة الحصول على القفل لمنع تداخل العمليات
|
| 105 |
if not r2.acquire_lock():
|
| 106 |
-
print("🔒 [Cycle Skipped]
|
| 107 |
return
|
| 108 |
|
| 109 |
sys_state.cycle_running = True
|
| 110 |
start_time = datetime.now()
|
| 111 |
|
| 112 |
try:
|
| 113 |
-
#
|
| 114 |
open_trades = list(trade_manager.open_positions.values())
|
| 115 |
|
| 116 |
-
if open_trades:
|
| 117 |
-
# ---
|
| 118 |
-
print(f"\n⚔️ [Unified Cycle] Active trades detected
|
| 119 |
-
await
|
| 120 |
else:
|
| 121 |
-
# ---
|
| 122 |
-
print("\n🔭 [Unified Cycle] No active trades. Engaging EXPLORER
|
| 123 |
-
await
|
| 124 |
|
| 125 |
except Exception as e:
|
| 126 |
-
print(f"❌ [
|
| 127 |
traceback.print_exc()
|
| 128 |
finally:
|
| 129 |
-
#
|
| 130 |
r2.release_lock()
|
| 131 |
sys_state.cycle_running = False
|
| 132 |
-
gc.collect() # تنظيف الذاكرة
|
| 133 |
-
|
|
|
|
| 134 |
|
| 135 |
# ==============================================================================
|
| 136 |
-
#
|
| 137 |
# ==============================================================================
|
| 138 |
-
async def
|
| 139 |
-
"""
|
| 140 |
for trade in open_trades:
|
| 141 |
-
symbol = trade
|
| 142 |
-
|
|
|
|
|
|
|
| 143 |
|
| 144 |
try:
|
| 145 |
-
# 1. جمع البيانات
|
| 146 |
current_price = await data_manager.get_latest_price_async(symbol)
|
| 147 |
whale_data = await whale_monitor.get_symbol_whale_activity(symbol)
|
| 148 |
news_text = await news_fetcher.get_news_for_symbol(symbol)
|
| 149 |
|
| 150 |
-
# محاولة الحصول على
|
| 151 |
-
#
|
| 152 |
-
|
| 153 |
|
| 154 |
current_data_packet = {
|
| 155 |
'symbol': symbol,
|
| 156 |
'current_price': current_price,
|
| 157 |
-
'titan_score':
|
| 158 |
'whale_data': whale_data,
|
| 159 |
'news_text': news_text
|
| 160 |
}
|
| 161 |
|
| 162 |
-
# 2.
|
| 163 |
decision = await llm_service.re_analyze_trade_async(trade, current_data_packet)
|
| 164 |
|
| 165 |
-
# 3. تنفيذ
|
| 166 |
if decision:
|
| 167 |
-
action = decision.get('action')
|
| 168 |
-
reason = decision.get('reasoning', '
|
| 169 |
|
| 170 |
if action == 'EMERGENCY_EXIT':
|
| 171 |
-
print(f" 🚨 BRAIN COMMAND:
|
| 172 |
-
await trade_manager.execute_emergency_exit(symbol, f"Brain
|
| 173 |
|
| 174 |
elif action == 'UPDATE_TARGETS':
|
| 175 |
new_tp = decision.get('new_tp')
|
| 176 |
new_sl = decision.get('new_sl')
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
else:
|
| 181 |
-
print(f" ⚠️ Brain requested target update for {symbol} but provided no values.")
|
| 182 |
else:
|
| 183 |
-
# HOLD
|
| 184 |
-
print(f" ✅ Brain verdict for {symbol}: HOLD.
|
| 185 |
else:
|
| 186 |
-
print(f" ⚠️
|
| 187 |
|
| 188 |
except Exception as e:
|
| 189 |
-
print(f" ❌
|
|
|
|
| 190 |
|
| 191 |
# ==============================================================================
|
| 192 |
-
# 🔭
|
| 193 |
# ==============================================================================
|
| 194 |
-
async def
|
| 195 |
-
"""تنفيذ دورة البحث الكاملة عبر الطبقات الأربع"""
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
data_queue.task_done()
|
| 215 |
-
break
|
| 216 |
-
|
| 217 |
-
for raw_data in batch:
|
| 218 |
-
# المعالجة الأولية باستخدام MLProcessor
|
| 219 |
-
res = await ml_processor.process_and_score_symbol_enhanced(raw_data)
|
| 220 |
-
# عتبة مرور أولية مخففة (مثلاً 0.50) للسماح بمرور عدد كافٍ للطبقة الثانية
|
| 221 |
-
if res and res.get('enhanced_final_score', 0.0) >= 0.50:
|
| 222 |
-
l1_passed.append(res)
|
| 223 |
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
l1_score = cand['enhanced_final_score']
|
| 254 |
-
whale_bonus = 0.15 if whale_data.get('trading_signal', {}).get('action') in ['BUY', 'STRONG_BUY'] else 0.0
|
| 255 |
-
news_bonus = 0.10 if news_score > 0.25 else (-0.10 if news_score < -0.25 else 0.0)
|
| 256 |
-
|
| 257 |
-
final_l2_score = min(1.0, max(0.0, l1_score + whale_bonus + news_bonus))
|
| 258 |
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
for cand in layer3_candidates:
|
| 279 |
-
symbol = cand['symbol']
|
| 280 |
-
print(f" ⚖️ Consulting Brain for {symbol}...")
|
| 281 |
-
|
| 282 |
-
# استشارة العقل الكلي بوجبة البيانات الكاملة
|
| 283 |
-
decision = await llm_service.get_trading_decision(cand)
|
| 284 |
-
|
| 285 |
-
if decision and decision.get('action') == 'WATCH':
|
| 286 |
-
confidence = decision.get('confidence_level', 0)
|
| 287 |
-
print(f" 🎉 APPROVED by Brain! Confidence: {confidence:.2f}")
|
| 288 |
-
cand['llm_decision'] = decision
|
| 289 |
-
approved_targets.append(cand)
|
| 290 |
-
else:
|
| 291 |
-
reason = decision.get('reasoning', 'Unknown reason') if decision else 'Brain Consultation Failed'
|
| 292 |
-
print(f" 🛑 REJECTED by Brain: {reason[:60]}...")
|
| 293 |
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
else:
|
| 302 |
-
|
|
|
|
| 303 |
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
|
| 308 |
# ==============================================================================
|
| 309 |
-
# 🔥
|
| 310 |
# ==============================================================================
|
| 311 |
@asynccontextmanager
|
| 312 |
async def lifespan(app: FastAPI):
|
| 313 |
-
#
|
| 314 |
await initialize_system()
|
| 315 |
yield
|
| 316 |
-
#
|
|
|
|
| 317 |
if trade_manager: await trade_manager.stop_sentry_loops()
|
| 318 |
if data_manager: await data_manager.close()
|
| 319 |
-
print("👋 System Shutdown
|
| 320 |
|
| 321 |
-
app = FastAPI(lifespan=lifespan, title="Titan
|
| 322 |
|
| 323 |
@app.get("/")
|
| 324 |
-
def root():
|
|
|
|
| 325 |
return {
|
| 326 |
-
"
|
| 327 |
"initialized": sys_state.ready,
|
| 328 |
-
"
|
| 329 |
}
|
| 330 |
|
| 331 |
@app.get("/run-cycle")
|
| 332 |
-
async def
|
| 333 |
-
"""نقطة الاستدعاء الخارجية
|
| 334 |
if not sys_state.ready:
|
| 335 |
-
raise HTTPException(status_code=503, detail="System is still initializing
|
| 336 |
|
| 337 |
-
# إضافة الدورة الموحدة إلى مهام الخلفية
|
| 338 |
background_tasks.add_task(run_unified_cycle)
|
| 339 |
-
return {"message": "Unified smart cycle triggered in background."}
|
| 340 |
|
| 341 |
@app.get("/status")
|
| 342 |
-
async def
|
| 343 |
-
"""جلب حالة النظام
|
| 344 |
return {
|
| 345 |
"initialized": sys_state.ready,
|
| 346 |
"cycle_running": sys_state.cycle_running,
|
| 347 |
-
"
|
| 348 |
-
"
|
| 349 |
-
"
|
| 350 |
-
"
|
| 351 |
}
|
| 352 |
|
|
|
|
| 353 |
if __name__ == "__main__":
|
| 354 |
import uvicorn
|
| 355 |
-
|
| 356 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
# app.py (V14.2 - Final Production Version - FULL CODE)
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import traceback
|
| 5 |
+
import asyncio
|
| 6 |
+
import gc
|
| 7 |
+
import json
|
| 8 |
from datetime import datetime
|
| 9 |
from contextlib import asynccontextmanager
|
| 10 |
from fastapi import FastAPI, HTTPException, BackgroundTasks
|
| 11 |
|
| 12 |
+
# ==============================================================================
|
| 13 |
+
# 📥 استيراد الوحدات الأساسية (Core Modules Imports)
|
| 14 |
+
# ==============================================================================
|
| 15 |
try:
|
| 16 |
from r2 import R2Service
|
| 17 |
from data_manager import DataManager
|
|
|
|
| 19 |
from trade_manager import TradeManager
|
| 20 |
from LLM import LLMService
|
| 21 |
from learning_hub.hub_manager import LearningHubManager
|
| 22 |
+
# وحدات الطبقة الثانية المتخصصة
|
| 23 |
from whale_monitor.core import EnhancedWhaleMonitor
|
| 24 |
from sentiment_news import NewsFetcher
|
| 25 |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 26 |
except ImportError as e:
|
| 27 |
+
# إيقاف فوري للنظام في حال فقدان أي مكون حيوي
|
| 28 |
+
sys.exit(f"❌ [FATAL ERROR] Failed to import core modules: {e}")
|
| 29 |
|
| 30 |
+
# ==============================================================================
|
| 31 |
+
# 🌐 المتغيرات العامة وحالة النظام (Global State)
|
| 32 |
+
# ==============================================================================
|
| 33 |
+
r2: R2Service = None
|
| 34 |
+
data_manager: DataManager = None
|
| 35 |
+
ml_processor: MLProcessor = None
|
| 36 |
+
trade_manager: TradeManager = None
|
| 37 |
+
llm_service: LLMService = None
|
| 38 |
+
learning_hub: LearningHubManager = None
|
| 39 |
+
whale_monitor: EnhancedWhaleMonitor = None
|
| 40 |
+
news_fetcher: NewsFetcher = None
|
| 41 |
+
vader: SentimentIntensityAnalyzer = None
|
| 42 |
|
| 43 |
class SystemState:
|
| 44 |
def __init__(self):
|
|
|
|
| 48 |
sys_state = SystemState()
|
| 49 |
|
| 50 |
# ==============================================================================
|
| 51 |
+
# 🛠️ تهيئة النظام (Full System Initialization)
|
| 52 |
# ==============================================================================
|
| 53 |
async def initialize_system():
|
| 54 |
global r2, data_manager, ml_processor, trade_manager, llm_service, learning_hub
|
| 55 |
global whale_monitor, news_fetcher, vader
|
| 56 |
|
| 57 |
+
if sys_state.ready:
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
+
print("\n🔌 [System V14.2] Starting Full Initialization Sequence...")
|
| 61 |
|
| 62 |
try:
|
| 63 |
+
# 1. البنية التحتية والبيانات (Infrastructure Layer)
|
| 64 |
r2 = R2Service()
|
| 65 |
+
contracts_db = await r2.load_contracts_db_async()
|
| 66 |
+
print(f" ✅ R2 Service connected (Contracts loaded: {len(contracts_db)})")
|
| 67 |
|
| 68 |
+
whale_monitor = EnhancedWhaleMonitor(contracts_db=contracts_db, r2_service=r2)
|
| 69 |
+
data_manager = DataManager(contracts_db, whale_monitor, r2)
|
| 70 |
await data_manager.initialize()
|
| 71 |
+
print(" ✅ DataManager & WhaleMonitor initialized.")
|
| 72 |
+
|
| 73 |
+
# 2. أدوات التحليل المساعدة (Auxiliary Tools)
|
| 74 |
news_fetcher = NewsFetcher()
|
| 75 |
vader = SentimentIntensityAnalyzer()
|
| 76 |
+
print(" ✅ NewsFetcher & VADER initialized.")
|
| 77 |
|
| 78 |
+
# 3. العقل والتعلم (Intelligence Layer)
|
| 79 |
llm_service = LLMService()
|
| 80 |
+
llm_service.r2_service = r2 # لربط حفظ السجلات
|
|
|
|
| 81 |
|
| 82 |
learning_hub = LearningHubManager(r2, llm_service, data_manager)
|
| 83 |
await learning_hub.initialize()
|
| 84 |
+
llm_service.learning_hub = learning_hub # الربط العكسي للعقل بمركز التعلم
|
| 85 |
+
print(" ✅ LLM Brain & Learning Hub connected.")
|
| 86 |
|
| 87 |
+
# 4. محركات المعالجة والتنفيذ (Execution Layer)
|
| 88 |
ml_processor = MLProcessor(None, data_manager, learning_hub)
|
| 89 |
await ml_processor.initialize()
|
| 90 |
+
print(" ✅ ML Processor (Titan + Patterns) ready.")
|
| 91 |
|
| 92 |
trade_manager = TradeManager(r2, data_manager, ml_processor.titan, ml_processor.pattern_engine)
|
| 93 |
await trade_manager.initialize_sentry_exchanges()
|
| 94 |
+
# بدء مهام المراقبة الخلفية للحارس
|
| 95 |
asyncio.create_task(trade_manager.start_sentry_loops())
|
| 96 |
+
print(" ✅ TradeManager Sentry loops started.")
|
| 97 |
|
| 98 |
sys_state.ready = True
|
| 99 |
+
print("\n🚀 [SYSTEM READY] All core systems are online and awaiting orders.")
|
| 100 |
|
| 101 |
except Exception as e:
|
| 102 |
+
print(f"\n❌ [INIT FATAL ERROR] System failed to start: {e}")
|
| 103 |
traceback.print_exc()
|
| 104 |
+
sys.exit(1)
|
| 105 |
|
| 106 |
# ==============================================================================
|
| 107 |
+
# 🔄 الدورة الموحدة الذكية (Unified Smart Cycle Dispatcher)
|
| 108 |
# ==============================================================================
|
| 109 |
async def run_unified_cycle():
|
| 110 |
"""
|
| 111 |
+
نقطة الدخول المركزية للدورات.
|
| 112 |
+
تقوم تلقائياً بتوجيه النظام إما لوضع 'إعادة التقييم' (إذا وجدت صفقات) أو وضع 'المستكشف'.
|
| 113 |
"""
|
| 114 |
+
# فحوصات الأمان قبل البدء
|
| 115 |
if not sys_state.ready:
|
| 116 |
+
print("⏳ [Cycle Skipped] System is not fully initialized yet.")
|
| 117 |
return
|
| 118 |
if sys_state.cycle_running:
|
| 119 |
+
print("⏳ [Cycle Skipped] Another cycle is already in progress.")
|
| 120 |
return
|
|
|
|
|
|
|
| 121 |
if not r2.acquire_lock():
|
| 122 |
+
print("🔒 [Cycle Skipped] Could not acquire execution lock.")
|
| 123 |
return
|
| 124 |
|
| 125 |
sys_state.cycle_running = True
|
| 126 |
start_time = datetime.now()
|
| 127 |
|
| 128 |
try:
|
| 129 |
+
# التحقق من وجود صفقات نشطة لدى الحارس
|
| 130 |
open_trades = list(trade_manager.open_positions.values())
|
| 131 |
|
| 132 |
+
if len(open_trades) > 0:
|
| 133 |
+
# --- مسار 1: وضع إعادة التقييم الاستراتيجي ---
|
| 134 |
+
print(f"\n⚔️ [Unified Cycle] Active trades detected: {len(open_trades)}. Engaging STRATEGIC RE-ANALYSIS Mode.")
|
| 135 |
+
await _run_reanalysis_mode_full(open_trades)
|
| 136 |
else:
|
| 137 |
+
# --- مسار 2: وضع المستكشف الكامل ---
|
| 138 |
+
print("\n🔭 [Unified Cycle] No active trades. Engaging FULL EXPLORER Mode (4 Layers).")
|
| 139 |
+
await _run_explorer_mode_full()
|
| 140 |
|
| 141 |
except Exception as e:
|
| 142 |
+
print(f"❌ [CYCLE ERROR] Unexpected error during unified cycle: {e}")
|
| 143 |
traceback.print_exc()
|
| 144 |
finally:
|
| 145 |
+
# ضمان تحرير الموارد والقفل في جميع الحالات
|
| 146 |
r2.release_lock()
|
| 147 |
sys_state.cycle_running = False
|
| 148 |
+
gc.collect() # تنظيف الذاكرة العشوائية
|
| 149 |
+
duration = (datetime.now() - start_time).total_seconds()
|
| 150 |
+
print(f"🏁 [Cycle Completed] Execution time: {duration:.2f} seconds.")
|
| 151 |
|
| 152 |
# ==============================================================================
|
| 153 |
+
# ⚔️ المسار 1: وضع إعادة التقييم الكامل (Full Re-analysis Mode)
|
| 154 |
# ==============================================================================
|
| 155 |
+
async def _run_reanalysis_mode_full(open_trades):
|
| 156 |
+
"""يقوم بإعادة تقييم كل صفقة مفتوحة باستخدام العقل الكلي"""
|
| 157 |
for trade in open_trades:
|
| 158 |
+
symbol = trade.get('symbol')
|
| 159 |
+
if not symbol: continue
|
| 160 |
+
|
| 161 |
+
print(f" ⚖️ [Re-eval] Consulting Omniscient Brain for {symbol}...")
|
| 162 |
|
| 163 |
try:
|
| 164 |
+
# 1. جمع أحدث البيانات من السوق (Fresh Data Snapshot)
|
| 165 |
current_price = await data_manager.get_latest_price_async(symbol)
|
| 166 |
whale_data = await whale_monitor.get_symbol_whale_activity(symbol)
|
| 167 |
news_text = await news_fetcher.get_news_for_symbol(symbol)
|
| 168 |
|
| 169 |
+
# محاولة الحصول على درجة تيتان سريعة (إذا أمكن)
|
| 170 |
+
# (يمكن تحسين هذا الجزء لاحقاً لاستدعاء تيتان فعلياً إذا توفرت الموارد)
|
| 171 |
+
titan_score_now = 0.0
|
| 172 |
|
| 173 |
current_data_packet = {
|
| 174 |
'symbol': symbol,
|
| 175 |
'current_price': current_price,
|
| 176 |
+
'titan_score': titan_score_now,
|
| 177 |
'whale_data': whale_data,
|
| 178 |
'news_text': news_text
|
| 179 |
}
|
| 180 |
|
| 181 |
+
# 2. استدعاء العقل الكلي للتقييم
|
| 182 |
decision = await llm_service.re_analyze_trade_async(trade, current_data_packet)
|
| 183 |
|
| 184 |
+
# 3. تنفيذ القرار فوراً
|
| 185 |
if decision:
|
| 186 |
+
action = decision.get('action', 'HOLD')
|
| 187 |
+
reason = decision.get('reasoning', 'No reasoning provided')
|
| 188 |
|
| 189 |
if action == 'EMERGENCY_EXIT':
|
| 190 |
+
print(f" 🚨 [EXECUTE] BRAIN COMMAND: EMERGENCY EXIT for {symbol}!")
|
| 191 |
+
await trade_manager.execute_emergency_exit(symbol, f"Brain: {reason}")
|
| 192 |
|
| 193 |
elif action == 'UPDATE_TARGETS':
|
| 194 |
new_tp = decision.get('new_tp')
|
| 195 |
new_sl = decision.get('new_sl')
|
| 196 |
+
print(f" 🎯 [EXECUTE] BRAIN COMMAND: Update Targets for {symbol} (TP:{new_tp}, SL:{new_sl})")
|
| 197 |
+
await trade_manager.update_trade_targets(symbol, new_tp, new_sl, f"Brain: {reason}")
|
| 198 |
+
|
|
|
|
|
|
|
| 199 |
else:
|
| 200 |
+
# HOLD أو أي قرار آخر غير حرج
|
| 201 |
+
print(f" ✅ [MAINTAIN] Brain verdict for {symbol}: HOLD. ({reason[:60]}...)")
|
| 202 |
else:
|
| 203 |
+
print(f" ⚠️ [WARNING] Brain returned no valid decision for {symbol}. Holding position.")
|
| 204 |
|
| 205 |
except Exception as e:
|
| 206 |
+
print(f" ❌ [ERROR] Failed to re-evaluate {symbol}: {e}")
|
| 207 |
+
traceback.print_exc()
|
| 208 |
|
| 209 |
# ==============================================================================
|
| 210 |
+
# 🔭 المسار 2: وضع المستكشف الكامل (Full 4-Layer Explorer Mode)
|
| 211 |
# ==============================================================================
|
| 212 |
+
async def _run_explorer_mode_full():
|
| 213 |
+
"""تنفيذ دورة البحث الكاملة عبر الطبقات الأربع بدون أي اختصارات"""
|
| 214 |
+
|
| 215 |
+
# ----------------------------------------------------------------------
|
| 216 |
+
# LAYER 1: Rapid Hybrid Screening (Titan + Patterns + Simple MC)
|
| 217 |
+
# ----------------------------------------------------------------------
|
| 218 |
+
print("\n--- 🛡️ Layer 1: Rapid Hybrid Screening ---")
|
| 219 |
+
raw_candidates = await data_manager.layer1_rapid_screening()
|
| 220 |
+
if not raw_candidates:
|
| 221 |
+
print(" ⚠️ Layer 1 yielded no initial candidates from DataManager.")
|
| 222 |
+
return
|
| 223 |
|
| 224 |
+
print(f" Running ML Processor on {len(raw_candidates)} candidates...")
|
| 225 |
+
l1_passed_candidates = []
|
| 226 |
+
|
| 227 |
+
# استخدام طابور لمعالجة البيانات المتدفقة بشكل غير متزامن
|
| 228 |
+
data_queue = asyncio.Queue()
|
| 229 |
+
producer_task = asyncio.create_task(data_manager.stream_ohlcv_data(raw_candidates, data_queue))
|
| 230 |
+
|
| 231 |
+
while True:
|
| 232 |
+
batch_data = await data_queue.get()
|
| 233 |
+
if batch_data is None:
|
| 234 |
+
data_queue.task_done()
|
| 235 |
+
break
|
| 236 |
|
| 237 |
+
for raw_symbol_data in batch_data:
|
| 238 |
+
# المعالجة الكاملة لكل عملة
|
| 239 |
+
analysis_result = await ml_processor.process_and_score_symbol_enhanced(raw_symbol_data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
+
if analysis_result:
|
| 242 |
+
score = analysis_result.get('enhanced_final_score', 0.0)
|
| 243 |
+
# عتبة المرور الأولية (يمكن تعديلها من الإعدادات)
|
| 244 |
+
if score >= 0.50:
|
| 245 |
+
l1_passed_candidates.append(analysis_result)
|
| 246 |
|
| 247 |
+
data_queue.task_done()
|
| 248 |
+
|
| 249 |
+
await producer_task # انتظار انتهاء تدفق البيانات بالكامل
|
| 250 |
+
|
| 251 |
+
# ترتيب النتائج واختيار أفضل 10
|
| 252 |
+
l1_passed_candidates.sort(key=lambda x: x['enhanced_final_score'], reverse=True)
|
| 253 |
+
layer2_input_candidates = l1_passed_candidates[:10]
|
| 254 |
+
|
| 255 |
+
print(f"✅ Layer 1 Complete. {len(layer2_input_candidates)} candidates advanced to Layer 2.")
|
| 256 |
+
if not layer2_input_candidates:
|
| 257 |
+
return
|
| 258 |
|
| 259 |
+
# طباعة جدول المتأهلين من الطبقة 1
|
| 260 |
+
print("\n📊 [L1] Top Candidates for Deep Analysis:")
|
| 261 |
+
for idx, cand in enumerate(layer2_input_candidates, 1):
|
| 262 |
+
comps = cand.get('components', {})
|
| 263 |
+
print(f" #{idx:2d} {cand['symbol']:<10} | Score: {cand['enhanced_final_score']:.4f} "
|
| 264 |
+
f"[Titan:{comps.get('titan_score',0):.2f}, Pat:{comps.get('patterns_score',0):.2f}, MC:{comps.get('mc_score',0):.2f}]")
|
| 265 |
|
| 266 |
+
# ----------------------------------------------------------------------
|
| 267 |
+
# LAYER 2: Deep Analysis (Whales + News + Advanced Scoring)
|
| 268 |
+
# ----------------------------------------------------------------------
|
| 269 |
+
print("\n--- 🐳 Layer 2: Deep Multi-Factor Analysis ---")
|
| 270 |
+
l2_scored_candidates = []
|
| 271 |
+
|
| 272 |
+
for cand in layer2_input_candidates:
|
| 273 |
+
symbol = cand['symbol']
|
| 274 |
+
print(f" 🔎 Performing deep scan on {symbol}...")
|
| 275 |
+
|
| 276 |
+
# أ. تحليل الحيتان العميق
|
| 277 |
+
whale_data = await whale_monitor.get_symbol_whale_activity(symbol)
|
| 278 |
+
|
| 279 |
+
# ب. تحليل الأخبار والمشاعر
|
| 280 |
+
news_text = await news_fetcher.get_news_for_symbol(symbol)
|
| 281 |
+
news_score_raw = 0.0
|
| 282 |
+
if news_text:
|
| 283 |
+
vader_res = vader.polarity_scores(news_text)
|
| 284 |
+
news_score_raw = vader_res.get('compound', 0.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
+
# ج. حساب النقاط المعززة (Enhanced Layer 2 Score)
|
| 287 |
+
l1_score = cand['enhanced_final_score']
|
| 288 |
+
|
| 289 |
+
# بونص الحيتان (إضافة 15% إذا كانت الإشارة إيجابية)
|
| 290 |
+
whale_signal = whale_data.get('trading_signal', {}).get('action', 'HOLD')
|
| 291 |
+
whale_bonus = 0.15 if whale_signal in ['BUY', 'STRONG_BUY'] else 0.0
|
| 292 |
+
|
| 293 |
+
# بونص الأخبار (إضافة/خصم 10% بناءً على المشاعر)
|
| 294 |
+
news_bonus = 0.0
|
| 295 |
+
if news_score_raw > 0.25: news_bonus = 0.10
|
| 296 |
+
elif news_score_raw < -0.25: news_bonus = -0.10
|
| 297 |
+
|
| 298 |
+
final_l2_score = l1_score + whale_bonus + news_bonus
|
| 299 |
+
# ضمان بقاء النتيجة بين 0 و 1
|
| 300 |
+
final_l2_score = max(0.0, min(1.0, final_l2_score))
|
| 301 |
+
|
| 302 |
+
# تحديث بيانات المرشح للطبقة التالية
|
| 303 |
+
cand.update({
|
| 304 |
+
'layer2_score': final_l2_score,
|
| 305 |
+
'whale_data': whale_data,
|
| 306 |
+
'news_text': news_text,
|
| 307 |
+
'news_score_raw': news_score_raw
|
| 308 |
+
})
|
| 309 |
+
l2_scored_candidates.append(cand)
|
| 310 |
|
| 311 |
+
# ترتيب واختيار أفضل 5 للطبقة الثالثة
|
| 312 |
+
l2_scored_candidates.sort(key=lambda x: x['layer2_score'], reverse=True)
|
| 313 |
+
layer3_input_candidates = l2_scored_candidates[:5]
|
| 314 |
+
|
| 315 |
+
print(f"✅ Layer 2 Complete. {len(layer3_input_candidates)} candidates selected for Brain validation.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
|
| 317 |
+
# ----------------------------------------------------------------------
|
| 318 |
+
# LAYER 3: Omniscient Brain Validation (LLM)
|
| 319 |
+
# ----------------------------------------------------------------------
|
| 320 |
+
print("\n--- 🧠 Layer 3: Omniscient Brain Validation ---")
|
| 321 |
+
approved_targets = []
|
| 322 |
+
|
| 323 |
+
for cand in layer3_input_candidates:
|
| 324 |
+
symbol = cand['symbol']
|
| 325 |
+
print(f" ⚖️ Submitting {symbol} to Omniscient Brain for final verdict...")
|
| 326 |
+
|
| 327 |
+
decision = await llm_service.get_trading_decision(cand)
|
| 328 |
+
|
| 329 |
+
if decision and decision.get('action') == 'WATCH':
|
| 330 |
+
confidence = decision.get('confidence_level', 0.0)
|
| 331 |
+
print(f" 🎉 BRAIN APPROVED: {symbol} | Confidence: {confidence:.2f}")
|
| 332 |
+
cand['llm_decision'] = decision
|
| 333 |
+
approved_targets.append(cand)
|
| 334 |
else:
|
| 335 |
+
reason = decision.get('reasoning', 'Unknown reason') if decision else 'No response from Brain'
|
| 336 |
+
print(f" 🛑 BRAIN REJECTED: {symbol} | Reason: {reason[:60]}...")
|
| 337 |
|
| 338 |
+
# ----------------------------------------------------------------------
|
| 339 |
+
# LAYER 4: Sentry Handover (Active Monitoring)
|
| 340 |
+
# ----------------------------------------------------------------------
|
| 341 |
+
print("\n--- 🛡️ Layer 4: Sentry Handover ---")
|
| 342 |
+
if approved_targets:
|
| 343 |
+
print(f"🚀 Handing over {len(approved_targets)} elite targets to TradeManager Sentry.")
|
| 344 |
+
await trade_manager.update_sentry_watchlist(approved_targets)
|
| 345 |
+
else:
|
| 346 |
+
print("😴 Cycle ended with NO targets passing all 4 layers. Sentry remains on standby.")
|
| 347 |
|
| 348 |
# ==============================================================================
|
| 349 |
+
# 🔥 نقاط نهاية التطبيق (FastAPI Endpoints)
|
| 350 |
# ==============================================================================
|
| 351 |
@asynccontextmanager
|
| 352 |
async def lifespan(app: FastAPI):
|
| 353 |
+
# عند بدء التشغيل
|
| 354 |
await initialize_system()
|
| 355 |
yield
|
| 356 |
+
# عند الإيقاف
|
| 357 |
+
print("\n🛑 [System] Initiating shutdown sequence...")
|
| 358 |
if trade_manager: await trade_manager.stop_sentry_loops()
|
| 359 |
if data_manager: await data_manager.close()
|
| 360 |
+
print("👋 [System] Shutdown complete.")
|
| 361 |
|
| 362 |
+
app = FastAPI(lifespan=lifespan, title="Titan Hybrid System V14.2 (Full Production)")
|
| 363 |
|
| 364 |
@app.get("/")
|
| 365 |
+
async def root():
|
| 366 |
+
"""فحص حالة النظام الأساسية"""
|
| 367 |
return {
|
| 368 |
+
"system_status": "ONLINE",
|
| 369 |
"initialized": sys_state.ready,
|
| 370 |
+
"current_mode": "RE-ANALYSIS" if trade_manager and trade_manager.open_positions else "EXPLORER"
|
| 371 |
}
|
| 372 |
|
| 373 |
@app.get("/run-cycle")
|
| 374 |
+
async def trigger_cycle_endpoint(background_tasks: BackgroundTasks):
|
| 375 |
+
"""نقطة الاستدعاء الخارجية لتشغيل الدورة الموحدة"""
|
| 376 |
if not sys_state.ready:
|
| 377 |
+
raise HTTPException(status_code=503, detail="System is still initializing, please wait.")
|
| 378 |
|
|
|
|
| 379 |
background_tasks.add_task(run_unified_cycle)
|
| 380 |
+
return {"status": "ACCEPTED", "message": "Unified smart cycle has been triggered in background."}
|
| 381 |
|
| 382 |
@app.get("/status")
|
| 383 |
+
async def get_full_status():
|
| 384 |
+
"""جلب تفاصيل حالة النظام الحالية"""
|
| 385 |
return {
|
| 386 |
"initialized": sys_state.ready,
|
| 387 |
"cycle_running": sys_state.cycle_running,
|
| 388 |
+
"active_trades_count": len(trade_manager.open_positions) if trade_manager else 0,
|
| 389 |
+
"active_trades": list(trade_manager.open_positions.keys()) if trade_manager else [],
|
| 390 |
+
"sentry_watchlist_count": len(trade_manager.watchlist) if trade_manager else 0,
|
| 391 |
+
"sentry_watchlist": list(trade_manager.watchlist.keys()) if trade_manager else []
|
| 392 |
}
|
| 393 |
|
| 394 |
+
# نقطة الدخول الرئيسية عند التشغيل المباشر
|
| 395 |
if __name__ == "__main__":
|
| 396 |
import uvicorn
|
| 397 |
+
print("🖥️ Starting Titan Server on port 7860...")
|
| 398 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|