Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app.py (V12.3 -
|
| 2 |
import os
|
| 3 |
import traceback
|
| 4 |
import signal
|
|
@@ -13,18 +13,16 @@ from fastapi import FastAPI, HTTPException, BackgroundTasks
|
|
| 13 |
from datetime import datetime
|
| 14 |
from typing import List, Dict, Any
|
| 15 |
|
| 16 |
-
# --- استيراد الخدمات ---
|
| 17 |
try:
|
| 18 |
from r2 import R2Service
|
| 19 |
from LLM import LLMService
|
| 20 |
-
from data_manager import DataManager
|
| 21 |
from ml_engine.processor import MLProcessor
|
| 22 |
from learning_hub.hub_manager import LearningHubManager
|
| 23 |
from trade_manager import TradeManager
|
| 24 |
except ImportError as e:
|
| 25 |
sys.exit(f"❌ Fatal Error: {e}")
|
| 26 |
|
| 27 |
-
# --- المتغيرات العالمية ---
|
| 28 |
r2_service_global = None
|
| 29 |
data_manager_global = None
|
| 30 |
llm_service_global = None
|
|
@@ -32,7 +30,6 @@ learning_hub_global = None
|
|
| 32 |
trade_manager_global = None
|
| 33 |
ml_processor_global = None
|
| 34 |
|
| 35 |
-
# --- مدير الحالة ---
|
| 36 |
class StateManager:
|
| 37 |
def __init__(self):
|
| 38 |
self.initialization_complete = False
|
|
@@ -46,13 +43,12 @@ class StateManager:
|
|
| 46 |
|
| 47 |
state_manager = StateManager()
|
| 48 |
|
| 49 |
-
# --- التهيئة المركزية ---
|
| 50 |
async def initialize_services():
|
| 51 |
global r2_service_global, data_manager_global, llm_service_global
|
| 52 |
global learning_hub_global, trade_manager_global, ml_processor_global
|
| 53 |
|
| 54 |
try:
|
| 55 |
-
print("🚀 [System V12.3] Starting
|
| 56 |
r2_service_global = R2Service()
|
| 57 |
state_manager.set_service_initialized('r2')
|
| 58 |
|
|
@@ -74,7 +70,9 @@ async def initialize_services():
|
|
| 74 |
trade_manager_global = TradeManager(
|
| 75 |
r2_service_global,
|
| 76 |
data_manager_global,
|
| 77 |
-
titan_engine=ml_processor_global.titan
|
|
|
|
|
|
|
| 78 |
)
|
| 79 |
await trade_manager_global.initialize_sentry_exchanges()
|
| 80 |
state_manager.set_service_initialized('trade')
|
|
@@ -85,7 +83,6 @@ async def initialize_services():
|
|
| 85 |
traceback.print_exc()
|
| 86 |
return False
|
| 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...")
|
|
@@ -94,13 +91,11 @@ async def run_explorer_cycle():
|
|
| 94 |
print(f"\n🔭 [Explorer V12.3] Cycle started at {datetime.now().strftime('%H:%M:%S')}")
|
| 95 |
|
| 96 |
try:
|
| 97 |
-
# 1. غربلة سريعة (Layer 1)
|
| 98 |
candidates = await data_manager_global.layer1_rapid_screening()
|
| 99 |
if not candidates:
|
| 100 |
print("😴 [Explorer] No candidates found in Layer 1.")
|
| 101 |
return
|
| 102 |
|
| 103 |
-
# 2. تحليل عميق (Layer 2 - Titan Hybrid)
|
| 104 |
print(f"🔬 [Titan Hybrid] analyzing {len(candidates)} candidates...")
|
| 105 |
titan_candidates = []
|
| 106 |
all_scored_debug = []
|
|
@@ -120,24 +115,23 @@ async def run_explorer_cycle():
|
|
| 120 |
score = res.get('enhanced_final_score', 0.0)
|
| 121 |
all_scored_debug.append(res)
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
|
|
|
| 125 |
titan_candidates.append(res)
|
| 126 |
|
| 127 |
data_queue.task_done()
|
| 128 |
await producer
|
| 129 |
|
| 130 |
-
# 3. التحديث النهائي للحارس
|
| 131 |
if titan_candidates:
|
| 132 |
titan_candidates.sort(key=lambda x: x['enhanced_final_score'], reverse=True)
|
| 133 |
top_picks = titan_candidates[:5]
|
| 134 |
print(f"✅ [Explorer] Sending {len(top_picks)} to Sentry.")
|
| 135 |
await trade_manager_global.update_sentry_watchlist(top_picks)
|
| 136 |
else:
|
| 137 |
-
print("📉 [Explorer]
|
| 138 |
-
# 🔥 طباعة تشخيصية مفصلة لأفضل المرفوضين 🔥
|
| 139 |
if all_scored_debug:
|
| 140 |
-
print(f"\n🔍 [Debug] أفضل 10 مرفوضين (
|
| 141 |
all_scored_debug.sort(key=lambda x: x.get('enhanced_final_score', 0.0), reverse=True)
|
| 142 |
for i, cand in enumerate(all_scored_debug[:10]):
|
| 143 |
final = cand.get('enhanced_final_score', 0.0)
|
|
@@ -145,7 +139,6 @@ async def run_explorer_cycle():
|
|
| 145 |
t_s = comps.get('titan_score', 0.0)
|
| 146 |
p_s = comps.get('patterns_score', 0.0)
|
| 147 |
m_s = comps.get('mc_score', 0.0)
|
| 148 |
-
# طباعة مفصلة: النتيجة النهائية [تيتان | أنماط | مونت كارلو]
|
| 149 |
print(f" #{i+1} {cand['symbol']:<10}: {final:.4f} [🐺Titan:{t_s:.2f} | 📊Pat:{p_s:.2f} | 🎲MC:{m_s:.2f}]")
|
| 150 |
print("-" * 60)
|
| 151 |
|
|
@@ -155,7 +148,6 @@ async def run_explorer_cycle():
|
|
| 155 |
finally:
|
| 156 |
gc.collect()
|
| 157 |
|
| 158 |
-
# --- FastAPI Setup ---
|
| 159 |
@asynccontextmanager
|
| 160 |
async def lifespan(app: FastAPI):
|
| 161 |
asyncio.create_task(initialize_services())
|
|
@@ -164,18 +156,28 @@ async def lifespan(app: FastAPI):
|
|
| 164 |
if data_manager_global: await data_manager_global.close()
|
| 165 |
print("👋 [System] Shutdown complete.")
|
| 166 |
|
| 167 |
-
app = FastAPI(lifespan=lifespan, title="Titan Trading Bot V12.3")
|
| 168 |
|
| 169 |
@app.get("/")
|
| 170 |
async def root():
|
| 171 |
-
return {"status": "
|
| 172 |
|
| 173 |
@app.get("/run-cycle")
|
| 174 |
async def trigger_cycle(background_tasks: BackgroundTasks):
|
| 175 |
if not state_manager.initialization_complete:
|
| 176 |
raise HTTPException(status_code=503, detail="System initializing...")
|
| 177 |
background_tasks.add_task(run_explorer_cycle)
|
| 178 |
-
return {"message": "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
if __name__ == "__main__":
|
| 181 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
# app.py (V12.3 - Hybrid Orchestrator with Correct Naming)
|
| 2 |
import os
|
| 3 |
import traceback
|
| 4 |
import signal
|
|
|
|
| 13 |
from datetime import datetime
|
| 14 |
from typing import List, Dict, Any
|
| 15 |
|
|
|
|
| 16 |
try:
|
| 17 |
from r2 import R2Service
|
| 18 |
from LLM import LLMService
|
| 19 |
+
from ml_engine.data_manager import DataManager
|
| 20 |
from ml_engine.processor import MLProcessor
|
| 21 |
from learning_hub.hub_manager import LearningHubManager
|
| 22 |
from trade_manager import TradeManager
|
| 23 |
except ImportError as e:
|
| 24 |
sys.exit(f"❌ Fatal Error: {e}")
|
| 25 |
|
|
|
|
| 26 |
r2_service_global = None
|
| 27 |
data_manager_global = None
|
| 28 |
llm_service_global = None
|
|
|
|
| 30 |
trade_manager_global = None
|
| 31 |
ml_processor_global = None
|
| 32 |
|
|
|
|
| 33 |
class StateManager:
|
| 34 |
def __init__(self):
|
| 35 |
self.initialization_complete = False
|
|
|
|
| 43 |
|
| 44 |
state_manager = StateManager()
|
| 45 |
|
|
|
|
| 46 |
async def initialize_services():
|
| 47 |
global r2_service_global, data_manager_global, llm_service_global
|
| 48 |
global learning_hub_global, trade_manager_global, ml_processor_global
|
| 49 |
|
| 50 |
try:
|
| 51 |
+
print("🚀 [System V12.3] Starting Hybrid Initialization...")
|
| 52 |
r2_service_global = R2Service()
|
| 53 |
state_manager.set_service_initialized('r2')
|
| 54 |
|
|
|
|
| 70 |
trade_manager_global = TradeManager(
|
| 71 |
r2_service_global,
|
| 72 |
data_manager_global,
|
| 73 |
+
titan_engine=ml_processor_global.titan,
|
| 74 |
+
# تمرير المعالج بالكامل للوصول إلى التقييم الهجين لاحقاً إذا احتجنا
|
| 75 |
+
processor=ml_processor_global
|
| 76 |
)
|
| 77 |
await trade_manager_global.initialize_sentry_exchanges()
|
| 78 |
state_manager.set_service_initialized('trade')
|
|
|
|
| 83 |
traceback.print_exc()
|
| 84 |
return False
|
| 85 |
|
|
|
|
| 86 |
async def run_explorer_cycle():
|
| 87 |
if not state_manager.initialization_complete:
|
| 88 |
print("⏳ [Cycle Skipped] System still initializing...")
|
|
|
|
| 91 |
print(f"\n🔭 [Explorer V12.3] Cycle started at {datetime.now().strftime('%H:%M:%S')}")
|
| 92 |
|
| 93 |
try:
|
|
|
|
| 94 |
candidates = await data_manager_global.layer1_rapid_screening()
|
| 95 |
if not candidates:
|
| 96 |
print("😴 [Explorer] No candidates found in Layer 1.")
|
| 97 |
return
|
| 98 |
|
|
|
|
| 99 |
print(f"🔬 [Titan Hybrid] analyzing {len(candidates)} candidates...")
|
| 100 |
titan_candidates = []
|
| 101 |
all_scored_debug = []
|
|
|
|
| 115 |
score = res.get('enhanced_final_score', 0.0)
|
| 116 |
all_scored_debug.append(res)
|
| 117 |
|
| 118 |
+
# استخدام العتبة الهجينة الجديدة
|
| 119 |
+
if score >= data_manager_global.HYBRID_ENTRY_THRESHOLD:
|
| 120 |
+
print(f" 🌟 [Hybrid Approved] {res['symbol']} Score: {score:.4f}")
|
| 121 |
titan_candidates.append(res)
|
| 122 |
|
| 123 |
data_queue.task_done()
|
| 124 |
await producer
|
| 125 |
|
|
|
|
| 126 |
if titan_candidates:
|
| 127 |
titan_candidates.sort(key=lambda x: x['enhanced_final_score'], reverse=True)
|
| 128 |
top_picks = titan_candidates[:5]
|
| 129 |
print(f"✅ [Explorer] Sending {len(top_picks)} to Sentry.")
|
| 130 |
await trade_manager_global.update_sentry_watchlist(top_picks)
|
| 131 |
else:
|
| 132 |
+
print("📉 [Explorer] No candidates met the Hybrid Threshold this cycle.")
|
|
|
|
| 133 |
if all_scored_debug:
|
| 134 |
+
print(f"\n🔍 [Debug] أفضل 10 مرفوضين (العتبة الهجينة: {data_manager_global.HYBRID_ENTRY_THRESHOLD}):")
|
| 135 |
all_scored_debug.sort(key=lambda x: x.get('enhanced_final_score', 0.0), reverse=True)
|
| 136 |
for i, cand in enumerate(all_scored_debug[:10]):
|
| 137 |
final = cand.get('enhanced_final_score', 0.0)
|
|
|
|
| 139 |
t_s = comps.get('titan_score', 0.0)
|
| 140 |
p_s = comps.get('patterns_score', 0.0)
|
| 141 |
m_s = comps.get('mc_score', 0.0)
|
|
|
|
| 142 |
print(f" #{i+1} {cand['symbol']:<10}: {final:.4f} [🐺Titan:{t_s:.2f} | 📊Pat:{p_s:.2f} | 🎲MC:{m_s:.2f}]")
|
| 143 |
print("-" * 60)
|
| 144 |
|
|
|
|
| 148 |
finally:
|
| 149 |
gc.collect()
|
| 150 |
|
|
|
|
| 151 |
@asynccontextmanager
|
| 152 |
async def lifespan(app: FastAPI):
|
| 153 |
asyncio.create_task(initialize_services())
|
|
|
|
| 156 |
if data_manager_global: await data_manager_global.close()
|
| 157 |
print("👋 [System] Shutdown complete.")
|
| 158 |
|
| 159 |
+
app = FastAPI(lifespan=lifespan, title="Titan Hybrid Trading Bot V12.3")
|
| 160 |
|
| 161 |
@app.get("/")
|
| 162 |
async def root():
|
| 163 |
+
return {"status": "Hybrid System Online", "initialized": state_manager.initialization_complete}
|
| 164 |
|
| 165 |
@app.get("/run-cycle")
|
| 166 |
async def trigger_cycle(background_tasks: BackgroundTasks):
|
| 167 |
if not state_manager.initialization_complete:
|
| 168 |
raise HTTPException(status_code=503, detail="System initializing...")
|
| 169 |
background_tasks.add_task(run_explorer_cycle)
|
| 170 |
+
return {"message": "Hybrid cycle triggered"}
|
| 171 |
+
|
| 172 |
+
@app.get("/status")
|
| 173 |
+
async def get_status():
|
| 174 |
+
sentry_status = trade_manager_global.watchlist if trade_manager_global else {}
|
| 175 |
+
return {
|
| 176 |
+
"initialized": state_manager.initialization_complete,
|
| 177 |
+
"sentry_targets": list(sentry_status.keys()),
|
| 178 |
+
# استخدام الاسم الجديد في الحالة
|
| 179 |
+
"hybrid_threshold": data_manager_global.HYBRID_ENTRY_THRESHOLD if data_manager_global else None
|
| 180 |
+
}
|
| 181 |
|
| 182 |
if __name__ == "__main__":
|
| 183 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|