Riy777 commited on
Commit
3ed4595
·
verified ·
1 Parent(s): 57368cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -25
app.py CHANGED
@@ -1,48 +1,62 @@
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)
 
1
+ # app.py (وضع المحاكاة المؤقت - V1.0)
2
+ # هذا الملف يحل محل البوت الحي لتشغيل اختبارات تاريخية.
3
+
4
  import uvicorn
5
  import asyncio
6
+ import os
7
  from fastapi import FastAPI, BackgroundTasks
8
  from contextlib import asynccontextmanager
 
9
 
10
+ # محاولة استيراد محرك المحاكاة
11
+ # يجب أن يكون مجلد simulation_engine بجانب هذا الملف تماماً
12
  try:
13
  from simulation_engine.sim_runner import run_realistic_simulation, SIM_STATUS, SIM_CONFIG
14
+ SIMULATION_AVAILABLE = True
15
+ except ImportError as e:
16
+ print(f"❌ خطأ فادح: لم يتم العثور على محرك المحاكاة. تأكد من وجود مجلد 'simulation_engine' والمِلَف '__init__.py' بداخله.\nالتفاصيل: {e}")
17
+ SIMULATION_AVAILABLE = False
18
+
19
+ # --- مهمة الخلفية المستمرة ---
20
+ async def auto_start_simulation():
21
+ """تبدأ المحاكاة تلقائياً بعد فترة قصيرة من تشغيل التطبيق"""
22
+ if not SIMULATION_AVAILABLE:
23
+ print("🚫 لن يتم بدء المحاكاة بسبب أخطاء الاستيراد.")
24
+ return
25
+
26
+ print("⏳ ستبدأ المحاكاة تلقائياً خلال 15 ثانية... (تأكد من أن البيانات جاهزة)")
27
+ await asyncio.sleep(15)
28
+
29
+ # تشغيل المحاكاة (هذه الدالة ستستغرق وقتاً طويلاً حتى تنتهي)
30
  await run_realistic_simulation()
31
+ print("✅ انتهت جلسة المحاكاة. يمكنك مراجعة النتائج في R2.")
32
 
33
+ # --- إعداد FastAPI ---
34
  @asynccontextmanager
35
  async def lifespan(app: FastAPI):
36
+ # عند بدء التشغيل، نطلق مهمة المحاكاة في الخلفية
37
+ task = asyncio.create_task(auto_start_simulation())
38
  yield
39
+ # عند الإيقاف (لا يوجد شيء خاص للتنظيف هنا حالياً)
40
  pass
41
 
42
+ app = FastAPI(lifespan=lifespan, title="Titan Simulation Runner (Temporary)")
43
 
44
  @app.get("/")
45
  async def root():
46
+ """واجهة بسيطة لعرض حالة المحاكاة"""
47
+ if not SIMULATION_AVAILABLE:
48
+ return {"status": "ERROR", "message": "Simulation engine not found."}
49
+
50
  return {
51
+ "status": "RUNNING" if SIM_STATUS["running"] else "IDLE (Waiting or Finished)",
52
+ "progress": f"{SIM_STATUS['progress']:.2f}%",
53
+ "virtual_balance": f"${SIM_STATUS['current_balance']:.2f}",
54
  "trades_executed": SIM_STATUS["trades_count"],
55
+ "simulation_period": f"{SIM_CONFIG['START_DATE']} -> {SIM_CONFIG['END_DATE']}"
56
  }
57
 
58
  if __name__ == "__main__":
59
+ # تشغيل السيرفر
60
+ print("🔥 تشغيل خادم المحاكاة (Titan Sim)...")
61
+ # نستخدم منفذ مختلف قليلاً أو نفسه حسب رغبتك، هنا نستخدم الافتراضي 7860
62
  uvicorn.run(app, host="0.0.0.0", port=7860)