Update app.py
Browse files
app.py
CHANGED
|
@@ -1,183 +1,48 @@
|
|
| 1 |
-
# app.py (
|
| 2 |
-
import os
|
| 3 |
-
import traceback
|
| 4 |
-
import signal
|
| 5 |
-
import sys
|
| 6 |
import uvicorn
|
| 7 |
import asyncio
|
| 8 |
-
import
|
| 9 |
-
import gc
|
| 10 |
-
import time
|
| 11 |
from contextlib import asynccontextmanager
|
| 12 |
-
|
| 13 |
-
from datetime import datetime
|
| 14 |
-
from typing import List, Dict, Any
|
| 15 |
|
|
|
|
| 16 |
try:
|
| 17 |
-
from
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
ml_processor_global = None
|
| 32 |
-
|
| 33 |
-
class StateManager:
|
| 34 |
-
def __init__(self):
|
| 35 |
-
self.initialization_complete = False
|
| 36 |
-
self.services_initialized = {}
|
| 37 |
-
|
| 38 |
-
def set_service_initialized(self, service_name):
|
| 39 |
-
self.services_initialized[service_name] = True
|
| 40 |
-
if len(self.services_initialized) >= 5:
|
| 41 |
-
self.initialization_complete = True
|
| 42 |
-
print("🎯 [System] All services initialized. Ready for external triggers.")
|
| 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 |
-
|
| 55 |
-
contracts_db = await r2_service_global.load_contracts_db_async() or {}
|
| 56 |
-
data_manager_global = DataManager(contracts_db, None, r2_service_global)
|
| 57 |
-
await data_manager_global.initialize()
|
| 58 |
-
state_manager.set_service_initialized('data')
|
| 59 |
-
|
| 60 |
-
llm_service_global = LLMService()
|
| 61 |
-
llm_service_global.r2_service = r2_service_global
|
| 62 |
-
learning_hub_global = LearningHubManager(r2_service_global, llm_service_global, data_manager_global)
|
| 63 |
-
await learning_hub_global.initialize()
|
| 64 |
-
state_manager.set_service_initialized('hub')
|
| 65 |
-
|
| 66 |
-
ml_processor_global = MLProcessor(None, data_manager_global, learning_hub_global)
|
| 67 |
-
await ml_processor_global.initialize()
|
| 68 |
-
state_manager.set_service_initialized('processor')
|
| 69 |
-
|
| 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')
|
| 79 |
-
|
| 80 |
-
return True
|
| 81 |
-
except Exception as e:
|
| 82 |
-
print(f"❌ [Init Error] {e}")
|
| 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...")
|
| 89 |
-
return
|
| 90 |
-
|
| 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 = []
|
| 102 |
-
|
| 103 |
-
data_queue = asyncio.Queue(maxsize=10)
|
| 104 |
-
producer = asyncio.create_task(data_manager_global.stream_ohlcv_data(candidates, data_queue))
|
| 105 |
-
|
| 106 |
-
while True:
|
| 107 |
-
batch = await data_queue.get()
|
| 108 |
-
if batch is None:
|
| 109 |
-
data_queue.task_done()
|
| 110 |
-
break
|
| 111 |
-
|
| 112 |
-
for raw_data in batch:
|
| 113 |
-
res = await ml_processor_global.process_and_score_symbol_enhanced(raw_data)
|
| 114 |
-
if res:
|
| 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)
|
| 138 |
-
comps = cand.get('components', {})
|
| 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 |
-
|
| 145 |
-
except Exception as e:
|
| 146 |
-
print(f"❌ [Cycle Error] {e}")
|
| 147 |
-
traceback.print_exc()
|
| 148 |
-
finally:
|
| 149 |
-
gc.collect()
|
| 150 |
-
|
| 151 |
@asynccontextmanager
|
| 152 |
async def lifespan(app: FastAPI):
|
| 153 |
-
|
|
|
|
| 154 |
yield
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
print("👋 [System] Shutdown complete.")
|
| 158 |
|
| 159 |
-
app = FastAPI(lifespan=lifespan, title="Titan
|
| 160 |
|
| 161 |
@app.get("/")
|
| 162 |
async def root():
|
| 163 |
-
|
| 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 |
-
"
|
| 177 |
-
"
|
| 178 |
-
|
| 179 |
-
"
|
|
|
|
| 180 |
}
|
| 181 |
|
| 182 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 183 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
# app.py (Simulation Version - Auto-Runner)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import uvicorn
|
| 3 |
import asyncio
|
| 4 |
+
from fastapi import FastAPI, BackgroundTasks
|
|
|
|
|
|
|
| 5 |
from contextlib import asynccontextmanager
|
| 6 |
+
import os
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
# استيراد مشغل المحاكاة والحالة
|
| 9 |
try:
|
| 10 |
+
from simulation_engine.sim_runner import run_realistic_simulation, SIM_STATUS, SIM_CONFIG
|
| 11 |
+
except ImportError:
|
| 12 |
+
print("❌ Error: تأكد من أنك داخل مجلد المحاكاة وأن simulation_engine موجود.")
|
| 13 |
+
exit(1)
|
| 14 |
+
|
| 15 |
+
# مهمة الخلفية التي لا تتوقف
|
| 16 |
+
async def continuous_simulation_task():
|
| 17 |
+
print("⏳ انتظار قصير قبل بدء المحاكاة (10 ثواني)...")
|
| 18 |
+
await asyncio.sleep(10)
|
| 19 |
+
# تشغيل المحاكاة مرة واحدة (يمكن وضعها في while True لو أردت تكرارها بتواريخ مختلفة)
|
| 20 |
+
await run_realistic_simulation()
|
| 21 |
+
print("✅ تمت مهمة المحاكاة التلقائية.")
|
| 22 |
+
|
| 23 |
+
# إعداد التطبيق
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
@asynccontextmanager
|
| 25 |
async def lifespan(app: FastAPI):
|
| 26 |
+
# عند البدء: تشغيل المحاكاة في الخلفية فوراً
|
| 27 |
+
task = asyncio.create_task(continuous_simulation_task())
|
| 28 |
yield
|
| 29 |
+
# عند الإيقاف: لا شيء مميز
|
| 30 |
+
pass
|
|
|
|
| 31 |
|
| 32 |
+
app = FastAPI(lifespan=lifespan, title="Titan Simulation Runner")
|
| 33 |
|
| 34 |
@app.get("/")
|
| 35 |
async def root():
|
| 36 |
+
# واجهة بسيطة تعرض الحالة الحالية
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
return {
|
| 38 |
+
"status": "RUNNING" if SIM_STATUS["running"] else "IDLE (Finished or Not Started)",
|
| 39 |
+
"progress": f"{SIM_STATUS['progress']:.1f}%",
|
| 40 |
+
"current_sim_balance": f"${SIM_STATUS['current_balance']:.2f}",
|
| 41 |
+
"trades_executed": SIM_STATUS["trades_count"],
|
| 42 |
+
"config": SIM_CONFIG
|
| 43 |
}
|
| 44 |
|
| 45 |
if __name__ == "__main__":
|
| 46 |
+
# تشغيل السيرفر الذي سيبدأ المحاكاة تلقائياً
|
| 47 |
+
print("🔥 تشغيل خادم المحاكاة... ستبدأ المحاكاة تلقائياً.")
|
| 48 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|