Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# ==============================================================================
|
| 2 |
-
# 🚀 app.py (
|
| 3 |
# ==============================================================================
|
| 4 |
|
| 5 |
import os
|
|
@@ -190,7 +190,7 @@ async def auto_pilot_loop():
|
|
| 190 |
async def lifespan(app: FastAPI):
|
| 191 |
global r2, data_manager, ml_processor, adaptive_hub, trade_manager, whale_monitor, news_fetcher, senti_analyzer, sys_state, scheduler
|
| 192 |
|
| 193 |
-
logger.info("\n🚀 [System] Startup Sequence (Titan
|
| 194 |
try:
|
| 195 |
# 1. الخدمات الأساسية
|
| 196 |
r2 = R2Service()
|
|
@@ -438,7 +438,6 @@ async def run_unified_cycle():
|
|
| 438 |
# LAYER 4: Sniper & Governance & Execution
|
| 439 |
if approved_signals:
|
| 440 |
log_and_print("-" * 110)
|
| 441 |
-
# ✅ تحديث النص ليعكس وجود الحوكمة
|
| 442 |
log_and_print(f" [4/5] 🎯 L4 Sniper -> 🏛️ Governance -> 💰 Portfolio ({len(approved_signals)} candidates)...")
|
| 443 |
tm_log_buffer = StringIO()
|
| 444 |
|
|
@@ -529,6 +528,19 @@ async def reset_capital_handler():
|
|
| 529 |
await sp._save_state_to_r2()
|
| 530 |
return f"✅ Capital Reset to ${INITIAL_CAPITAL} (History Kept)"
|
| 531 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 532 |
async def toggle_auto_pilot(enable):
|
| 533 |
sys_state.auto_pilot = enable
|
| 534 |
return f"Auto-Pilot: {enable}"
|
|
@@ -539,15 +551,16 @@ async def run_cycle_from_gradio():
|
|
| 539 |
return "🚀 Launched."
|
| 540 |
|
| 541 |
# ------------------------------------------------------------------------------
|
| 542 |
-
# UI Updates (
|
| 543 |
# ------------------------------------------------------------------------------
|
| 544 |
async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
| 545 |
empty_chart = go.Figure()
|
| 546 |
empty_chart.update_layout(template="plotly_dark", paper_bgcolor="#0b0f19", plot_bgcolor="#0b0f19", xaxis={'visible':False}, yaxis={'visible':False})
|
| 547 |
wl_df_empty = pd.DataFrame(columns=["Coin", "Score"])
|
|
|
|
| 548 |
|
| 549 |
if not sys_state.ready:
|
| 550 |
-
return "Initializing...", "...", empty_chart, "0.0", "0.0", "0.0", "0.0", "0.0%", wl_df_empty, "Loading...", "Loading...", "Loading..."
|
| 551 |
|
| 552 |
try:
|
| 553 |
sp = trade_manager.smart_portfolio
|
|
@@ -591,7 +604,6 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 591 |
size = float(trade.get('entry_capital', 0.0))
|
| 592 |
pnl_val_unrealized = size * (pnl_pct / 100)
|
| 593 |
|
| 594 |
-
# عرض البيانات الجديدة في الواجهة
|
| 595 |
active_trade_info = f"""
|
| 596 |
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc; margin-top:5px; border-top: 1px solid #333; padding-top: 5px;'>
|
| 597 |
<span>⏱️ Time:</span> <span style='color: #ffff00;'>{trade_dur_str}</span>
|
|
@@ -654,6 +666,7 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 654 |
"Hydra: Stagnation (Time)": "stagnation"
|
| 655 |
}
|
| 656 |
target_key = key_map.get(selected_view, "hybrid")
|
|
|
|
| 657 |
stats_data = trade_manager.ai_stats.get(target_key, {"total":0, "good":0, "saved":0.0, "missed":0.0})
|
| 658 |
|
| 659 |
tot_ds = stats_data['total']
|
|
@@ -729,6 +742,22 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 729 |
</div>
|
| 730 |
</div>
|
| 731 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 732 |
|
| 733 |
wl_data = [[k, f"{v.get('final_total_score',0):.2f}"] for k, v in trade_manager.watchlist.items()]
|
| 734 |
wl_df = pd.DataFrame(wl_data, columns=["Coin", "Score"])
|
|
@@ -766,12 +795,13 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 766 |
train_status = sys_state.training_status_msg
|
| 767 |
if sys_state.training_running: train_status = "🧪 Backtest Running..."
|
| 768 |
|
|
|
|
| 769 |
return (status_txt, status_line, fig, f"{curr_p:.6f}", f"{entry_p:.6f}", f"{tp_p:.6f}", f"{sl_p:.6f}",
|
| 770 |
-
f"{pnl_pct:+.2f}%", wl_df, wallet_md, history_md, neural_md)
|
| 771 |
|
| 772 |
except Exception:
|
| 773 |
traceback.print_exc()
|
| 774 |
-
return "Error", "Error", empty_chart, "0", "0", "0", "0", "0%", wl_df_empty, "Err", "Err", "Err"
|
| 775 |
|
| 776 |
# ------------------------------------------------------------------------------
|
| 777 |
# Gradio UI Construction
|
|
@@ -779,10 +809,10 @@ async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
|
| 779 |
def create_gradio_ui():
|
| 780 |
custom_css = ".gradio-container {background:#0b0f19} .dataframe {background:#1a1a1a!important} .html-box {min-height:180px}"
|
| 781 |
|
| 782 |
-
with gr.Blocks(title="Titan
|
| 783 |
gr.HTML(f"<style>{custom_css}</style>")
|
| 784 |
|
| 785 |
-
gr.Markdown("# 🚀 Titan
|
| 786 |
|
| 787 |
with gr.Row():
|
| 788 |
with gr.Column(scale=3):
|
|
@@ -797,9 +827,23 @@ def create_gradio_ui():
|
|
| 797 |
|
| 798 |
with gr.Column(scale=1):
|
| 799 |
wallet_out = gr.HTML(label="Smart Wallet", elem_classes="html-box")
|
| 800 |
-
# 🔥 إضافة المخرج الجديد
|
| 801 |
neural_out = gr.HTML(label="Neural Cycles", elem_classes="html-box")
|
| 802 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 803 |
stats_dd = gr.Dropdown([
|
| 804 |
"Dual-Core (Hybrid)",
|
| 805 |
"Hydra: Crash (Panic)",
|
|
@@ -840,8 +884,12 @@ def create_gradio_ui():
|
|
| 840 |
btn_backtest.click(fn=trigger_strategic_backtest, outputs=alert)
|
| 841 |
auto_pilot.change(fn=toggle_auto_pilot, inputs=auto_pilot, outputs=alert)
|
| 842 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 843 |
gr.Timer(3).tick(fn=check_live_pnl_and_status, inputs=stats_dd,
|
| 844 |
-
outputs=[logs, status, live_chart, t_price, t_entry, t_tp, t_sl, t_pnl, watchlist_out, wallet_out, history_out, neural_out])
|
| 845 |
return demo
|
| 846 |
|
| 847 |
fast_api_server = FastAPI(lifespan=lifespan)
|
|
|
|
| 1 |
# ==============================================================================
|
| 2 |
+
# 🚀 app.py (V38.0 - GEM-Architect: Diagnostic Matrix Integration)
|
| 3 |
# ==============================================================================
|
| 4 |
|
| 5 |
import os
|
|
|
|
| 190 |
async def lifespan(app: FastAPI):
|
| 191 |
global r2, data_manager, ml_processor, adaptive_hub, trade_manager, whale_monitor, news_fetcher, senti_analyzer, sys_state, scheduler
|
| 192 |
|
| 193 |
+
logger.info("\n🚀 [System] Startup Sequence (Titan V38.0 - Diagnostics)...")
|
| 194 |
try:
|
| 195 |
# 1. الخدمات الأساسية
|
| 196 |
r2 = R2Service()
|
|
|
|
| 438 |
# LAYER 4: Sniper & Governance & Execution
|
| 439 |
if approved_signals:
|
| 440 |
log_and_print("-" * 110)
|
|
|
|
| 441 |
log_and_print(f" [4/5] 🎯 L4 Sniper -> 🏛️ Governance -> 💰 Portfolio ({len(approved_signals)} candidates)...")
|
| 442 |
tm_log_buffer = StringIO()
|
| 443 |
|
|
|
|
| 528 |
await sp._save_state_to_r2()
|
| 529 |
return f"✅ Capital Reset to ${INITIAL_CAPITAL} (History Kept)"
|
| 530 |
|
| 531 |
+
# 🔥 زر تصفير مصفوفة التشخيص
|
| 532 |
+
async def reset_diagnostics_handler():
|
| 533 |
+
await r2.reset_diagnostic_stats_async()
|
| 534 |
+
return "✅ Diagnostic Matrix Reset."
|
| 535 |
+
|
| 536 |
+
# 🔥 زر تصفير إحصائيات الحراس
|
| 537 |
+
async def reset_guardians_handler():
|
| 538 |
+
await r2.reset_guardian_stats_async()
|
| 539 |
+
# تحديث الذاكرة المحلية لمدير التجارة لتنعكس التغييرات فوراً
|
| 540 |
+
if trade_manager:
|
| 541 |
+
trade_manager.ai_stats = await r2.get_guardian_stats_async()
|
| 542 |
+
return "✅ Guardian Stats Reset."
|
| 543 |
+
|
| 544 |
async def toggle_auto_pilot(enable):
|
| 545 |
sys_state.auto_pilot = enable
|
| 546 |
return f"Auto-Pilot: {enable}"
|
|
|
|
| 551 |
return "🚀 Launched."
|
| 552 |
|
| 553 |
# ------------------------------------------------------------------------------
|
| 554 |
+
# UI Updates (Updated for Diagnostics)
|
| 555 |
# ------------------------------------------------------------------------------
|
| 556 |
async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
| 557 |
empty_chart = go.Figure()
|
| 558 |
empty_chart.update_layout(template="plotly_dark", paper_bgcolor="#0b0f19", plot_bgcolor="#0b0f19", xaxis={'visible':False}, yaxis={'visible':False})
|
| 559 |
wl_df_empty = pd.DataFrame(columns=["Coin", "Score"])
|
| 560 |
+
diag_df_empty = pd.DataFrame(columns=["Model", "Wins", "Losses", "PnL (USD)"])
|
| 561 |
|
| 562 |
if not sys_state.ready:
|
| 563 |
+
return "Initializing...", "...", empty_chart, "0.0", "0.0", "0.0", "0.0", "0.0%", wl_df_empty, diag_df_empty, "Loading...", "Loading...", "Loading..."
|
| 564 |
|
| 565 |
try:
|
| 566 |
sp = trade_manager.smart_portfolio
|
|
|
|
| 604 |
size = float(trade.get('entry_capital', 0.0))
|
| 605 |
pnl_val_unrealized = size * (pnl_pct / 100)
|
| 606 |
|
|
|
|
| 607 |
active_trade_info = f"""
|
| 608 |
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc; margin-top:5px; border-top: 1px solid #333; padding-top: 5px;'>
|
| 609 |
<span>⏱️ Time:</span> <span style='color: #ffff00;'>{trade_dur_str}</span>
|
|
|
|
| 666 |
"Hydra: Stagnation (Time)": "stagnation"
|
| 667 |
}
|
| 668 |
target_key = key_map.get(selected_view, "hybrid")
|
| 669 |
+
# استخدام النسخة الموجودة في TradeManager مباشرة لضمان الحداثة
|
| 670 |
stats_data = trade_manager.ai_stats.get(target_key, {"total":0, "good":0, "saved":0.0, "missed":0.0})
|
| 671 |
|
| 672 |
tot_ds = stats_data['total']
|
|
|
|
| 742 |
</div>
|
| 743 |
</div>
|
| 744 |
"""
|
| 745 |
+
|
| 746 |
+
# 🔥 جلب بيانات مصفوفة التشخيص (Diagnostic Matrix)
|
| 747 |
+
diag_data = await r2.get_diagnostic_stats_async()
|
| 748 |
+
diag_list = []
|
| 749 |
+
ordered_models = ["Titan", "Patterns", "Oracle", "Sniper", "MonteCarlo_L", "MonteCarlo_A", "Governance"]
|
| 750 |
+
|
| 751 |
+
for m in ordered_models:
|
| 752 |
+
stats = diag_data.get(m, {"wins": 0, "losses": 0, "pnl": 0.0})
|
| 753 |
+
diag_list.append([
|
| 754 |
+
m,
|
| 755 |
+
stats['wins'],
|
| 756 |
+
stats['losses'],
|
| 757 |
+
f"${stats['pnl']:.2f}"
|
| 758 |
+
])
|
| 759 |
+
|
| 760 |
+
diag_df = pd.DataFrame(diag_list, columns=["Model", "Wins", "Losses", "PnL (USD)"])
|
| 761 |
|
| 762 |
wl_data = [[k, f"{v.get('final_total_score',0):.2f}"] for k, v in trade_manager.watchlist.items()]
|
| 763 |
wl_df = pd.DataFrame(wl_data, columns=["Coin", "Score"])
|
|
|
|
| 795 |
train_status = sys_state.training_status_msg
|
| 796 |
if sys_state.training_running: train_status = "🧪 Backtest Running..."
|
| 797 |
|
| 798 |
+
# إضافة diag_df إلى مخرجات الدالة
|
| 799 |
return (status_txt, status_line, fig, f"{curr_p:.6f}", f"{entry_p:.6f}", f"{tp_p:.6f}", f"{sl_p:.6f}",
|
| 800 |
+
f"{pnl_pct:+.2f}%", wl_df, diag_df, wallet_md, history_md, neural_md)
|
| 801 |
|
| 802 |
except Exception:
|
| 803 |
traceback.print_exc()
|
| 804 |
+
return "Error", "Error", empty_chart, "0", "0", "0", "0", "0%", wl_df_empty, diag_df_empty, "Err", "Err", "Err"
|
| 805 |
|
| 806 |
# ------------------------------------------------------------------------------
|
| 807 |
# Gradio UI Construction
|
|
|
|
| 809 |
def create_gradio_ui():
|
| 810 |
custom_css = ".gradio-container {background:#0b0f19} .dataframe {background:#1a1a1a!important} .html-box {min-height:180px}"
|
| 811 |
|
| 812 |
+
with gr.Blocks(title="Titan V38.0 (Neural Dashboard)") as demo:
|
| 813 |
gr.HTML(f"<style>{custom_css}</style>")
|
| 814 |
|
| 815 |
+
gr.Markdown("# 🚀 Titan V38.0 (Cybernetic: Neural Dashboard)")
|
| 816 |
|
| 817 |
with gr.Row():
|
| 818 |
with gr.Column(scale=3):
|
|
|
|
| 827 |
|
| 828 |
with gr.Column(scale=1):
|
| 829 |
wallet_out = gr.HTML(label="Smart Wallet", elem_classes="html-box")
|
|
|
|
| 830 |
neural_out = gr.HTML(label="Neural Cycles", elem_classes="html-box")
|
| 831 |
|
| 832 |
+
# 🔥 إضافة مصفوفة التشخيص الجديدة
|
| 833 |
+
gr.Markdown("### 🕵️ Diagnostic Matrix")
|
| 834 |
+
diagnostic_out = gr.Dataframe(
|
| 835 |
+
headers=["Model", "Wins", "Losses", "PnL (USD)"],
|
| 836 |
+
datatype=["str", "number", "number", "str"],
|
| 837 |
+
interactive=False,
|
| 838 |
+
label="Model Performance"
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
with gr.Row():
|
| 842 |
+
btn_reset_diag = gr.Button("🧹 Reset Matrix", size="sm", variant="secondary")
|
| 843 |
+
btn_reset_guard = gr.Button("🛡️ Reset Guardians", size="sm", variant="secondary")
|
| 844 |
+
|
| 845 |
+
gr.HTML("<hr style='border-color:#444; margin: 10px 0;'>")
|
| 846 |
+
|
| 847 |
stats_dd = gr.Dropdown([
|
| 848 |
"Dual-Core (Hybrid)",
|
| 849 |
"Hydra: Crash (Panic)",
|
|
|
|
| 884 |
btn_backtest.click(fn=trigger_strategic_backtest, outputs=alert)
|
| 885 |
auto_pilot.change(fn=toggle_auto_pilot, inputs=auto_pilot, outputs=alert)
|
| 886 |
|
| 887 |
+
# ربط أزرار التصفير الجديدة
|
| 888 |
+
btn_reset_diag.click(fn=reset_diagnostics_handler, outputs=alert)
|
| 889 |
+
btn_reset_guard.click(fn=reset_guardians_handler, outputs=alert)
|
| 890 |
+
|
| 891 |
gr.Timer(3).tick(fn=check_live_pnl_and_status, inputs=stats_dd,
|
| 892 |
+
outputs=[logs, status, live_chart, t_price, t_entry, t_tp, t_sl, t_pnl, watchlist_out, diagnostic_out, wallet_out, history_out, neural_out])
|
| 893 |
return demo
|
| 894 |
|
| 895 |
fast_api_server = FastAPI(lifespan=lifespan)
|