Spaces:
Building
Building
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app.py (Fully updated to Explorer-Sentry-Executor architecture V5.
|
| 2 |
import os
|
| 3 |
import traceback
|
| 4 |
import signal
|
|
@@ -79,7 +79,9 @@ async def initialize_services():
|
|
| 79 |
global learning_hub_global, trade_manager_global, sentiment_analyzer_global
|
| 80 |
global symbol_whale_monitor_global
|
| 81 |
try:
|
| 82 |
-
|
|
|
|
|
|
|
| 83 |
print(" 🔄 تهيئة R2Service..."); r2_service_global = R2Service(); state_manager.set_service_initialized('r2_service'); print(" ✅ R2Service مهيأة")
|
| 84 |
print(" 🔄 جلب قاعدة بيانات العقود..."); contracts_database = await r2_service_global.load_contracts_db_async(); print(f" ✅ تم تحميل {len(contracts_database)} عقد")
|
| 85 |
|
|
@@ -124,6 +126,7 @@ async def initialize_services():
|
|
| 124 |
|
| 125 |
print(" 🔄 تهيئة مدير الصفقات (Layer 2 Sentry + Layer 3 Executor)...");
|
| 126 |
|
|
|
|
| 127 |
trade_manager_global = TradeManager(
|
| 128 |
r2_service=r2_service_global,
|
| 129 |
learning_hub=learning_hub_global,
|
|
@@ -487,14 +490,16 @@ async def re_analyze_open_trade_async(trade_data):
|
|
| 487 |
|
| 488 |
async def run_bot_cycle_async():
|
| 489 |
"""
|
| 490 |
-
(محدث V5.
|
| 491 |
"""
|
| 492 |
try:
|
| 493 |
if not await state_manager.wait_for_initialization():
|
| 494 |
print("❌ Services not fully initialized - skipping cycle"); return
|
| 495 |
|
|
|
|
| 496 |
# (إضافة: تأخير بسيط لضمان تحرير القفل من الدورة السابقة)
|
| 497 |
await asyncio.sleep(1.0)
|
|
|
|
| 498 |
|
| 499 |
print("🔄 Starting Explorer cycle (Layer 1)...");
|
| 500 |
await r2_service_global.save_system_logs_async({"explorer_cycle_started": True})
|
|
@@ -528,16 +533,13 @@ async def run_bot_cycle_async():
|
|
| 528 |
print(f" ℹ️ (Explorer) Holding {trade.get('symbol')}. Resetting 15-min timer.")
|
| 529 |
await trade_manager_global.update_trade_strategy(trade, result['decision'])
|
| 530 |
|
| 531 |
-
# 🔴 --- START OF CHANGE (V5.8 - FIX) --- 🔴
|
| 532 |
elif result and result['decision'].get('action') == "CLOSE_TRADE":
|
| 533 |
print(f" 🛑 (Explorer) LLM Re-analysis ordered CLOSE_TRADE for {trade.get('symbol')}. Executing...")
|
| 534 |
-
# (استدعاء المنفذ لإغلاق الصفقة)
|
| 535 |
await trade_manager_global.immediate_close_trade(
|
| 536 |
trade.get('symbol'),
|
| 537 |
-
result['current_price'],
|
| 538 |
f"Strategic Exit: LLM Re-analysis ({result['decision'].get('reasoning', 'N/A')[:50]}...)"
|
| 539 |
)
|
| 540 |
-
# 🔴 --- END OF CHANGE --- 🔴
|
| 541 |
|
| 542 |
elif result:
|
| 543 |
print(f" ℹ️ (Explorer) Re-analysis returned unhandled action '{result['decision'].get('action')}' for {trade.get('symbol')}.")
|
|
@@ -605,7 +607,7 @@ async def lifespan(application: FastAPI):
|
|
| 605 |
await cleanup_on_shutdown()
|
| 606 |
|
| 607 |
|
| 608 |
-
application = FastAPI(lifespan=lifespan, title="AI Trading Bot", description="Explorer-Sentry-Executor Architecture (V5.
|
| 609 |
|
| 610 |
@application.get("/")
|
| 611 |
async def root(): return {"message": "Welcome to the AI Trading System", "system": "Explorer-Sentry-Executor", "status": "running" if state_manager.initialization_complete else "initializing", "timestamp": datetime.now().isoformat()}
|
|
@@ -617,7 +619,7 @@ async def run_cycle_api():
|
|
| 617 |
return {"message": "Explorer (Layer 1) cycle initiated", "system": "Explorer-Sentry-Executor"}
|
| 618 |
|
| 619 |
@application.get("/health")
|
| 620 |
-
async def health_check(): return {"status": "healthy" if state_manager.initialization_complete else "initializing", "initialization_complete": state_manager.initialization_complete, "services_initialized": state_manager.services_initialized, "initialization_error": state_manager.initialization_error, "timestamp": datetime.now().isoformat(), "system_architecture": "Explorer-Sentry-Executor (V5.
|
| 621 |
|
| 622 |
@application.get("/analyze-market")
|
| 623 |
async def analyze_market_api():
|
|
@@ -670,5 +672,5 @@ def signal_handler(signum, frame): print(f"🛑 Received signal {signum}. Initia
|
|
| 670 |
signal.signal(signal.SIGINT, signal_handler); signal.signal(signal.SIGTERM, signal_handler)
|
| 671 |
|
| 672 |
if __name__ == "__main__":
|
| 673 |
-
print("🚀 Starting AI Trading Bot (Explorer-Sentry-Executor V5.
|
| 674 |
uvicorn.run( application, host="0.0.0.0", port=7860, log_level="info", access_log=True )
|
|
|
|
| 1 |
+
# app.py (Fully updated to Explorer-Sentry-Executor architecture V5.9 - Callback Logic)
|
| 2 |
import os
|
| 3 |
import traceback
|
| 4 |
import signal
|
|
|
|
| 79 |
global learning_hub_global, trade_manager_global, sentiment_analyzer_global
|
| 80 |
global symbol_whale_monitor_global
|
| 81 |
try:
|
| 82 |
+
# 🔴 --- START OF CHANGE (V7.0) --- 🔴
|
| 83 |
+
print("🚀 بدء تهيئة الخدمات (بنية Sentry الجديدة V5.9)...")
|
| 84 |
+
# 🔴 --- END OF CHANGE --- 🔴
|
| 85 |
print(" 🔄 تهيئة R2Service..."); r2_service_global = R2Service(); state_manager.set_service_initialized('r2_service'); print(" ✅ R2Service مهيأة")
|
| 86 |
print(" 🔄 جلب قاعدة بيانات العقود..."); contracts_database = await r2_service_global.load_contracts_db_async(); print(f" ✅ تم تحميل {len(contracts_database)} عقد")
|
| 87 |
|
|
|
|
| 126 |
|
| 127 |
print(" 🔄 تهيئة مدير الصفقات (Layer 2 Sentry + Layer 3 Executor)...");
|
| 128 |
|
| 129 |
+
# (تمرير دالة الدورة كـ "رد نداء" ليتم استدعاؤها بعد إغلاق الصفقة)
|
| 130 |
trade_manager_global = TradeManager(
|
| 131 |
r2_service=r2_service_global,
|
| 132 |
learning_hub=learning_hub_global,
|
|
|
|
| 490 |
|
| 491 |
async def run_bot_cycle_async():
|
| 492 |
"""
|
| 493 |
+
(محدث V5.9) - دورة البوت الرئيسية (المستكشف)
|
| 494 |
"""
|
| 495 |
try:
|
| 496 |
if not await state_manager.wait_for_initialization():
|
| 497 |
print("❌ Services not fully initialized - skipping cycle"); return
|
| 498 |
|
| 499 |
+
# 🔴 --- START OF CHANGE (V6.9) --- 🔴
|
| 500 |
# (إضافة: تأخير بسيط لضمان تحرير القفل من الدورة السابقة)
|
| 501 |
await asyncio.sleep(1.0)
|
| 502 |
+
# 🔴 --- END OF CHANGE --- 🔴
|
| 503 |
|
| 504 |
print("🔄 Starting Explorer cycle (Layer 1)...");
|
| 505 |
await r2_service_global.save_system_logs_async({"explorer_cycle_started": True})
|
|
|
|
| 533 |
print(f" ℹ️ (Explorer) Holding {trade.get('symbol')}. Resetting 15-min timer.")
|
| 534 |
await trade_manager_global.update_trade_strategy(trade, result['decision'])
|
| 535 |
|
|
|
|
| 536 |
elif result and result['decision'].get('action') == "CLOSE_TRADE":
|
| 537 |
print(f" 🛑 (Explorer) LLM Re-analysis ordered CLOSE_TRADE for {trade.get('symbol')}. Executing...")
|
|
|
|
| 538 |
await trade_manager_global.immediate_close_trade(
|
| 539 |
trade.get('symbol'),
|
| 540 |
+
result['current_price'],
|
| 541 |
f"Strategic Exit: LLM Re-analysis ({result['decision'].get('reasoning', 'N/A')[:50]}...)"
|
| 542 |
)
|
|
|
|
| 543 |
|
| 544 |
elif result:
|
| 545 |
print(f" ℹ️ (Explorer) Re-analysis returned unhandled action '{result['decision'].get('action')}' for {trade.get('symbol')}.")
|
|
|
|
| 607 |
await cleanup_on_shutdown()
|
| 608 |
|
| 609 |
|
| 610 |
+
application = FastAPI(lifespan=lifespan, title="AI Trading Bot", description="Explorer-Sentry-Executor Architecture (V5.9)", version="5.9.0")
|
| 611 |
|
| 612 |
@application.get("/")
|
| 613 |
async def root(): return {"message": "Welcome to the AI Trading System", "system": "Explorer-Sentry-Executor", "status": "running" if state_manager.initialization_complete else "initializing", "timestamp": datetime.now().isoformat()}
|
|
|
|
| 619 |
return {"message": "Explorer (Layer 1) cycle initiated", "system": "Explorer-Sentry-Executor"}
|
| 620 |
|
| 621 |
@application.get("/health")
|
| 622 |
+
async def health_check(): return {"status": "healthy" if state_manager.initialization_complete else "initializing", "initialization_complete": state_manager.initialization_complete, "services_initialized": state_manager.services_initialized, "initialization_error": state_manager.initialization_error, "timestamp": datetime.now().isoformat(), "system_architecture": "Explorer-Sentry-Executor (V5.9)"}
|
| 623 |
|
| 624 |
@application.get("/analyze-market")
|
| 625 |
async def analyze_market_api():
|
|
|
|
| 672 |
signal.signal(signal.SIGINT, signal_handler); signal.signal(signal.SIGTERM, signal_handler)
|
| 673 |
|
| 674 |
if __name__ == "__main__":
|
| 675 |
+
print("🚀 Starting AI Trading Bot (Explorer-Sentry-Executor V5.9)...")
|
| 676 |
uvicorn.run( application, host="0.0.0.0", port=7860, log_level="info", access_log=True )
|