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,9 +40,10 @@ class StateManager:
|
|
| 40 |
|
| 41 |
def set_service_initialized(self, service_name):
|
| 42 |
self.services_initialized[service_name] = True
|
|
|
|
| 43 |
if len(self.services_initialized) >= 5: # r2, data, hub, processor, trade
|
| 44 |
self.initialization_complete = True
|
| 45 |
-
print("🎯 [System] All services initialized.")
|
| 46 |
|
| 47 |
state_manager = StateManager()
|
| 48 |
|
|
@@ -52,7 +53,7 @@ async def initialize_services():
|
|
| 52 |
global learning_hub_global, trade_manager_global, ml_processor_global
|
| 53 |
|
| 54 |
try:
|
| 55 |
-
print("🚀 [System V12.
|
| 56 |
|
| 57 |
# 1. الأساسيات
|
| 58 |
r2_service_global = R2Service()
|
|
@@ -72,14 +73,14 @@ async def initialize_services():
|
|
| 72 |
|
| 73 |
# 3. المعالج (Titan Core)
|
| 74 |
ml_processor_global = MLProcessor(None, data_manager_global, learning_hub_global)
|
| 75 |
-
await ml_processor_global.initialize()
|
| 76 |
state_manager.set_service_initialized('processor')
|
| 77 |
|
| 78 |
-
# 4. مدير التداول
|
| 79 |
trade_manager_global = TradeManager(
|
| 80 |
r2_service_global,
|
| 81 |
data_manager_global,
|
| 82 |
-
titan_engine=ml_processor_global.titan
|
| 83 |
)
|
| 84 |
await trade_manager_global.initialize_sentry_exchanges()
|
| 85 |
state_manager.set_service_initialized('trade')
|
|
@@ -92,19 +93,24 @@ async def initialize_services():
|
|
| 92 |
|
| 93 |
# --- دورة المستكشف (Titan Explorer Cycle) ---
|
| 94 |
async def run_explorer_cycle():
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
try:
|
| 99 |
# 1. غربلة سريعة (Layer 1)
|
| 100 |
candidates = await data_manager_global.layer1_rapid_screening()
|
| 101 |
-
if not candidates:
|
|
|
|
|
|
|
| 102 |
|
| 103 |
# 2. تحليل عميق (Layer 2 - Titan)
|
| 104 |
print(f"🔬 [Titan] analyzing {len(candidates)} candidates...")
|
| 105 |
titan_candidates = []
|
| 106 |
|
| 107 |
-
# استخدام دفق البيانات الجديد الذي يدعم Titan
|
| 108 |
data_queue = asyncio.Queue(maxsize=10)
|
| 109 |
producer = asyncio.create_task(data_manager_global.stream_ohlcv_data(candidates, data_queue))
|
| 110 |
|
|
@@ -116,6 +122,7 @@ async def run_explorer_cycle():
|
|
| 116 |
|
| 117 |
for raw_data in batch:
|
| 118 |
res = await ml_processor_global.process_and_score_symbol_enhanced(raw_data)
|
|
|
|
| 119 |
if res and res['enhanced_final_score'] >= data_manager_global.TITAN_ENTRY_THRESHOLD:
|
| 120 |
print(f" 🌟 [Titan Approved] {res['symbol']} Score: {res['enhanced_final_score']:.4f}")
|
| 121 |
titan_candidates.append(res)
|
|
@@ -124,32 +131,67 @@ async def run_explorer_cycle():
|
|
| 124 |
await producer
|
| 125 |
|
| 126 |
# 3. التحديث النهائي للحارس
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
except Exception as e:
|
| 131 |
print(f"❌ [Cycle Error] {e}")
|
|
|
|
| 132 |
finally:
|
|
|
|
| 133 |
gc.collect()
|
| 134 |
|
| 135 |
# --- FastAPI Setup ---
|
| 136 |
@asynccontextmanager
|
| 137 |
async def lifespan(app: FastAPI):
|
|
|
|
| 138 |
asyncio.create_task(initialize_services())
|
| 139 |
yield
|
|
|
|
| 140 |
if trade_manager_global: await trade_manager_global.stop_sentry_loops()
|
| 141 |
if data_manager_global: await data_manager_global.close()
|
|
|
|
| 142 |
|
| 143 |
-
app = FastAPI(lifespan=lifespan, title="Titan Trading Bot V12.
|
| 144 |
|
| 145 |
@app.get("/")
|
| 146 |
async def root():
|
| 147 |
-
return {
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
if __name__ == "__main__":
|
| 155 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
# app.py (V12.1 - Titan Orchestrator + External Trigger Fixed)
|
| 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 |
+
# نحتاج 5 خدمات أساسية لتعمل قبل بدء أي دورة
|
| 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 |
|
| 48 |
state_manager = StateManager()
|
| 49 |
|
|
|
|
| 53 |
global learning_hub_global, trade_manager_global, ml_processor_global
|
| 54 |
|
| 55 |
try:
|
| 56 |
+
print("🚀 [System V12.1] Starting Titan-Powered Initialization...")
|
| 57 |
|
| 58 |
# 1. الأساسيات
|
| 59 |
r2_service_global = R2Service()
|
|
|
|
| 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,
|
| 83 |
+
titan_engine=ml_processor_global.titan
|
| 84 |
)
|
| 85 |
await trade_manager_global.initialize_sentry_exchanges()
|
| 86 |
state_manager.set_service_initialized('trade')
|
|
|
|
| 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.1] Cycle started at {datetime.now().strftime('%H:%M:%S')}")
|
| 102 |
|
| 103 |
try:
|
| 104 |
# 1. غربلة سريعة (Layer 1)
|
| 105 |
candidates = await data_manager_global.layer1_rapid_screening()
|
| 106 |
+
if not candidates:
|
| 107 |
+
print("😴 [Explorer] No candidates found in Layer 1.")
|
| 108 |
+
return
|
| 109 |
|
| 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))
|
| 116 |
|
|
|
|
| 122 |
|
| 123 |
for raw_data in batch:
|
| 124 |
res = await ml_processor_global.process_and_score_symbol_enhanced(raw_data)
|
| 125 |
+
# استخدام عتبة الدخول الصارمة لـ Titan
|
| 126 |
if res and res['enhanced_final_score'] >= data_manager_global.TITAN_ENTRY_THRESHOLD:
|
| 127 |
print(f" 🌟 [Titan Approved] {res['symbol']} Score: {res['enhanced_final_score']:.4f}")
|
| 128 |
titan_candidates.append(res)
|
|
|
|
| 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.1")
|
| 162 |
|
| 163 |
@app.get("/")
|
| 164 |
async def root():
|
| 165 |
+
return {
|
| 166 |
+
"status": "Titan Online",
|
| 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 still initializing, please wait.")
|
| 182 |
+
|
| 183 |
+
background_tasks.add_task(run_explorer_cycle)
|
| 184 |
+
return {"message": "Titan cycle triggered successfully", "timestamp": datetime.now().isoformat()}
|
| 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)
|