Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app.py (V12.
|
| 2 |
import os
|
| 3 |
import traceback
|
| 4 |
import signal
|
|
@@ -40,8 +40,7 @@ class StateManager:
|
|
| 40 |
|
| 41 |
def set_service_initialized(self, service_name):
|
| 42 |
self.services_initialized[service_name] = True
|
| 43 |
-
|
| 44 |
-
if len(self.services_initialized) >= 5: # r2, data, hub, processor, trade
|
| 45 |
self.initialization_complete = True
|
| 46 |
print("🎯 [System] All services initialized. Ready for external triggers.")
|
| 47 |
|
|
@@ -53,9 +52,7 @@ async def initialize_services():
|
|
| 53 |
global learning_hub_global, trade_manager_global, ml_processor_global
|
| 54 |
|
| 55 |
try:
|
| 56 |
-
print("🚀 [System V12.
|
| 57 |
-
|
| 58 |
-
# 1. الأساسيات
|
| 59 |
r2_service_global = R2Service()
|
| 60 |
state_manager.set_service_initialized('r2')
|
| 61 |
|
|
@@ -64,19 +61,16 @@ async def initialize_services():
|
|
| 64 |
await data_manager_global.initialize()
|
| 65 |
state_manager.set_service_initialized('data')
|
| 66 |
|
| 67 |
-
# 2. الذكاء
|
| 68 |
llm_service_global = LLMService()
|
| 69 |
llm_service_global.r2_service = r2_service_global
|
| 70 |
learning_hub_global = LearningHubManager(r2_service_global, llm_service_global, data_manager_global)
|
| 71 |
await learning_hub_global.initialize()
|
| 72 |
state_manager.set_service_initialized('hub')
|
| 73 |
|
| 74 |
-
# 3. المعالج (Titan Core)
|
| 75 |
ml_processor_global = MLProcessor(None, data_manager_global, learning_hub_global)
|
| 76 |
await ml_processor_global.initialize()
|
| 77 |
state_manager.set_service_initialized('processor')
|
| 78 |
|
| 79 |
-
# 4. مدير التداول
|
| 80 |
trade_manager_global = TradeManager(
|
| 81 |
r2_service_global,
|
| 82 |
data_manager_global,
|
|
@@ -93,12 +87,11 @@ async def initialize_services():
|
|
| 93 |
|
| 94 |
# --- دورة المستكشف (Titan Explorer Cycle) ---
|
| 95 |
async def run_explorer_cycle():
|
| 96 |
-
# حماية: لا تعمل إذا لم يكتمل التحميل
|
| 97 |
if not state_manager.initialization_complete:
|
| 98 |
print("⏳ [Cycle Skipped] System still initializing...")
|
| 99 |
return
|
| 100 |
|
| 101 |
-
print(f"\n🔭 [Explorer V12.
|
| 102 |
|
| 103 |
try:
|
| 104 |
# 1. غربلة سريعة (Layer 1)
|
|
@@ -110,6 +103,7 @@ async def run_explorer_cycle():
|
|
| 110 |
# 2. تحليل عميق (Layer 2 - Titan)
|
| 111 |
print(f"🔬 [Titan] analyzing {len(candidates)} candidates...")
|
| 112 |
titan_candidates = []
|
|
|
|
| 113 |
|
| 114 |
data_queue = asyncio.Queue(maxsize=10)
|
| 115 |
producer = asyncio.create_task(data_manager_global.stream_ohlcv_data(candidates, data_queue))
|
|
@@ -122,76 +116,61 @@ async def run_explorer_cycle():
|
|
| 122 |
|
| 123 |
for raw_data in batch:
|
| 124 |
res = await ml_processor_global.process_and_score_symbol_enhanced(raw_data)
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
data_queue.task_done()
|
| 131 |
await producer
|
| 132 |
|
| 133 |
-
# 3. التحديث النهائي للحارس
|
| 134 |
if titan_candidates:
|
| 135 |
titan_candidates.sort(key=lambda x: x['enhanced_final_score'], reverse=True)
|
| 136 |
-
# نرسل أفضل 5 فقط للحارس ليركز عليهم
|
| 137 |
top_picks = titan_candidates[:5]
|
| 138 |
print(f"✅ [Explorer] Sending {len(top_picks)} to Sentry.")
|
| 139 |
await trade_manager_global.update_sentry_watchlist(top_picks)
|
| 140 |
else:
|
| 141 |
print("📉 [Explorer] Titan rejected all candidates this cycle.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
except Exception as e:
|
| 144 |
print(f"❌ [Cycle Error] {e}")
|
| 145 |
traceback.print_exc()
|
| 146 |
finally:
|
| 147 |
-
# تنظيف الذاكرة بعد كل دورة مهم جداً عند التشغيل المستمر
|
| 148 |
gc.collect()
|
| 149 |
|
| 150 |
# --- FastAPI Setup ---
|
| 151 |
@asynccontextmanager
|
| 152 |
async def lifespan(app: FastAPI):
|
| 153 |
-
# بدء التهيئة عند تشغيل البوت
|
| 154 |
asyncio.create_task(initialize_services())
|
| 155 |
yield
|
| 156 |
-
# تنظيف عند الإيقاف
|
| 157 |
if trade_manager_global: await trade_manager_global.stop_sentry_loops()
|
| 158 |
if data_manager_global: await data_manager_global.close()
|
| 159 |
print("👋 [System] Shutdown complete.")
|
| 160 |
|
| 161 |
-
app = FastAPI(lifespan=lifespan, title="Titan Trading Bot V12.
|
| 162 |
|
| 163 |
@app.get("/")
|
| 164 |
async def root():
|
| 165 |
-
return {
|
| 166 |
-
|
| 167 |
-
"initialized": state_manager.initialization_complete,
|
| 168 |
-
"waiting_for_trigger": True
|
| 169 |
-
}
|
| 170 |
-
|
| 171 |
-
# ==================================================================
|
| 172 |
-
# 🔌 نقطة النهاية للمجدول الخارجي (External Trigger Endpoint)
|
| 173 |
-
# ==================================================================
|
| 174 |
@app.get("/run-cycle")
|
| 175 |
async def trigger_cycle(background_tasks: BackgroundTasks):
|
| 176 |
-
"""
|
| 177 |
-
يتم استدعاء هذا الرابط كل 15 دقيقة من قبل المجدول الخارجي.
|
| 178 |
-
يقوم بتشغيل دورة بحث كاملة في الخلفية.
|
| 179 |
-
"""
|
| 180 |
if not state_manager.initialization_complete:
|
| 181 |
-
raise HTTPException(status_code=503, detail="System
|
| 182 |
-
|
| 183 |
background_tasks.add_task(run_explorer_cycle)
|
| 184 |
-
return {"message": "
|
| 185 |
-
|
| 186 |
-
# نقطة نهاية إضافية لفحص الحالة بسرعة
|
| 187 |
-
@app.get("/status")
|
| 188 |
-
async def get_status():
|
| 189 |
-
sentry_status = trade_manager_global.watchlist if trade_manager_global else {}
|
| 190 |
-
return {
|
| 191 |
-
"initialized": state_manager.initialization_complete,
|
| 192 |
-
"sentry_targets": list(sentry_status.keys()),
|
| 193 |
-
"titan_threshold": data_manager_global.TITAN_ENTRY_THRESHOLD if data_manager_global else None
|
| 194 |
-
}
|
| 195 |
|
| 196 |
if __name__ == "__main__":
|
| 197 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
# app.py (V12.2 - Titan Orchestrator + Diagnostics)
|
| 2 |
import os
|
| 3 |
import traceback
|
| 4 |
import signal
|
|
|
|
| 40 |
|
| 41 |
def set_service_initialized(self, service_name):
|
| 42 |
self.services_initialized[service_name] = True
|
| 43 |
+
if len(self.services_initialized) >= 5:
|
|
|
|
| 44 |
self.initialization_complete = True
|
| 45 |
print("🎯 [System] All services initialized. Ready for external triggers.")
|
| 46 |
|
|
|
|
| 52 |
global learning_hub_global, trade_manager_global, ml_processor_global
|
| 53 |
|
| 54 |
try:
|
| 55 |
+
print("🚀 [System V12.2] Starting Titan-Powered Initialization...")
|
|
|
|
|
|
|
| 56 |
r2_service_global = R2Service()
|
| 57 |
state_manager.set_service_initialized('r2')
|
| 58 |
|
|
|
|
| 61 |
await data_manager_global.initialize()
|
| 62 |
state_manager.set_service_initialized('data')
|
| 63 |
|
|
|
|
| 64 |
llm_service_global = LLMService()
|
| 65 |
llm_service_global.r2_service = r2_service_global
|
| 66 |
learning_hub_global = LearningHubManager(r2_service_global, llm_service_global, data_manager_global)
|
| 67 |
await learning_hub_global.initialize()
|
| 68 |
state_manager.set_service_initialized('hub')
|
| 69 |
|
|
|
|
| 70 |
ml_processor_global = MLProcessor(None, data_manager_global, learning_hub_global)
|
| 71 |
await ml_processor_global.initialize()
|
| 72 |
state_manager.set_service_initialized('processor')
|
| 73 |
|
|
|
|
| 74 |
trade_manager_global = TradeManager(
|
| 75 |
r2_service_global,
|
| 76 |
data_manager_global,
|
|
|
|
| 87 |
|
| 88 |
# --- دورة المستكشف (Titan Explorer Cycle) ---
|
| 89 |
async def run_explorer_cycle():
|
|
|
|
| 90 |
if not state_manager.initialization_complete:
|
| 91 |
print("⏳ [Cycle Skipped] System still initializing...")
|
| 92 |
return
|
| 93 |
|
| 94 |
+
print(f"\n🔭 [Explorer V12.2] Cycle started at {datetime.now().strftime('%H:%M:%S')}")
|
| 95 |
|
| 96 |
try:
|
| 97 |
# 1. غربلة سريعة (Layer 1)
|
|
|
|
| 103 |
# 2. تحليل عميق (Layer 2 - Titan)
|
| 104 |
print(f"🔬 [Titan] analyzing {len(candidates)} candidates...")
|
| 105 |
titan_candidates = []
|
| 106 |
+
all_scored_debug = [] # 🔥 قائمة جديدة للتشخيص
|
| 107 |
|
| 108 |
data_queue = asyncio.Queue(maxsize=10)
|
| 109 |
producer = asyncio.create_task(data_manager_global.stream_ohlcv_data(candidates, data_queue))
|
|
|
|
| 116 |
|
| 117 |
for raw_data in batch:
|
| 118 |
res = await ml_processor_global.process_and_score_symbol_enhanced(raw_data)
|
| 119 |
+
if res:
|
| 120 |
+
score = res.get('enhanced_final_score', 0.0)
|
| 121 |
+
# تخزين للتشخيص
|
| 122 |
+
all_scored_debug.append(res)
|
| 123 |
+
|
| 124 |
+
if score >= data_manager_global.TITAN_ENTRY_THRESHOLD:
|
| 125 |
+
print(f" 🌟 [Titan Approved] {res['symbol']} Score: {score:.4f}")
|
| 126 |
+
titan_candidates.append(res)
|
| 127 |
|
| 128 |
data_queue.task_done()
|
| 129 |
await producer
|
| 130 |
|
| 131 |
+
# 3. التحديث النهائي للحارس (مع التشخيص)
|
| 132 |
if titan_candidates:
|
| 133 |
titan_candidates.sort(key=lambda x: x['enhanced_final_score'], reverse=True)
|
|
|
|
| 134 |
top_picks = titan_candidates[:5]
|
| 135 |
print(f"✅ [Explorer] Sending {len(top_picks)} to Sentry.")
|
| 136 |
await trade_manager_global.update_sentry_watchlist(top_picks)
|
| 137 |
else:
|
| 138 |
print("📉 [Explorer] Titan rejected all candidates this cycle.")
|
| 139 |
+
# 🔥 طباعة تشخيصية لأفضل المرفوضين
|
| 140 |
+
if all_scored_debug:
|
| 141 |
+
print(f"\n🔍 [Debug] أفضل 10 مرفوضين (العتبة المطلوبة: {data_manager_global.TITAN_ENTRY_THRESHOLD}):")
|
| 142 |
+
all_scored_debug.sort(key=lambda x: x.get('enhanced_final_score', 0.0), reverse=True)
|
| 143 |
+
for i, cand in enumerate(all_scored_debug[:10]):
|
| 144 |
+
print(f" #{i+1} {cand['symbol']}: {cand.get('enhanced_final_score', 0.0):.4f}")
|
| 145 |
+
print("-" * 40)
|
| 146 |
|
| 147 |
except Exception as e:
|
| 148 |
print(f"❌ [Cycle Error] {e}")
|
| 149 |
traceback.print_exc()
|
| 150 |
finally:
|
|
|
|
| 151 |
gc.collect()
|
| 152 |
|
| 153 |
# --- FastAPI Setup ---
|
| 154 |
@asynccontextmanager
|
| 155 |
async def lifespan(app: FastAPI):
|
|
|
|
| 156 |
asyncio.create_task(initialize_services())
|
| 157 |
yield
|
|
|
|
| 158 |
if trade_manager_global: await trade_manager_global.stop_sentry_loops()
|
| 159 |
if data_manager_global: await data_manager_global.close()
|
| 160 |
print("👋 [System] Shutdown complete.")
|
| 161 |
|
| 162 |
+
app = FastAPI(lifespan=lifespan, title="Titan Trading Bot V12.2")
|
| 163 |
|
| 164 |
@app.get("/")
|
| 165 |
async def root():
|
| 166 |
+
return {"status": "Titan Online", "initialized": state_manager.initialization_complete}
|
| 167 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
@app.get("/run-cycle")
|
| 169 |
async def trigger_cycle(background_tasks: BackgroundTasks):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
if not state_manager.initialization_complete:
|
| 171 |
+
raise HTTPException(status_code=503, detail="System initializing...")
|
|
|
|
| 172 |
background_tasks.add_task(run_explorer_cycle)
|
| 173 |
+
return {"message": "Cycle triggered"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
if __name__ == "__main__":
|
| 176 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|