Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# ==============================================================================
|
| 2 |
-
# 🚀 app.py (
|
| 3 |
# ==============================================================================
|
| 4 |
|
| 5 |
import os
|
|
@@ -34,7 +34,7 @@ logger = logging.getLogger("TitanCore")
|
|
| 34 |
# Imports
|
| 35 |
# ------------------------------------------------------------------------------
|
| 36 |
try:
|
| 37 |
-
from r2 import R2Service, INITIAL_CAPITAL
|
| 38 |
from ml_engine.data_manager import DataManager
|
| 39 |
from ml_engine.processor import MLProcessor, SystemLimits
|
| 40 |
from whale_monitor.core import EnhancedWhaleMonitor
|
|
@@ -43,6 +43,14 @@ try:
|
|
| 43 |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 44 |
from learning_hub.adaptive_hub import AdaptiveHub
|
| 45 |
from trade_manager import TradeManager
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
except ImportError as e:
|
| 47 |
logger.critical(f"❌ [FATAL ERROR] Failed to import core modules: {e}")
|
| 48 |
traceback.print_exc()
|
|
@@ -82,7 +90,7 @@ class SystemState:
|
|
| 82 |
|
| 83 |
def set_ready(self):
|
| 84 |
self.ready = True
|
| 85 |
-
self.last_cycle_logs = "✅ System Ready.
|
| 86 |
logger.info("✅ System State set to READY.")
|
| 87 |
|
| 88 |
def set_cycle_start(self):
|
|
@@ -146,15 +154,20 @@ async def auto_pilot_loop():
|
|
| 146 |
await asyncio.sleep(5)
|
| 147 |
if not sys_state.ready: continue
|
| 148 |
|
|
|
|
| 149 |
if adaptive_hub and int(time.time()) % 60 == 0:
|
| 150 |
sys_state.training_status_msg = adaptive_hub.get_status()
|
| 151 |
|
|
|
|
| 152 |
if trade_manager and len(trade_manager.open_positions) > 0:
|
| 153 |
wd_status = await trade_manager.ensure_active_guardians()
|
| 154 |
if "No active" not in wd_status:
|
| 155 |
-
|
|
|
|
|
|
|
| 156 |
continue
|
| 157 |
|
|
|
|
| 158 |
if sys_state.auto_pilot and not sys_state.cycle_running and not sys_state.training_running:
|
| 159 |
if sys_state.last_cycle_time:
|
| 160 |
elapsed = (datetime.now() - sys_state.last_cycle_time).total_seconds()
|
|
@@ -176,13 +189,15 @@ async def auto_pilot_loop():
|
|
| 176 |
async def lifespan(app: FastAPI):
|
| 177 |
global r2, data_manager, ml_processor, adaptive_hub, trade_manager, whale_monitor, news_fetcher, senti_analyzer, sys_state
|
| 178 |
|
| 179 |
-
logger.info("\n🚀 [System] Startup Sequence (Titan
|
| 180 |
try:
|
|
|
|
| 181 |
r2 = R2Service()
|
| 182 |
data_manager = DataManager(contracts_db={}, whale_monitor=None, r2_service=r2)
|
| 183 |
await data_manager.initialize()
|
| 184 |
await data_manager.load_contracts_from_r2()
|
| 185 |
|
|
|
|
| 186 |
whale_monitor = EnhancedWhaleMonitor(contracts_db=data_manager.get_contracts_db(), r2_service=r2)
|
| 187 |
rpc_mgr = AdaptiveRpcManager(data_manager.http_client)
|
| 188 |
whale_monitor.set_rpc_manager(rpc_mgr)
|
|
@@ -191,21 +206,30 @@ async def lifespan(app: FastAPI):
|
|
| 191 |
senti_analyzer = SentimentIntensityAnalyzer()
|
| 192 |
data_manager.whale_monitor = whale_monitor
|
| 193 |
|
|
|
|
|
|
|
| 194 |
adaptive_hub = AdaptiveHub(r2_service=r2)
|
| 195 |
await adaptive_hub.initialize()
|
| 196 |
|
|
|
|
|
|
|
| 197 |
ml_processor = MLProcessor(data_manager=data_manager)
|
| 198 |
await ml_processor.initialize()
|
| 199 |
|
|
|
|
| 200 |
trade_manager = TradeManager(r2_service=r2, data_manager=data_manager, processor=ml_processor)
|
|
|
|
|
|
|
|
|
|
| 201 |
trade_manager.learning_hub = adaptive_hub
|
| 202 |
-
await trade_manager.initialize_sentry_exchanges()
|
| 203 |
|
|
|
|
| 204 |
await trade_manager.start_sentry_loops()
|
| 205 |
|
|
|
|
| 206 |
sys_state.set_ready()
|
| 207 |
asyncio.create_task(auto_pilot_loop())
|
| 208 |
-
logger.info("✅ [System READY] All modules operational.")
|
| 209 |
yield
|
| 210 |
|
| 211 |
except Exception as e:
|
|
@@ -237,22 +261,10 @@ async def _analyze_symbol_task(symbol: str) -> Dict[str, Any]:
|
|
| 237 |
current_price = await data_manager.get_latest_price_async(symbol)
|
| 238 |
raw_data = {'symbol': symbol, 'ohlcv': ohlcv_data, 'current_price': current_price, 'timestamp': time.time()}
|
| 239 |
|
|
|
|
| 240 |
res = await ml_processor.process_compound_signal(raw_data)
|
| 241 |
if not res: return None
|
| 242 |
|
| 243 |
-
titan_s = res.get('titan_score', 0.5)
|
| 244 |
-
pattern_s = res.get('patterns_score', 0.5)
|
| 245 |
-
mc_light_s = res.get('mc_score', 0.5)
|
| 246 |
-
|
| 247 |
-
l2_base_score = (
|
| 248 |
-
(titan_s * SystemLimits.L2_WEIGHT_TITAN) +
|
| 249 |
-
(pattern_s * SystemLimits.L2_WEIGHT_PATTERNS) +
|
| 250 |
-
(mc_light_s * SystemLimits.L2_WEIGHT_MC)
|
| 251 |
-
)
|
| 252 |
-
|
| 253 |
-
res['enhanced_final_score'] = l2_base_score
|
| 254 |
-
res['l2_base_score'] = l2_base_score
|
| 255 |
-
|
| 256 |
return res
|
| 257 |
except Exception: return None
|
| 258 |
|
|
@@ -271,9 +283,10 @@ async def run_unified_cycle():
|
|
| 271 |
sys_state.set_cycle_start()
|
| 272 |
|
| 273 |
try:
|
| 274 |
-
# LAYER 0: Guardian
|
| 275 |
await trade_manager.sync_internal_state_with_r2()
|
| 276 |
|
|
|
|
| 277 |
if len(trade_manager.open_positions) > 0:
|
| 278 |
log_and_print(f"ℹ️ [Cycle] Active Positions: {len(trade_manager.open_positions)}")
|
| 279 |
for sym, tr in trade_manager.open_positions.items():
|
|
@@ -282,11 +295,14 @@ async def run_unified_cycle():
|
|
| 282 |
pnl = ((curr_p - entry_p)/entry_p)*100 if entry_p > 0 else 0
|
| 283 |
log_and_print(f" 🔒 {sym}: {pnl:+.2f}%")
|
| 284 |
|
| 285 |
-
# LAYER 1: Screening
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
| 287 |
candidates = await data_manager.layer1_rapid_screening()
|
| 288 |
if not candidates:
|
| 289 |
-
log_and_print("⚠️ No L1 candidates found.")
|
| 290 |
sys_state.set_cycle_end(logs=log_buffer.getvalue())
|
| 291 |
return
|
| 292 |
|
|
@@ -296,22 +312,24 @@ async def run_unified_cycle():
|
|
| 296 |
results = await asyncio.gather(*tasks)
|
| 297 |
valid_l2 = [res for res in results if res is not None]
|
| 298 |
|
| 299 |
-
|
|
|
|
| 300 |
|
| 301 |
if not semi_finalists:
|
| 302 |
log_and_print("⚠️ No valid L2 candidates.")
|
| 303 |
sys_state.set_cycle_end(logs=log_buffer.getvalue())
|
| 304 |
return
|
| 305 |
|
| 306 |
-
# LAYER 3: Deep Dive
|
| 307 |
-
log_and_print(f" [3/5] 📡 L3 Deep Dive (
|
| 308 |
|
| 309 |
final_candidates = []
|
| 310 |
|
| 311 |
for sig in semi_finalists:
|
| 312 |
symbol = sig['symbol']
|
| 313 |
-
l2_score = sig.get('
|
| 314 |
|
|
|
|
| 315 |
whale_points = 0.0
|
| 316 |
try:
|
| 317 |
if whale_monitor:
|
|
@@ -325,6 +343,7 @@ async def run_unified_cycle():
|
|
| 325 |
elif action == 'SELL': whale_points = -dynamic_impact
|
| 326 |
except Exception: pass
|
| 327 |
|
|
|
|
| 328 |
news_points = 0.0
|
| 329 |
try:
|
| 330 |
if news_fetcher and senti_analyzer:
|
|
@@ -336,6 +355,7 @@ async def run_unified_cycle():
|
|
| 336 |
news_points = compound_score * SystemLimits.L3_NEWS_IMPACT_MAX
|
| 337 |
except Exception: pass
|
| 338 |
|
|
|
|
| 339 |
mc_a_points = 0.0
|
| 340 |
try:
|
| 341 |
raw_mc_a = await ml_processor.run_advanced_monte_carlo(symbol, '1h')
|
|
@@ -356,8 +376,8 @@ async def run_unified_cycle():
|
|
| 356 |
|
| 357 |
approved_signals = []
|
| 358 |
|
| 359 |
-
header = (f"{'SYM':<9} | {'
|
| 360 |
-
f"{'WHALE':<6} | {'
|
| 361 |
log_and_print("-" * 110)
|
| 362 |
log_and_print(header)
|
| 363 |
log_and_print("-" * 110)
|
|
@@ -365,6 +385,7 @@ async def run_unified_cycle():
|
|
| 365 |
for sig in final_candidates:
|
| 366 |
symbol = sig['symbol']
|
| 367 |
|
|
|
|
| 368 |
decision = await ml_processor.consult_oracle(sig)
|
| 369 |
|
| 370 |
action = decision.get('action', 'WAIT')
|
|
@@ -377,21 +398,19 @@ async def run_unified_cycle():
|
|
| 377 |
sig.update(decision)
|
| 378 |
approved_signals.append(sig)
|
| 379 |
|
|
|
|
| 380 |
titan_d = sig.get('titan_score', 0.0)
|
| 381 |
-
mcl_d = sig.get('mc_score', 0.0)
|
| 382 |
patt_d = sig.get('patterns_score', 0.0)
|
| 383 |
whale_d = sig.get('whale_score', 0.0)
|
| 384 |
-
news_d = sig.get('news_score', 0.0)
|
| 385 |
mca_d = sig.get('mc_advanced_score', 0.0)
|
| 386 |
final_d = sig.get('final_total_score', 0.0)
|
| 387 |
|
| 388 |
log_and_print(
|
| 389 |
f"{symbol:<9} | "
|
|
|
|
| 390 |
f"{titan_d:.2f} | "
|
| 391 |
-
f"{mcl_d:.2f} | "
|
| 392 |
f"{patt_d:.2f} | "
|
| 393 |
f"{whale_d:+.2f} | "
|
| 394 |
-
f"{news_d:+.2f} | "
|
| 395 |
f"{mca_d:+.2f} | "
|
| 396 |
f"{final_d:.2f} | "
|
| 397 |
f"{oracle_conf:.2f} | "
|
|
@@ -425,32 +444,56 @@ async def run_unified_cycle():
|
|
| 425 |
# Handlers (Reset Logic & Training)
|
| 426 |
# ------------------------------------------------------------------------------
|
| 427 |
async def trigger_training_cycle():
|
|
|
|
| 428 |
if adaptive_hub:
|
| 429 |
status = adaptive_hub.get_status()
|
| 430 |
-
return f"🤖 Adaptive System
|
| 431 |
return "⚠️ System not ready."
|
| 432 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 433 |
async def manual_close_current_trade():
|
| 434 |
if not trade_manager.open_positions: return "⚠️ No trade."
|
| 435 |
symbol = list(trade_manager.open_positions.keys())[0]
|
| 436 |
await trade_manager.force_exit_by_manager(symbol, reason="MANUAL_UI")
|
| 437 |
return f"✅ Closed {symbol}."
|
| 438 |
|
| 439 |
-
# ✅ الدالة 1: تصفير السجل التاريخي فقط (مع الحفاظ على المال)
|
| 440 |
async def reset_history_handler():
|
| 441 |
if trade_manager.open_positions: return "⚠️ Close active trades first."
|
| 442 |
|
| 443 |
-
# نقرأ الحالة الحالية أولاً لنحافظ على المال
|
| 444 |
current_state = await r2.get_portfolio_state_async()
|
| 445 |
preserved_capital = current_state.get('current_capital_usd', INITIAL_CAPITAL)
|
| 446 |
|
| 447 |
-
# تصفير شامل (الذي يصفر كل شيء في r2)
|
| 448 |
await r2.reset_all_stats_async()
|
| 449 |
|
| 450 |
-
# استعادة رأس المال المحفوظ
|
| 451 |
if trade_manager and trade_manager.smart_portfolio:
|
| 452 |
sp = trade_manager.smart_portfolio
|
| 453 |
-
sp.state["current_capital"] = preserved_capital
|
| 454 |
sp.state["session_start_balance"] = preserved_capital
|
| 455 |
sp.state["allocated_capital_usd"] = 0.0
|
| 456 |
sp.state["daily_net_pnl"] = 0.0
|
|
@@ -459,13 +502,12 @@ async def reset_history_handler():
|
|
| 459 |
|
| 460 |
return f"✅ History Cleared. Capital Preserved at ${preserved_capital:.2f}"
|
| 461 |
|
| 462 |
-
# ✅ الدالة 2: تصفير رأس المال فقط (مع الحفاظ على السجل)
|
| 463 |
async def reset_capital_handler():
|
| 464 |
if trade_manager.open_positions: return "⚠️ Close active trades first."
|
| 465 |
|
| 466 |
if trade_manager and trade_manager.smart_portfolio:
|
| 467 |
sp = trade_manager.smart_portfolio
|
| 468 |
-
sp.state["current_capital"] = INITIAL_CAPITAL
|
| 469 |
sp.state["session_start_balance"] = INITIAL_CAPITAL
|
| 470 |
sp.state["allocated_capital_usd"] = 0.0
|
| 471 |
sp.state["daily_net_pnl"] = 0.0
|
|
@@ -484,7 +526,7 @@ async def run_cycle_from_gradio():
|
|
| 484 |
return "🚀 Launched."
|
| 485 |
|
| 486 |
# ------------------------------------------------------------------------------
|
| 487 |
-
# UI Updates
|
| 488 |
# ------------------------------------------------------------------------------
|
| 489 |
async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
| 490 |
empty_chart = go.Figure()
|
|
@@ -496,7 +538,7 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 496 |
|
| 497 |
try:
|
| 498 |
sp = trade_manager.smart_portfolio
|
| 499 |
-
equity = sp.state.get('current_capital', 10.0)
|
| 500 |
allocated = sp.state.get('allocated_capital_usd', 0.0)
|
| 501 |
free_cap = max(0.0, equity - allocated)
|
| 502 |
daily_pnl = sp.state.get('daily_net_pnl', 0.0)
|
|
@@ -504,7 +546,7 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 504 |
market_mood = sp.market_trend
|
| 505 |
fg_index = sp.fear_greed_index
|
| 506 |
|
| 507 |
-
#
|
| 508 |
symbol = None; entry_p = 0.0; tp_p = 0.0; sl_p = 0.0; curr_p = 0.0; pnl_pct = 0.0; pnl_val_unrealized = 0.0
|
| 509 |
active_trade_info = ""
|
| 510 |
trade_dur_str = "--:--:--"
|
|
@@ -522,7 +564,6 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 522 |
if curr_p > 0 and entry_p > 0:
|
| 523 |
pnl_pct = ((curr_p - entry_p) / entry_p) * 100
|
| 524 |
size = float(trade.get('entry_capital', 0.0))
|
| 525 |
-
# حساب القيمة العائمة (ربح/خسارة غير محققة)
|
| 526 |
pnl_val_unrealized = size * (pnl_pct / 100)
|
| 527 |
|
| 528 |
active_trade_info = f"""
|
|
@@ -534,16 +575,11 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 534 |
</div>
|
| 535 |
"""
|
| 536 |
|
| 537 |
-
# Virtual Equity = الرصيد المحقق + الربح/الخسارة العائمة
|
| 538 |
virtual_equity = equity + pnl_val_unrealized
|
| 539 |
-
|
| 540 |
-
# ✅ FIX: User requested ACTIVE TRADE PnL ONLY under the main Equity
|
| 541 |
-
# (Instead of Total Account PnL)
|
| 542 |
-
# If no trade active, this is 0.00
|
| 543 |
active_trade_pnl_val = pnl_val_unrealized
|
| 544 |
active_pnl_color = "#00ff00" if active_trade_pnl_val >= 0 else "#ff0000"
|
| 545 |
|
| 546 |
-
#
|
| 547 |
portfolio = await r2.get_portfolio_state_async()
|
| 548 |
total_t = portfolio.get('total_trades', 0)
|
| 549 |
wins = portfolio.get('winning_trades', 0)
|
|
@@ -556,6 +592,9 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 556 |
|
| 557 |
color = "#00ff00" if daily_pnl >= 0 else "#ff0000"
|
| 558 |
halt_status = "<span style='color:red; font-weight:bold;'>HALTED</span>" if is_halted else "<span style='color:#00ff00;'>ACTIVE</span>"
|
|
|
|
|
|
|
|
|
|
| 559 |
|
| 560 |
wallet_md = f"""
|
| 561 |
<div style='background-color: #1a1a1a; padding: 15px; border-radius: 8px; border: 1px solid #333; text-align:center;'>
|
|
@@ -574,6 +613,9 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 574 |
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc;'>
|
| 575 |
<span>🦅 Market:</span> <span style='color: white;'>{market_mood} ({fg_index})</span>
|
| 576 |
</div>
|
|
|
|
|
|
|
|
|
|
| 577 |
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc; margin-top:5px;'>
|
| 578 |
<span>🛡️ Status:</span> {halt_status}
|
| 579 |
</div>
|
|
@@ -650,7 +692,7 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 650 |
)
|
| 651 |
|
| 652 |
train_status = sys_state.training_status_msg
|
| 653 |
-
if sys_state.training_running: train_status = "
|
| 654 |
|
| 655 |
return (status_txt, status_line, fig, f"{curr_p:.6f}", f"{entry_p:.6f}", f"{tp_p:.6f}", f"{sl_p:.6f}",
|
| 656 |
f"{pnl_pct:+.2f}%", wl_df, wallet_md, history_md, train_status)
|
|
@@ -665,10 +707,10 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 665 |
def create_gradio_ui():
|
| 666 |
custom_css = ".gradio-container {background:#0b0f19} .dataframe {background:#1a1a1a!important} .html-box {min-height:180px}"
|
| 667 |
|
| 668 |
-
with gr.Blocks(title="Titan
|
| 669 |
gr.HTML(f"<style>{custom_css}</style>")
|
| 670 |
|
| 671 |
-
gr.Markdown("# 🚀 Titan
|
| 672 |
|
| 673 |
with gr.Row():
|
| 674 |
with gr.Column(scale=3):
|
|
@@ -701,20 +743,21 @@ def create_gradio_ui():
|
|
| 701 |
btn_run = gr.Button("🚀 Scan", variant="primary")
|
| 702 |
btn_close = gr.Button("🚨 Close", variant="stop")
|
| 703 |
with gr.Row():
|
| 704 |
-
btn_train = gr.Button("🤖
|
| 705 |
-
|
|
|
|
| 706 |
btn_history_reset = gr.Button("🗑️ Clear History", variant="secondary")
|
| 707 |
btn_cap_reset = gr.Button("💰 Reset Capital", variant="secondary")
|
| 708 |
|
| 709 |
status = gr.Markdown("Init...")
|
| 710 |
-
train_status = gr.Textbox(label="Adaptive
|
| 711 |
alert = gr.Textbox(label="Alerts", interactive=False)
|
| 712 |
|
| 713 |
with gr.Column(scale=3):
|
| 714 |
logs = gr.Textbox(label="Logs", lines=14, autoscroll=True, elem_classes="log-box", type="text")
|
| 715 |
gr.HTML("<style>.log-box textarea { font-family: 'Consolas', 'Monaco', monospace !important; font-size: 12px !important; white-space: pre !important; }</style>")
|
| 716 |
|
| 717 |
-
#
|
| 718 |
btn_run.click(fn=run_cycle_from_gradio, outputs=alert)
|
| 719 |
btn_close.click(fn=manual_close_current_trade, outputs=alert)
|
| 720 |
|
|
@@ -722,6 +765,8 @@ def create_gradio_ui():
|
|
| 722 |
btn_cap_reset.click(fn=reset_capital_handler, outputs=alert)
|
| 723 |
|
| 724 |
btn_train.click(fn=trigger_training_cycle, outputs=alert)
|
|
|
|
|
|
|
| 725 |
auto_pilot.change(fn=toggle_auto_pilot, inputs=auto_pilot, outputs=alert)
|
| 726 |
|
| 727 |
gr.Timer(3).tick(fn=check_live_pnl_and_status, inputs=stats_dd,
|
|
|
|
| 1 |
# ==============================================================================
|
| 2 |
+
# 🚀 app.py (V36.0 - GEM-Architect: The Cybernetic Host)
|
| 3 |
# ==============================================================================
|
| 4 |
|
| 5 |
import os
|
|
|
|
| 34 |
# Imports
|
| 35 |
# ------------------------------------------------------------------------------
|
| 36 |
try:
|
| 37 |
+
from r2 import R2Service, INITIAL_CAPITAL
|
| 38 |
from ml_engine.data_manager import DataManager
|
| 39 |
from ml_engine.processor import MLProcessor, SystemLimits
|
| 40 |
from whale_monitor.core import EnhancedWhaleMonitor
|
|
|
|
| 43 |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 44 |
from learning_hub.adaptive_hub import AdaptiveHub
|
| 45 |
from trade_manager import TradeManager
|
| 46 |
+
|
| 47 |
+
# محاولة استيراد محرك الباكتست (اختياري للتشغيل عبر الواجهة)
|
| 48 |
+
try:
|
| 49 |
+
from backtest_engine import run_strategic_optimization_task
|
| 50 |
+
BACKTEST_AVAILABLE = True
|
| 51 |
+
except ImportError:
|
| 52 |
+
BACKTEST_AVAILABLE = False
|
| 53 |
+
|
| 54 |
except ImportError as e:
|
| 55 |
logger.critical(f"❌ [FATAL ERROR] Failed to import core modules: {e}")
|
| 56 |
traceback.print_exc()
|
|
|
|
| 90 |
|
| 91 |
def set_ready(self):
|
| 92 |
self.ready = True
|
| 93 |
+
self.last_cycle_logs = "✅ System Ready. Cybernetic Loop ON."
|
| 94 |
logger.info("✅ System State set to READY.")
|
| 95 |
|
| 96 |
def set_cycle_start(self):
|
|
|
|
| 154 |
await asyncio.sleep(5)
|
| 155 |
if not sys_state.ready: continue
|
| 156 |
|
| 157 |
+
# تحديث حالة الـ Adaptive Hub في الواجهة كل دقيقة
|
| 158 |
if adaptive_hub and int(time.time()) % 60 == 0:
|
| 159 |
sys_state.training_status_msg = adaptive_hub.get_status()
|
| 160 |
|
| 161 |
+
# فحص الحراس (Watchdogs) للصفقات المفتوحة
|
| 162 |
if trade_manager and len(trade_manager.open_positions) > 0:
|
| 163 |
wd_status = await trade_manager.ensure_active_guardians()
|
| 164 |
if "No active" not in wd_status:
|
| 165 |
+
# تحديث السجلات بحالة الحارس فقط إذا لم تكن هناك دورة مسح نشطة
|
| 166 |
+
if not sys_state.cycle_running:
|
| 167 |
+
sys_state.last_cycle_logs = trade_manager.latest_guardian_log
|
| 168 |
continue
|
| 169 |
|
| 170 |
+
# تشغيل دورة المسح (Cycle) إذا كان الطيار الآلي مفعلاً
|
| 171 |
if sys_state.auto_pilot and not sys_state.cycle_running and not sys_state.training_running:
|
| 172 |
if sys_state.last_cycle_time:
|
| 173 |
elapsed = (datetime.now() - sys_state.last_cycle_time).total_seconds()
|
|
|
|
| 189 |
async def lifespan(app: FastAPI):
|
| 190 |
global r2, data_manager, ml_processor, adaptive_hub, trade_manager, whale_monitor, news_fetcher, senti_analyzer, sys_state
|
| 191 |
|
| 192 |
+
logger.info("\n🚀 [System] Startup Sequence (Titan V36.0 - Cybernetic)...")
|
| 193 |
try:
|
| 194 |
+
# 1. الخدمات الأساسية
|
| 195 |
r2 = R2Service()
|
| 196 |
data_manager = DataManager(contracts_db={}, whale_monitor=None, r2_service=r2)
|
| 197 |
await data_manager.initialize()
|
| 198 |
await data_manager.load_contracts_from_r2()
|
| 199 |
|
| 200 |
+
# 2. المراقبة والتحليل
|
| 201 |
whale_monitor = EnhancedWhaleMonitor(contracts_db=data_manager.get_contracts_db(), r2_service=r2)
|
| 202 |
rpc_mgr = AdaptiveRpcManager(data_manager.http_client)
|
| 203 |
whale_monitor.set_rpc_manager(rpc_mgr)
|
|
|
|
| 206 |
senti_analyzer = SentimentIntensityAnalyzer()
|
| 207 |
data_manager.whale_monitor = whale_monitor
|
| 208 |
|
| 209 |
+
# 3. العقل الاستراتيجي (Adaptive Hub)
|
| 210 |
+
# يتم تهيئته أولاً ليحقن الـ DNA في SystemLimits
|
| 211 |
adaptive_hub = AdaptiveHub(r2_service=r2)
|
| 212 |
await adaptive_hub.initialize()
|
| 213 |
|
| 214 |
+
# 4. المعالج العصبي (Processor)
|
| 215 |
+
# سيقرأ SystemLimits المحدثة من AdaptiveHub
|
| 216 |
ml_processor = MLProcessor(data_manager=data_manager)
|
| 217 |
await ml_processor.initialize()
|
| 218 |
|
| 219 |
+
# 5. مدير التنفيذ (Trade Manager)
|
| 220 |
trade_manager = TradeManager(r2_service=r2, data_manager=data_manager, processor=ml_processor)
|
| 221 |
+
|
| 222 |
+
# 🔥 الربط العصبي: حقن LearningHub داخل TradeManager
|
| 223 |
+
# هذا يغلق حلقة التعلم (Feedback Loop)
|
| 224 |
trade_manager.learning_hub = adaptive_hub
|
|
|
|
| 225 |
|
| 226 |
+
await trade_manager.initialize_sentry_exchanges()
|
| 227 |
await trade_manager.start_sentry_loops()
|
| 228 |
|
| 229 |
+
# 6. الجاهزية
|
| 230 |
sys_state.set_ready()
|
| 231 |
asyncio.create_task(auto_pilot_loop())
|
| 232 |
+
logger.info("✅ [System READY] All modules operational. Cybernetic Link Established.")
|
| 233 |
yield
|
| 234 |
|
| 235 |
except Exception as e:
|
|
|
|
| 261 |
current_price = await data_manager.get_latest_price_async(symbol)
|
| 262 |
raw_data = {'symbol': symbol, 'ohlcv': ohlcv_data, 'current_price': current_price, 'timestamp': time.time()}
|
| 263 |
|
| 264 |
+
# المعالجة (تستخدم الأوزان الديناميكية الحالية)
|
| 265 |
res = await ml_processor.process_compound_signal(raw_data)
|
| 266 |
if not res: return None
|
| 267 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
return res
|
| 269 |
except Exception: return None
|
| 270 |
|
|
|
|
| 283 |
sys_state.set_cycle_start()
|
| 284 |
|
| 285 |
try:
|
| 286 |
+
# LAYER 0: Guardian & Portfolio Check
|
| 287 |
await trade_manager.sync_internal_state_with_r2()
|
| 288 |
|
| 289 |
+
# عرض سريع للصفقات
|
| 290 |
if len(trade_manager.open_positions) > 0:
|
| 291 |
log_and_print(f"ℹ️ [Cycle] Active Positions: {len(trade_manager.open_positions)}")
|
| 292 |
for sym, tr in trade_manager.open_positions.items():
|
|
|
|
| 295 |
pnl = ((curr_p - entry_p)/entry_p)*100 if entry_p > 0 else 0
|
| 296 |
log_and_print(f" 🔒 {sym}: {pnl:+.2f}%")
|
| 297 |
|
| 298 |
+
# LAYER 1: Adaptive Screening
|
| 299 |
+
# يستخدم الآن النظام المتكيف (Bull/Bear/Range)
|
| 300 |
+
current_regime = getattr(SystemLimits, 'CURRENT_REGIME', 'UNKNOWN')
|
| 301 |
+
log_and_print(f" [1/5] 🔍 L1 Screening (Regime: {current_regime})...")
|
| 302 |
+
|
| 303 |
candidates = await data_manager.layer1_rapid_screening()
|
| 304 |
if not candidates:
|
| 305 |
+
log_and_print("⚠️ No L1 candidates found for current regime.")
|
| 306 |
sys_state.set_cycle_end(logs=log_buffer.getvalue())
|
| 307 |
return
|
| 308 |
|
|
|
|
| 312 |
results = await asyncio.gather(*tasks)
|
| 313 |
valid_l2 = [res for res in results if res is not None]
|
| 314 |
|
| 315 |
+
# ترتيب حسب النقاط النهائية (التي تم حسابها بالأوزان الديناميكية)
|
| 316 |
+
semi_finalists = sorted(valid_l2, key=lambda x: x.get('enhanced_final_score', 0.0), reverse=True)[:10]
|
| 317 |
|
| 318 |
if not semi_finalists:
|
| 319 |
log_and_print("⚠️ No valid L2 candidates.")
|
| 320 |
sys_state.set_cycle_end(logs=log_buffer.getvalue())
|
| 321 |
return
|
| 322 |
|
| 323 |
+
# LAYER 3: Deep Dive (Contextual)
|
| 324 |
+
log_and_print(f" [3/5] 📡 L3 Deep Dive (Whales & News) for TOP {len(semi_finalists)}...")
|
| 325 |
|
| 326 |
final_candidates = []
|
| 327 |
|
| 328 |
for sig in semi_finalists:
|
| 329 |
symbol = sig['symbol']
|
| 330 |
+
l2_score = sig.get('enhanced_final_score', 0.0)
|
| 331 |
|
| 332 |
+
# Whale Check
|
| 333 |
whale_points = 0.0
|
| 334 |
try:
|
| 335 |
if whale_monitor:
|
|
|
|
| 343 |
elif action == 'SELL': whale_points = -dynamic_impact
|
| 344 |
except Exception: pass
|
| 345 |
|
| 346 |
+
# News Check
|
| 347 |
news_points = 0.0
|
| 348 |
try:
|
| 349 |
if news_fetcher and senti_analyzer:
|
|
|
|
| 355 |
news_points = compound_score * SystemLimits.L3_NEWS_IMPACT_MAX
|
| 356 |
except Exception: pass
|
| 357 |
|
| 358 |
+
# MC Advanced
|
| 359 |
mc_a_points = 0.0
|
| 360 |
try:
|
| 361 |
raw_mc_a = await ml_processor.run_advanced_monte_carlo(symbol, '1h')
|
|
|
|
| 376 |
|
| 377 |
approved_signals = []
|
| 378 |
|
| 379 |
+
header = (f"{'SYM':<9} | {'L2(HYB)':<6} | {'TITAN':<5} | {'PATT':<5} | "
|
| 380 |
+
f"{'WHALE':<6} | {'MC(A)':<6} | {'FINAL':<6} | {'ORACLE':<6} | {'STATUS'}")
|
| 381 |
log_and_print("-" * 110)
|
| 382 |
log_and_print(header)
|
| 383 |
log_and_print("-" * 110)
|
|
|
|
| 385 |
for sig in final_candidates:
|
| 386 |
symbol = sig['symbol']
|
| 387 |
|
| 388 |
+
# Oracle Check (يستخدم العتبة الديناميكية)
|
| 389 |
decision = await ml_processor.consult_oracle(sig)
|
| 390 |
|
| 391 |
action = decision.get('action', 'WAIT')
|
|
|
|
| 398 |
sig.update(decision)
|
| 399 |
approved_signals.append(sig)
|
| 400 |
|
| 401 |
+
l2_hybrid = sig.get('enhanced_final_score', 0.0)
|
| 402 |
titan_d = sig.get('titan_score', 0.0)
|
|
|
|
| 403 |
patt_d = sig.get('patterns_score', 0.0)
|
| 404 |
whale_d = sig.get('whale_score', 0.0)
|
|
|
|
| 405 |
mca_d = sig.get('mc_advanced_score', 0.0)
|
| 406 |
final_d = sig.get('final_total_score', 0.0)
|
| 407 |
|
| 408 |
log_and_print(
|
| 409 |
f"{symbol:<9} | "
|
| 410 |
+
f"{l2_hybrid:.2f} | "
|
| 411 |
f"{titan_d:.2f} | "
|
|
|
|
| 412 |
f"{patt_d:.2f} | "
|
| 413 |
f"{whale_d:+.2f} | "
|
|
|
|
| 414 |
f"{mca_d:+.2f} | "
|
| 415 |
f"{final_d:.2f} | "
|
| 416 |
f"{oracle_conf:.2f} | "
|
|
|
|
| 444 |
# Handlers (Reset Logic & Training)
|
| 445 |
# ------------------------------------------------------------------------------
|
| 446 |
async def trigger_training_cycle():
|
| 447 |
+
"""عرض الحالة الحالية للأوزان والاستراتيجية"""
|
| 448 |
if adaptive_hub:
|
| 449 |
status = adaptive_hub.get_status()
|
| 450 |
+
return f"🤖 Adaptive System: {status}"
|
| 451 |
return "⚠️ System not ready."
|
| 452 |
|
| 453 |
+
async def trigger_strategic_backtest():
|
| 454 |
+
"""تشغيل الباكتست الاستراتيجي في الخلفية لتحديث الـ DNA"""
|
| 455 |
+
if not BACKTEST_AVAILABLE:
|
| 456 |
+
return "⚠️ Backtest Engine not found."
|
| 457 |
+
|
| 458 |
+
if sys_state.training_running:
|
| 459 |
+
return "⚠️ Training already in progress."
|
| 460 |
+
|
| 461 |
+
async def _run_bg_task():
|
| 462 |
+
sys_state.training_running = True
|
| 463 |
+
sys_state.training_status_msg = "🧪 Strategic Backtest Running..."
|
| 464 |
+
try:
|
| 465 |
+
logger.info("🧪 [Manual Trigger] Starting Strategic Backtest...")
|
| 466 |
+
await run_strategic_optimization_task()
|
| 467 |
+
# إعادة حقن الإعدادات الجديدة
|
| 468 |
+
if adaptive_hub:
|
| 469 |
+
await adaptive_hub.initialize()
|
| 470 |
+
logger.info("✅ [Manual Trigger] Backtest Complete. DNA Updated.")
|
| 471 |
+
except Exception as e:
|
| 472 |
+
logger.error(f"❌ Backtest Failed: {e}")
|
| 473 |
+
finally:
|
| 474 |
+
sys_state.training_running = False
|
| 475 |
+
sys_state.training_status_msg = adaptive_hub.get_status() if adaptive_hub else "Ready"
|
| 476 |
+
|
| 477 |
+
asyncio.create_task(_run_bg_task())
|
| 478 |
+
return "🧪 Strategic Backtest Started (Check Console)."
|
| 479 |
+
|
| 480 |
async def manual_close_current_trade():
|
| 481 |
if not trade_manager.open_positions: return "⚠️ No trade."
|
| 482 |
symbol = list(trade_manager.open_positions.keys())[0]
|
| 483 |
await trade_manager.force_exit_by_manager(symbol, reason="MANUAL_UI")
|
| 484 |
return f"✅ Closed {symbol}."
|
| 485 |
|
|
|
|
| 486 |
async def reset_history_handler():
|
| 487 |
if trade_manager.open_positions: return "⚠️ Close active trades first."
|
| 488 |
|
|
|
|
| 489 |
current_state = await r2.get_portfolio_state_async()
|
| 490 |
preserved_capital = current_state.get('current_capital_usd', INITIAL_CAPITAL)
|
| 491 |
|
|
|
|
| 492 |
await r2.reset_all_stats_async()
|
| 493 |
|
|
|
|
| 494 |
if trade_manager and trade_manager.smart_portfolio:
|
| 495 |
sp = trade_manager.smart_portfolio
|
| 496 |
+
sp.state["current_capital"] = preserved_capital
|
| 497 |
sp.state["session_start_balance"] = preserved_capital
|
| 498 |
sp.state["allocated_capital_usd"] = 0.0
|
| 499 |
sp.state["daily_net_pnl"] = 0.0
|
|
|
|
| 502 |
|
| 503 |
return f"✅ History Cleared. Capital Preserved at ${preserved_capital:.2f}"
|
| 504 |
|
|
|
|
| 505 |
async def reset_capital_handler():
|
| 506 |
if trade_manager.open_positions: return "⚠️ Close active trades first."
|
| 507 |
|
| 508 |
if trade_manager and trade_manager.smart_portfolio:
|
| 509 |
sp = trade_manager.smart_portfolio
|
| 510 |
+
sp.state["current_capital"] = INITIAL_CAPITAL
|
| 511 |
sp.state["session_start_balance"] = INITIAL_CAPITAL
|
| 512 |
sp.state["allocated_capital_usd"] = 0.0
|
| 513 |
sp.state["daily_net_pnl"] = 0.0
|
|
|
|
| 526 |
return "🚀 Launched."
|
| 527 |
|
| 528 |
# ------------------------------------------------------------------------------
|
| 529 |
+
# UI Updates
|
| 530 |
# ------------------------------------------------------------------------------
|
| 531 |
async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
| 532 |
empty_chart = go.Figure()
|
|
|
|
| 538 |
|
| 539 |
try:
|
| 540 |
sp = trade_manager.smart_portfolio
|
| 541 |
+
equity = sp.state.get('current_capital', 10.0)
|
| 542 |
allocated = sp.state.get('allocated_capital_usd', 0.0)
|
| 543 |
free_cap = max(0.0, equity - allocated)
|
| 544 |
daily_pnl = sp.state.get('daily_net_pnl', 0.0)
|
|
|
|
| 546 |
market_mood = sp.market_trend
|
| 547 |
fg_index = sp.fear_greed_index
|
| 548 |
|
| 549 |
+
# معلومات الصفقة النشطة
|
| 550 |
symbol = None; entry_p = 0.0; tp_p = 0.0; sl_p = 0.0; curr_p = 0.0; pnl_pct = 0.0; pnl_val_unrealized = 0.0
|
| 551 |
active_trade_info = ""
|
| 552 |
trade_dur_str = "--:--:--"
|
|
|
|
| 564 |
if curr_p > 0 and entry_p > 0:
|
| 565 |
pnl_pct = ((curr_p - entry_p) / entry_p) * 100
|
| 566 |
size = float(trade.get('entry_capital', 0.0))
|
|
|
|
| 567 |
pnl_val_unrealized = size * (pnl_pct / 100)
|
| 568 |
|
| 569 |
active_trade_info = f"""
|
|
|
|
| 575 |
</div>
|
| 576 |
"""
|
| 577 |
|
|
|
|
| 578 |
virtual_equity = equity + pnl_val_unrealized
|
|
|
|
|
|
|
|
|
|
|
|
|
| 579 |
active_trade_pnl_val = pnl_val_unrealized
|
| 580 |
active_pnl_color = "#00ff00" if active_trade_pnl_val >= 0 else "#ff0000"
|
| 581 |
|
| 582 |
+
# معلومات المحفظة
|
| 583 |
portfolio = await r2.get_portfolio_state_async()
|
| 584 |
total_t = portfolio.get('total_trades', 0)
|
| 585 |
wins = portfolio.get('winning_trades', 0)
|
|
|
|
| 592 |
|
| 593 |
color = "#00ff00" if daily_pnl >= 0 else "#ff0000"
|
| 594 |
halt_status = "<span style='color:red; font-weight:bold;'>HALTED</span>" if is_halted else "<span style='color:#00ff00;'>ACTIVE</span>"
|
| 595 |
+
|
| 596 |
+
# عرض الحالة الاستراتيجية الحالية
|
| 597 |
+
current_regime = getattr(SystemLimits, 'CURRENT_REGIME', 'N/A')
|
| 598 |
|
| 599 |
wallet_md = f"""
|
| 600 |
<div style='background-color: #1a1a1a; padding: 15px; border-radius: 8px; border: 1px solid #333; text-align:center;'>
|
|
|
|
| 613 |
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc;'>
|
| 614 |
<span>🦅 Market:</span> <span style='color: white;'>{market_mood} ({fg_index})</span>
|
| 615 |
</div>
|
| 616 |
+
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc; margin-top:3px;'>
|
| 617 |
+
<span>🧬 Regime:</span> <span style='color: #00e5ff; font-weight:bold;'>{current_regime}</span>
|
| 618 |
+
</div>
|
| 619 |
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc; margin-top:5px;'>
|
| 620 |
<span>🛡️ Status:</span> {halt_status}
|
| 621 |
</div>
|
|
|
|
| 692 |
)
|
| 693 |
|
| 694 |
train_status = sys_state.training_status_msg
|
| 695 |
+
if sys_state.training_running: train_status = "🧪 Backtest Running..."
|
| 696 |
|
| 697 |
return (status_txt, status_line, fig, f"{curr_p:.6f}", f"{entry_p:.6f}", f"{tp_p:.6f}", f"{sl_p:.6f}",
|
| 698 |
f"{pnl_pct:+.2f}%", wl_df, wallet_md, history_md, train_status)
|
|
|
|
| 707 |
def create_gradio_ui():
|
| 708 |
custom_css = ".gradio-container {background:#0b0f19} .dataframe {background:#1a1a1a!important} .html-box {min-height:180px}"
|
| 709 |
|
| 710 |
+
with gr.Blocks(title="Titan V36.0 (Cybernetic)", css=custom_css) as demo:
|
| 711 |
gr.HTML(f"<style>{custom_css}</style>")
|
| 712 |
|
| 713 |
+
gr.Markdown("# 🚀 Titan V36.0 (Cybernetic: Regime-Adaptive)")
|
| 714 |
|
| 715 |
with gr.Row():
|
| 716 |
with gr.Column(scale=3):
|
|
|
|
| 743 |
btn_run = gr.Button("🚀 Scan", variant="primary")
|
| 744 |
btn_close = gr.Button("🚨 Close", variant="stop")
|
| 745 |
with gr.Row():
|
| 746 |
+
btn_train = gr.Button("🤖 Status", variant="secondary")
|
| 747 |
+
btn_backtest = gr.Button("🧪 Run Strategic Backtest", variant="secondary")
|
| 748 |
+
with gr.Row():
|
| 749 |
btn_history_reset = gr.Button("🗑️ Clear History", variant="secondary")
|
| 750 |
btn_cap_reset = gr.Button("💰 Reset Capital", variant="secondary")
|
| 751 |
|
| 752 |
status = gr.Markdown("Init...")
|
| 753 |
+
train_status = gr.Textbox(label="Adaptive DNA Status", interactive=False, value="Active")
|
| 754 |
alert = gr.Textbox(label="Alerts", interactive=False)
|
| 755 |
|
| 756 |
with gr.Column(scale=3):
|
| 757 |
logs = gr.Textbox(label="Logs", lines=14, autoscroll=True, elem_classes="log-box", type="text")
|
| 758 |
gr.HTML("<style>.log-box textarea { font-family: 'Consolas', 'Monaco', monospace !important; font-size: 12px !important; white-space: pre !important; }</style>")
|
| 759 |
|
| 760 |
+
# Event Handlers
|
| 761 |
btn_run.click(fn=run_cycle_from_gradio, outputs=alert)
|
| 762 |
btn_close.click(fn=manual_close_current_trade, outputs=alert)
|
| 763 |
|
|
|
|
| 765 |
btn_cap_reset.click(fn=reset_capital_handler, outputs=alert)
|
| 766 |
|
| 767 |
btn_train.click(fn=trigger_training_cycle, outputs=alert)
|
| 768 |
+
btn_backtest.click(fn=trigger_strategic_backtest, outputs=alert) # زر الباكتست الجديد
|
| 769 |
+
|
| 770 |
auto_pilot.change(fn=toggle_auto_pilot, inputs=auto_pilot, outputs=alert)
|
| 771 |
|
| 772 |
gr.Timer(3).tick(fn=check_live_pnl_and_status, inputs=stats_dd,
|