Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,290 +1,814 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
-
#
|
| 4 |
|
|
|
|
|
|
|
|
|
|
| 5 |
import asyncio
|
| 6 |
-
import
|
| 7 |
-
import pandas as pd
|
| 8 |
-
import pandas_ta as ta
|
| 9 |
import time
|
| 10 |
-
import logging
|
| 11 |
-
import argparse
|
| 12 |
import json
|
|
|
|
| 13 |
from datetime import datetime, timedelta
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
from learning_hub.adaptive_hub import AdaptiveHub
|
| 20 |
-
from r2 import R2Service
|
| 21 |
-
|
| 22 |
-
# ============================================================
|
| 23 |
-
# 💎 THE GOLDEN LIST (52 Strategic Assets)
|
| 24 |
-
# ============================================================
|
| 25 |
-
STRATEGIC_COINS = [
|
| 26 |
-
'SOL/USDT', 'XRP/USDT', 'DOGE/USDT', 'ADA/USDT', 'AVAX/USDT', 'LINK/USDT',
|
| 27 |
-
'TON/USDT', 'INJ/USDT', 'APT/USDT', 'OP/USDT', 'ARB/USDT', 'SUI/USDT',
|
| 28 |
-
'SEI/USDT', 'MINA/USDT', 'MATIC/USDT', 'NEAR/USDT', 'RUNE/USDT', 'API3/USDT',
|
| 29 |
-
'FLOKI/USDT', 'BABYDOGE/USDT', 'SHIB/USDT', 'TRX/USDT', 'DOT/USDT', 'UNI/USDT',
|
| 30 |
-
'ONDO/USDT', 'SNX/USDT', 'HBAR/USDT', 'XLM/USDT', 'AGIX/USDT', 'IMX/USDT',
|
| 31 |
-
'LRC/USDT', 'KCS/USDT', 'ICP/USDT', 'SAND/USDT', 'AXS/USDT', 'APE/USDT',
|
| 32 |
-
'GMT/USDT', 'CHZ/USDT', 'CFX/USDT', 'LDO/USDT', 'FET/USDT', 'RPL/USDT',
|
| 33 |
-
'MNT/USDT', 'RAY/USDT', 'CAKE/USDT', 'SRM/USDT', 'PENDLE/USDT', 'ATOM/USDT'
|
| 34 |
-
]
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
logger = logging.getLogger("TitanCore")
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
#
|
| 40 |
-
#
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
try:
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
try:
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
current_dna = hub.strategies.get(detected_regime)
|
| 106 |
-
if not current_dna: return False
|
| 107 |
-
|
| 108 |
-
tuning_coins = STRATEGIC_COINS if use_fixed_list else ['DOGE/USDT']
|
| 109 |
-
logger.info(f" 🌌 Universe: {len(tuning_coins)} Strategic Assets.")
|
| 110 |
-
|
| 111 |
-
opt = HeavyDutyBacktester(dm, proc)
|
| 112 |
-
opt.TARGET_COINS = tuning_coins
|
| 113 |
-
|
| 114 |
-
base_filters = current_dna.base_filters
|
| 115 |
-
base_guards = current_dna.base_guards
|
| 116 |
-
scan_range = 0.03 if period_type == 'weekly' else 0.05
|
| 117 |
-
steps = 3
|
| 118 |
-
def create_micro_grid(center_val):
|
| 119 |
-
low = max(0.1, center_val - scan_range)
|
| 120 |
-
high = min(0.99, center_val + scan_range)
|
| 121 |
-
return np.linspace(low, high, steps)
|
| 122 |
-
|
| 123 |
-
opt.GRID_RANGES = {
|
| 124 |
-
'TITAN': create_micro_grid(current_dna.model_weights.get('titan', 0.3)),
|
| 125 |
-
'ORACLE': create_micro_grid(base_filters['l3_oracle_thresh']),
|
| 126 |
-
'SNIPER': create_micro_grid(base_filters['l4_sniper_thresh']),
|
| 127 |
-
'PATTERN': [0.1, 0.5], 'L1_SCORE': [10.0],
|
| 128 |
-
'HYDRA_CRASH': create_micro_grid(base_guards['hydra_crash']),
|
| 129 |
-
'HYDRA_GIVEBACK': create_micro_grid(base_guards['hydra_giveback']),
|
| 130 |
-
'LEGACY_V2': create_micro_grid(base_guards['legacy_v2']),
|
| 131 |
-
}
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
opt.set_date_range(start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d"))
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
|
|
|
|
|
|
| 139 |
|
| 140 |
-
if
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
except Exception as e:
|
| 154 |
-
logger.
|
| 155 |
-
|
| 156 |
finally:
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
await
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
try:
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
except Exception as e:
|
| 194 |
-
logger.error(f"⚠️ [Scheduler Loop Error] {e}")
|
| 195 |
-
|
| 196 |
-
async def _load_state(self):
|
| 197 |
-
try:
|
| 198 |
-
if self.trade_manager.r2:
|
| 199 |
-
data = await self.trade_manager.r2.get_file_async(self.state_file)
|
| 200 |
-
if data:
|
| 201 |
-
state = json.loads(data)
|
| 202 |
-
if state.get('last_weekly'):
|
| 203 |
-
self.last_weekly_run = datetime.fromisoformat(state['last_weekly'])
|
| 204 |
-
if state.get('last_monthly'):
|
| 205 |
-
self.last_monthly_run = datetime.fromisoformat(state['last_monthly'])
|
| 206 |
-
|
| 207 |
-
# استرجاع العدادات
|
| 208 |
-
self.weekly_count = state.get('weekly_count', 0)
|
| 209 |
-
self.monthly_count = state.get('monthly_count', 0)
|
| 210 |
-
|
| 211 |
-
logger.info(f" 🕰️ [Scheduler] State Restored (W:{self.weekly_count} | M:{self.monthly_count}).")
|
| 212 |
-
except Exception: pass
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
return (now - self.last_monthly_run).days >= 25
|
| 235 |
-
return False
|
| 236 |
-
|
| 237 |
-
async def _try_run(self, period_type):
|
| 238 |
-
if len(self.trade_manager.open_positions) > 0:
|
| 239 |
-
logger.warning(f"⏳ [Scheduler] Postponing {period_type} run: Active trades present.")
|
| 240 |
-
return
|
| 241 |
-
|
| 242 |
-
self.is_running = True
|
| 243 |
-
try:
|
| 244 |
-
# 1. Run Optimization (Isolated)
|
| 245 |
-
success = await run_surgical_tuning(period_type, use_fixed_list=True)
|
| 246 |
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
except Exception as e:
|
| 265 |
-
logger.error(f"❌
|
| 266 |
finally:
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
if __name__ == "__main__":
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
args = parser.parse_args()
|
| 290 |
-
asyncio.run(run_surgical_tuning(args.type, use_fixed_list=True))
|
|
|
|
| 1 |
+
# ==============================================================================
|
| 2 |
+
# 🚀 app.py (V36.3 - GEM-Architect: Neural Dashboard)
|
| 3 |
+
# ==============================================================================
|
| 4 |
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import traceback
|
| 8 |
import asyncio
|
| 9 |
+
import gc
|
|
|
|
|
|
|
| 10 |
import time
|
|
|
|
|
|
|
| 11 |
import json
|
| 12 |
+
import logging
|
| 13 |
from datetime import datetime, timedelta
|
| 14 |
+
from contextlib import asynccontextmanager, redirect_stdout, redirect_stderr
|
| 15 |
+
from io import StringIO
|
| 16 |
+
from typing import List, Dict, Any, Optional
|
| 17 |
|
| 18 |
+
from fastapi import FastAPI, HTTPException, BackgroundTasks
|
| 19 |
+
import gradio as gr
|
| 20 |
+
import pandas as pd
|
| 21 |
+
import plotly.graph_objects as go
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
# ------------------------------------------------------------------------------
|
| 24 |
+
# Logging Setup
|
| 25 |
+
# ------------------------------------------------------------------------------
|
| 26 |
+
logging.basicConfig(
|
| 27 |
+
level=logging.INFO,
|
| 28 |
+
format="[%(levelname)s] %(message)s",
|
| 29 |
+
handlers=[logging.StreamHandler(sys.stdout)]
|
| 30 |
+
)
|
| 31 |
logger = logging.getLogger("TitanCore")
|
| 32 |
|
| 33 |
+
# ------------------------------------------------------------------------------
|
| 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
|
| 41 |
+
from whale_monitor.rpc_manager import AdaptiveRpcManager
|
| 42 |
+
from sentiment_news import NewsFetcher
|
| 43 |
+
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 44 |
+
from learning_hub.adaptive_hub import AdaptiveHub
|
| 45 |
+
from trade_manager import TradeManager
|
| 46 |
+
from periodic_tuner import AutoTunerScheduler
|
| 47 |
+
|
| 48 |
+
# محاولة استيراد محرك الباكتست (اختياري للتشغيل عبر الواجهة)
|
| 49 |
try:
|
| 50 |
+
from backtest_engine import run_strategic_optimization_task
|
| 51 |
+
BACKTEST_AVAILABLE = True
|
| 52 |
+
except ImportError:
|
| 53 |
+
BACKTEST_AVAILABLE = False
|
| 54 |
+
|
| 55 |
+
except ImportError as e:
|
| 56 |
+
logger.critical(f"❌ [FATAL ERROR] Failed to import core modules: {e}")
|
| 57 |
+
traceback.print_exc()
|
| 58 |
+
sys.exit(1)
|
| 59 |
+
|
| 60 |
+
# ------------------------------------------------------------------------------
|
| 61 |
+
# Global Context
|
| 62 |
+
# ------------------------------------------------------------------------------
|
| 63 |
+
r2: R2Service = None
|
| 64 |
+
data_manager: DataManager = None
|
| 65 |
+
ml_processor: MLProcessor = None
|
| 66 |
+
adaptive_hub: AdaptiveHub = None
|
| 67 |
+
trade_manager: TradeManager = None
|
| 68 |
+
whale_monitor: EnhancedWhaleMonitor = None
|
| 69 |
+
news_fetcher: NewsFetcher = None
|
| 70 |
+
senti_analyzer: SentimentIntensityAnalyzer = None
|
| 71 |
+
sys_state: 'SystemState' = None
|
| 72 |
+
scheduler: AutoTunerScheduler = None
|
| 73 |
+
|
| 74 |
+
# ------------------------------------------------------------------------------
|
| 75 |
+
# State Management
|
| 76 |
+
# ------------------------------------------------------------------------------
|
| 77 |
+
class SystemState:
|
| 78 |
+
def __init__(self):
|
| 79 |
+
self.ready = False
|
| 80 |
+
self.cycle_running = False
|
| 81 |
+
self.training_running = False
|
| 82 |
+
self.auto_pilot = True
|
| 83 |
+
|
| 84 |
+
self.last_cycle_time: datetime = None
|
| 85 |
+
self.last_cycle_error = None
|
| 86 |
+
self.app_start_time = datetime.now()
|
| 87 |
+
|
| 88 |
+
self.last_cycle_logs = "System Initializing..."
|
| 89 |
+
self.training_status_msg = "Adaptive Mode: Active"
|
| 90 |
+
|
| 91 |
+
self.scan_interval = 60
|
| 92 |
+
|
| 93 |
+
def set_ready(self):
|
| 94 |
+
self.ready = True
|
| 95 |
+
self.last_cycle_logs = "✅ System Ready. Cybernetic Loop ON."
|
| 96 |
+
logger.info("✅ System State set to READY.")
|
| 97 |
+
|
| 98 |
+
def set_cycle_start(self):
|
| 99 |
+
self.cycle_running = True
|
| 100 |
+
self.last_cycle_logs = "🌀 [Cycle START] Scanning Markets..."
|
| 101 |
+
logger.info("🌀 Cycle STARTED.")
|
| 102 |
+
|
| 103 |
+
def set_cycle_end(self, error=None, logs=None):
|
| 104 |
+
self.cycle_running = False
|
| 105 |
+
self.last_cycle_time = datetime.now()
|
| 106 |
+
self.last_cycle_error = str(error) if error else None
|
| 107 |
+
|
| 108 |
+
if logs:
|
| 109 |
+
self.last_cycle_logs = logs
|
| 110 |
+
elif error:
|
| 111 |
+
self.last_cycle_logs = f"❌ [Cycle ERROR] {error}"
|
| 112 |
+
logger.error(f"Cycle Error: {error}")
|
| 113 |
+
else:
|
| 114 |
+
self.last_cycle_logs = f"✅ [Cycle END] Finished successfully."
|
| 115 |
+
logger.info("✅ Cycle ENDED.")
|
| 116 |
+
|
| 117 |
+
sys_state = SystemState()
|
| 118 |
+
|
| 119 |
+
# ------------------------------------------------------------------------------
|
| 120 |
+
# Utilities
|
| 121 |
+
# ------------------------------------------------------------------------------
|
| 122 |
+
def format_crypto_price(price):
|
| 123 |
+
if price is None: return "0.0"
|
| 124 |
try:
|
| 125 |
+
p = float(price)
|
| 126 |
+
if p == 0: return "0.0"
|
| 127 |
+
return "{:.8f}".format(p).rstrip('0').rstrip('.')
|
| 128 |
+
except: return str(price)
|
| 129 |
+
|
| 130 |
+
def calculate_duration_str(timestamp_str):
|
| 131 |
+
if not timestamp_str: return "--:--:--"
|
| 132 |
+
try:
|
| 133 |
+
if isinstance(timestamp_str, str):
|
| 134 |
+
start_time = datetime.fromisoformat(timestamp_str)
|
| 135 |
+
else: start_time = timestamp_str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
+
diff = datetime.now() - start_time
|
| 138 |
+
total_seconds = int(diff.total_seconds())
|
|
|
|
| 139 |
|
| 140 |
+
days = total_seconds // 86400
|
| 141 |
+
hours = (total_seconds % 86400) // 3600
|
| 142 |
+
minutes = (total_seconds % 3600) // 60
|
| 143 |
+
seconds = total_seconds % 60
|
| 144 |
|
| 145 |
+
if days > 0: return f"{days}d {hours:02}:{minutes:02}:{seconds:02}"
|
| 146 |
+
return f"{hours:02}:{minutes:02}:{seconds:02}"
|
| 147 |
+
except: return "--:--:--"
|
| 148 |
+
|
| 149 |
+
# ------------------------------------------------------------------------------
|
| 150 |
+
# Auto-Pilot Daemon
|
| 151 |
+
# ------------------------------------------------------------------------------
|
| 152 |
+
async def auto_pilot_loop():
|
| 153 |
+
logger.info("🤖 [Auto-Pilot] Daemon started.")
|
| 154 |
+
while True:
|
| 155 |
+
try:
|
| 156 |
+
await asyncio.sleep(5)
|
| 157 |
+
if not sys_state.ready: continue
|
| 158 |
|
| 159 |
+
# تحديث حالة الـ Adaptive Hub في الواجهة كل دقيقة
|
| 160 |
+
if adaptive_hub and int(time.time()) % 60 == 0:
|
| 161 |
+
sys_state.training_status_msg = adaptive_hub.get_status()
|
| 162 |
+
|
| 163 |
+
# فحص الحراس (Watchdogs) للصفقات المفتوحة
|
| 164 |
+
if trade_manager and len(trade_manager.open_positions) > 0:
|
| 165 |
+
wd_status = await trade_manager.ensure_active_guardians()
|
| 166 |
+
if "No active" not in wd_status:
|
| 167 |
+
if not sys_state.cycle_running:
|
| 168 |
+
sys_state.last_cycle_logs = trade_manager.latest_guardian_log
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
# تشغيل دورة المسح (Cycle) إذا كان الطيار الآلي مفعلاً
|
| 172 |
+
if sys_state.auto_pilot and not sys_state.cycle_running and not sys_state.training_running:
|
| 173 |
+
if sys_state.last_cycle_time:
|
| 174 |
+
elapsed = (datetime.now() - sys_state.last_cycle_time).total_seconds()
|
| 175 |
+
if elapsed < sys_state.scan_interval:
|
| 176 |
+
continue
|
| 177 |
+
|
| 178 |
+
logger.info("🤖 [Auto-Pilot] Triggering scan...")
|
| 179 |
+
asyncio.create_task(run_unified_cycle())
|
| 180 |
+
await asyncio.sleep(5)
|
| 181 |
+
|
| 182 |
+
except Exception as e:
|
| 183 |
+
logger.error(f"⚠️ [Auto-Pilot Error] {e}")
|
| 184 |
+
await asyncio.sleep(30)
|
| 185 |
+
|
| 186 |
+
# ------------------------------------------------------------------------------
|
| 187 |
+
# Lifespan
|
| 188 |
+
# ------------------------------------------------------------------------------
|
| 189 |
+
@asynccontextmanager
|
| 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 V36.3 - Neural Dashboard)...")
|
| 194 |
+
try:
|
| 195 |
+
# 1. الخدمات الأساسية
|
| 196 |
+
r2 = R2Service()
|
| 197 |
+
data_manager = DataManager(contracts_db={}, whale_monitor=None, r2_service=r2)
|
| 198 |
+
await data_manager.initialize()
|
| 199 |
+
await data_manager.load_contracts_from_r2()
|
| 200 |
+
|
| 201 |
+
# 2. المراقبة والتحليل
|
| 202 |
+
whale_monitor = EnhancedWhaleMonitor(contracts_db=data_manager.get_contracts_db(), r2_service=r2)
|
| 203 |
+
rpc_mgr = AdaptiveRpcManager(data_manager.http_client)
|
| 204 |
+
whale_monitor.set_rpc_manager(rpc_mgr)
|
| 205 |
+
|
| 206 |
+
news_fetcher = NewsFetcher()
|
| 207 |
+
senti_analyzer = SentimentIntensityAnalyzer()
|
| 208 |
+
data_manager.whale_monitor = whale_monitor
|
| 209 |
+
|
| 210 |
+
# 3. العقل الاستراتيجي (Adaptive Hub)
|
| 211 |
+
adaptive_hub = AdaptiveHub(r2_service=r2)
|
| 212 |
+
await adaptive_hub.initialize()
|
| 213 |
+
|
| 214 |
+
# 4. المعالج العصبي (Processor)
|
| 215 |
+
ml_processor = MLProcessor(data_manager=data_manager)
|
| 216 |
+
await ml_processor.initialize()
|
| 217 |
+
|
| 218 |
+
# 5. مدير التنفيذ (Trade Manager)
|
| 219 |
+
trade_manager = TradeManager(r2_service=r2, data_manager=data_manager, processor=ml_processor)
|
| 220 |
+
trade_manager.learning_hub = adaptive_hub
|
| 221 |
+
|
| 222 |
+
await trade_manager.initialize_sentry_exchanges()
|
| 223 |
+
await trade_manager.start_sentry_loops()
|
| 224 |
+
|
| 225 |
+
# 6. المجدول التلقائي (Auto-Tuner Scheduler)
|
| 226 |
+
scheduler = AutoTunerScheduler(trade_manager)
|
| 227 |
+
asyncio.create_task(scheduler.start_loop())
|
| 228 |
+
logger.info("🕰️ [Scheduler] Auto-Tuner Background Task Started.")
|
| 229 |
+
|
| 230 |
+
# 7. الجاهزية
|
| 231 |
+
sys_state.set_ready()
|
| 232 |
+
asyncio.create_task(auto_pilot_loop())
|
| 233 |
+
logger.info("✅ [System READY] All modules operational. Cybernetic Link Established.")
|
| 234 |
+
yield
|
| 235 |
|
| 236 |
except Exception as e:
|
| 237 |
+
logger.critical(f"❌ [FATAL STARTUP ERROR] {e}")
|
| 238 |
+
traceback.print_exc()
|
| 239 |
finally:
|
| 240 |
+
sys_state.ready = False
|
| 241 |
+
if trade_manager: await trade_manager.stop_sentry_loops()
|
| 242 |
+
if data_manager: await data_manager.close()
|
| 243 |
+
if whale_monitor and whale_monitor.rpc_manager: await whale_monitor.rpc_manager.close()
|
| 244 |
+
logger.info("✅ [System] Shutdown Complete.")
|
| 245 |
+
|
| 246 |
+
# ------------------------------------------------------------------------------
|
| 247 |
+
# Helper Tasks
|
| 248 |
+
# ------------------------------------------------------------------------------
|
| 249 |
+
async def _analyze_symbol_task(symbol: str) -> Dict[str, Any]:
|
| 250 |
+
try:
|
| 251 |
+
required_tfs = ["5m", "15m", "1h", "4h"]
|
| 252 |
+
data_tasks = [data_manager.get_latest_ohlcv(symbol, tf, limit=300) for tf in required_tfs]
|
| 253 |
+
all_data = await asyncio.gather(*data_tasks)
|
| 254 |
+
|
| 255 |
+
ohlcv_data = {}
|
| 256 |
+
for tf, data in zip(required_tfs, all_data):
|
| 257 |
+
if data and len(data) > 0: ohlcv_data[tf] = data
|
| 258 |
+
|
| 259 |
+
if '1h' not in ohlcv_data or '5m' not in ohlcv_data:
|
| 260 |
+
return None
|
| 261 |
+
|
| 262 |
+
current_price = await data_manager.get_latest_price_async(symbol)
|
| 263 |
+
raw_data = {'symbol': symbol, 'ohlcv': ohlcv_data, 'current_price': current_price, 'timestamp': time.time()}
|
| 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 |
+
|
| 271 |
+
# ------------------------------------------------------------------------------
|
| 272 |
+
# Unified Cycle
|
| 273 |
+
# ------------------------------------------------------------------------------
|
| 274 |
+
async def run_unified_cycle():
|
| 275 |
+
log_buffer = StringIO()
|
| 276 |
+
def log_and_print(message):
|
| 277 |
+
logger.info(message)
|
| 278 |
+
log_buffer.write(message + '\n')
|
| 279 |
+
|
| 280 |
+
if sys_state.cycle_running or sys_state.training_running: return
|
| 281 |
+
if not sys_state.ready: return
|
| 282 |
+
|
| 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 |
+
if len(trade_manager.open_positions) > 0:
|
| 290 |
+
log_and_print(f"ℹ️ [Cycle] Active Positions: {len(trade_manager.open_positions)}")
|
| 291 |
+
for sym, tr in trade_manager.open_positions.items():
|
| 292 |
+
curr_p = await data_manager.get_latest_price_async(sym)
|
| 293 |
+
entry_p = float(tr.get('entry_price', 0))
|
| 294 |
+
pnl = ((curr_p - entry_p)/entry_p)*100 if entry_p > 0 else 0
|
| 295 |
+
log_and_print(f" 🔒 {sym}: {pnl:+.2f}%")
|
| 296 |
+
|
| 297 |
+
# LAYER 1: Adaptive Screening
|
| 298 |
+
current_regime = getattr(SystemLimits, 'CURRENT_REGIME', 'UNKNOWN')
|
| 299 |
+
log_and_print(f" [1/5] 🔍 L1 Screening (Regime: {current_regime})...")
|
| 300 |
+
|
| 301 |
+
candidates = await data_manager.layer1_rapid_screening()
|
| 302 |
+
if not candidates:
|
| 303 |
+
log_and_print("⚠️ No L1 candidates found for current regime.")
|
| 304 |
+
sys_state.set_cycle_end(logs=log_buffer.getvalue())
|
| 305 |
+
return
|
| 306 |
+
|
| 307 |
+
# LAYER 2: Deep Analysis
|
| 308 |
+
log_and_print(f" [2/5] 🧠 L2 Deep Analysis ({len(candidates)} items)...")
|
| 309 |
+
tasks = [_analyze_symbol_task(c['symbol']) for c in candidates]
|
| 310 |
+
results = await asyncio.gather(*tasks)
|
| 311 |
+
valid_l2 = [res for res in results if res is not None]
|
| 312 |
+
|
| 313 |
+
semi_finalists = sorted(valid_l2, key=lambda x: x.get('enhanced_final_score', 0.0), reverse=True)[:10]
|
| 314 |
+
|
| 315 |
+
if not semi_finalists:
|
| 316 |
+
log_and_print("⚠️ No valid L2 candidates.")
|
| 317 |
+
sys_state.set_cycle_end(logs=log_buffer.getvalue())
|
| 318 |
+
return
|
| 319 |
+
|
| 320 |
+
# LAYER 3: Deep Dive (Contextual)
|
| 321 |
+
log_and_print(f" [3/5] 📡 L3 Deep Dive (Whales & News) for TOP {len(semi_finalists)}...")
|
| 322 |
+
|
| 323 |
+
final_candidates = []
|
| 324 |
+
|
| 325 |
+
for sig in semi_finalists:
|
| 326 |
+
symbol = sig['symbol']
|
| 327 |
+
l2_score = sig.get('enhanced_final_score', 0.0)
|
| 328 |
+
|
| 329 |
+
# Whale Check
|
| 330 |
+
whale_points = 0.0
|
| 331 |
try:
|
| 332 |
+
if whale_monitor:
|
| 333 |
+
w_data = await whale_monitor.get_symbol_whale_activity(symbol, known_price=sig.get('current_price', 0))
|
| 334 |
+
if w_data and w_data.get('data_available', False) and 'trading_signal' in w_data:
|
| 335 |
+
signal = w_data['trading_signal']
|
| 336 |
+
action = signal.get('action', 'HOLD')
|
| 337 |
+
confidence = float(signal.get('confidence', 0.5))
|
| 338 |
+
dynamic_impact = SystemLimits.L3_WHALE_IMPACT_MAX * confidence
|
| 339 |
+
if action == 'BUY': whale_points = dynamic_impact
|
| 340 |
+
elif action == 'SELL': whale_points = -dynamic_impact
|
| 341 |
+
except Exception: pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
|
| 343 |
+
# News Check
|
| 344 |
+
news_points = 0.0
|
| 345 |
+
try:
|
| 346 |
+
if news_fetcher and senti_analyzer:
|
| 347 |
+
n_data = await news_fetcher.get_news(symbol)
|
| 348 |
+
summary_text = n_data.get('summary', '')
|
| 349 |
+
if "No specific news" not in summary_text:
|
| 350 |
+
sent = senti_analyzer.polarity_scores(summary_text)
|
| 351 |
+
compound_score = sent['compound']
|
| 352 |
+
news_points = compound_score * SystemLimits.L3_NEWS_IMPACT_MAX
|
| 353 |
+
except Exception: pass
|
| 354 |
+
|
| 355 |
+
# MC Advanced
|
| 356 |
+
mc_a_points = 0.0
|
| 357 |
+
try:
|
| 358 |
+
raw_mc_a = await ml_processor.run_advanced_monte_carlo(symbol, '1h')
|
| 359 |
+
mc_a_points = max(-SystemLimits.L3_MC_ADVANCED_MAX, min(SystemLimits.L3_MC_ADVANCED_MAX, raw_mc_a))
|
| 360 |
+
except Exception: pass
|
| 361 |
+
|
| 362 |
+
final_score = l2_score + whale_points + news_points + mc_a_points
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
+
sig['whale_score'] = whale_points
|
| 365 |
+
sig['news_score'] = news_points
|
| 366 |
+
sig['mc_advanced_score'] = mc_a_points
|
| 367 |
+
sig['final_total_score'] = final_score
|
| 368 |
+
|
| 369 |
+
final_candidates.append(sig)
|
| 370 |
+
|
| 371 |
+
# RE-RANKING
|
| 372 |
+
final_candidates.sort(key=lambda x: x['final_total_score'], reverse=True)
|
| 373 |
+
|
| 374 |
+
approved_signals = []
|
| 375 |
+
|
| 376 |
+
header = (f"{'SYM':<9} | {'L2(HYB)':<6} | {'TITAN':<5} | {'PATT':<5} | "
|
| 377 |
+
f"{'WHALE':<6} | {'MC(A)':<6} | {'FINAL':<6} | {'ORACLE':<6} | {'STATUS'}")
|
| 378 |
+
log_and_print("-" * 110)
|
| 379 |
+
log_and_print(header)
|
| 380 |
+
log_and_print("-" * 110)
|
| 381 |
+
|
| 382 |
+
for sig in final_candidates:
|
| 383 |
+
symbol = sig['symbol']
|
| 384 |
+
|
| 385 |
+
decision = await ml_processor.consult_oracle(sig)
|
| 386 |
+
|
| 387 |
+
action = decision.get('action', 'WAIT')
|
| 388 |
+
oracle_conf = decision.get('confidence', 0.0)
|
| 389 |
+
target_class = decision.get('target_class', '')
|
| 390 |
|
| 391 |
+
status_str = "WAIT 🔴"
|
| 392 |
+
if action == 'WATCH' or action == 'BUY':
|
| 393 |
+
status_str = f"✅ {target_class}"
|
| 394 |
+
sig.update(decision)
|
| 395 |
+
approved_signals.append(sig)
|
| 396 |
+
|
| 397 |
+
l2_hybrid = sig.get('enhanced_final_score', 0.0)
|
| 398 |
+
titan_d = sig.get('titan_score', 0.0)
|
| 399 |
+
patt_d = sig.get('patterns_score', 0.0)
|
| 400 |
+
whale_d = sig.get('whale_score', 0.0)
|
| 401 |
+
mca_d = sig.get('mc_advanced_score', 0.0)
|
| 402 |
+
final_d = sig.get('final_total_score', 0.0)
|
| 403 |
+
|
| 404 |
+
log_and_print(
|
| 405 |
+
f"{symbol:<9} | "
|
| 406 |
+
f"{l2_hybrid:.2f} | "
|
| 407 |
+
f"{titan_d:.2f} | "
|
| 408 |
+
f"{patt_d:.2f} | "
|
| 409 |
+
f"{whale_d:+.2f} | "
|
| 410 |
+
f"{mca_d:+.2f} | "
|
| 411 |
+
f"{final_d:.2f} | "
|
| 412 |
+
f"{oracle_conf:.2f} | "
|
| 413 |
+
f"{status_str}"
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
# LAYER 4: Sniper Execution
|
| 417 |
+
if approved_signals:
|
| 418 |
+
log_and_print("-" * 110)
|
| 419 |
+
log_and_print(f" [4/5] 🎯 L4 Sniper & Portfolio Check ({len(approved_signals)} candidates)...")
|
| 420 |
+
tm_log_buffer = StringIO()
|
| 421 |
+
|
| 422 |
+
with redirect_stdout(tm_log_buffer), redirect_stderr(tm_log_buffer):
|
| 423 |
+
await trade_manager.select_and_execute_best_signal(approved_signals)
|
| 424 |
+
|
| 425 |
+
tm_logs = tm_log_buffer.getvalue()
|
| 426 |
+
for line in tm_logs.splitlines():
|
| 427 |
+
if line.strip(): log_and_print(line.strip())
|
| 428 |
+
else:
|
| 429 |
+
log_and_print(" -> 🛑 No candidates approved by Oracle for Sniper check.")
|
| 430 |
+
|
| 431 |
+
gc.collect()
|
| 432 |
+
sys_state.set_cycle_end(logs=log_buffer.getvalue())
|
| 433 |
+
|
| 434 |
+
except Exception as e:
|
| 435 |
+
logger.error(f"❌ [Cycle ERROR] {e}")
|
| 436 |
+
traceback.print_exc()
|
| 437 |
+
sys_state.set_cycle_end(error=e, logs=log_buffer.getvalue())
|
| 438 |
+
|
| 439 |
+
# ------------------------------------------------------------------------------
|
| 440 |
+
# Handlers
|
| 441 |
+
# ------------------------------------------------------------------------------
|
| 442 |
+
async def trigger_training_cycle():
|
| 443 |
+
if adaptive_hub:
|
| 444 |
+
status = adaptive_hub.get_status()
|
| 445 |
+
return f"🤖 Adaptive System: {status}"
|
| 446 |
+
return "⚠️ System not ready."
|
| 447 |
+
|
| 448 |
+
async def trigger_strategic_backtest():
|
| 449 |
+
if not BACKTEST_AVAILABLE:
|
| 450 |
+
return "⚠️ Backtest Engine not found."
|
| 451 |
+
|
| 452 |
+
if trade_manager and len(trade_manager.open_positions) > 0:
|
| 453 |
+
return "⛔ Cannot start Backtest: Active trades exist! Close them first."
|
| 454 |
+
|
| 455 |
+
if sys_state.training_running:
|
| 456 |
+
return "⚠️ Training already in progress."
|
| 457 |
+
|
| 458 |
+
async def _run_bg_task():
|
| 459 |
+
sys_state.training_running = True
|
| 460 |
+
sys_state.training_status_msg = "🧪 Strategic Backtest Running..."
|
| 461 |
+
try:
|
| 462 |
+
logger.info("🧪 [Manual Trigger] Starting Strategic Backtest...")
|
| 463 |
+
await run_strategic_optimization_task()
|
| 464 |
+
if adaptive_hub:
|
| 465 |
+
await adaptive_hub.initialize()
|
| 466 |
+
logger.info("✅ [Manual Trigger] Backtest Complete. DNA Updated.")
|
| 467 |
except Exception as e:
|
| 468 |
+
logger.error(f"❌ Backtest Failed: {e}")
|
| 469 |
finally:
|
| 470 |
+
sys_state.training_running = False
|
| 471 |
+
sys_state.training_status_msg = adaptive_hub.get_status() if adaptive_hub else "Ready"
|
| 472 |
+
|
| 473 |
+
asyncio.create_task(_run_bg_task())
|
| 474 |
+
return "🧪 Strategic Backtest Started (Safe Mode)."
|
| 475 |
+
|
| 476 |
+
async def manual_close_current_trade():
|
| 477 |
+
if not trade_manager.open_positions: return "⚠️ No trade."
|
| 478 |
+
symbol = list(trade_manager.open_positions.keys())[0]
|
| 479 |
+
await trade_manager.force_exit_by_manager(symbol, reason="MANUAL_UI")
|
| 480 |
+
return f"✅ Closed {symbol}."
|
| 481 |
+
|
| 482 |
+
async def reset_history_handler():
|
| 483 |
+
if trade_manager.open_positions: return "⚠️ Close active trades first."
|
| 484 |
+
current_state = await r2.get_portfolio_state_async()
|
| 485 |
+
preserved_capital = current_state.get('current_capital_usd', INITIAL_CAPITAL)
|
| 486 |
+
await r2.reset_all_stats_async()
|
| 487 |
+
if trade_manager and trade_manager.smart_portfolio:
|
| 488 |
+
sp = trade_manager.smart_portfolio
|
| 489 |
+
sp.state["current_capital"] = preserved_capital
|
| 490 |
+
sp.state["session_start_balance"] = preserved_capital
|
| 491 |
+
sp.state["allocated_capital_usd"] = 0.0
|
| 492 |
+
sp.state["daily_net_pnl"] = 0.0
|
| 493 |
+
sp.state["is_trading_halted"] = False
|
| 494 |
+
await sp._save_state_to_r2()
|
| 495 |
+
return f"✅ History Cleared. Capital Preserved at ${preserved_capital:.2f}"
|
| 496 |
+
|
| 497 |
+
async def reset_capital_handler():
|
| 498 |
+
if trade_manager.open_positions: return "⚠️ Close active trades first."
|
| 499 |
+
if trade_manager and trade_manager.smart_portfolio:
|
| 500 |
+
sp = trade_manager.smart_portfolio
|
| 501 |
+
sp.state["current_capital"] = INITIAL_CAPITAL
|
| 502 |
+
sp.state["session_start_balance"] = INITIAL_CAPITAL
|
| 503 |
+
sp.state["allocated_capital_usd"] = 0.0
|
| 504 |
+
sp.state["daily_net_pnl"] = 0.0
|
| 505 |
+
sp.state["is_trading_halted"] = False
|
| 506 |
+
await sp._save_state_to_r2()
|
| 507 |
+
return f"✅ Capital Reset to ${INITIAL_CAPITAL} (History Kept)"
|
| 508 |
+
|
| 509 |
+
async def toggle_auto_pilot(enable):
|
| 510 |
+
sys_state.auto_pilot = enable
|
| 511 |
+
return f"Auto-Pilot: {enable}"
|
| 512 |
+
|
| 513 |
+
async def run_cycle_from_gradio():
|
| 514 |
+
if sys_state.cycle_running: return "Busy."
|
| 515 |
+
asyncio.create_task(run_unified_cycle())
|
| 516 |
+
return "🚀 Launched."
|
| 517 |
+
|
| 518 |
+
# ------------------------------------------------------------------------------
|
| 519 |
+
# UI Updates
|
| 520 |
+
# ------------------------------------------------------------------------------
|
| 521 |
+
async def check_live_pnl_and_status(selected_view="Dual-Core (Hybrid)"):
|
| 522 |
+
empty_chart = go.Figure()
|
| 523 |
+
empty_chart.update_layout(template="plotly_dark", paper_bgcolor="#0b0f19", plot_bgcolor="#0b0f19", xaxis={'visible':False}, yaxis={'visible':False})
|
| 524 |
+
wl_df_empty = pd.DataFrame(columns=["Coin", "Score"])
|
| 525 |
+
|
| 526 |
+
if not sys_state.ready:
|
| 527 |
+
return "Initializing...", "...", empty_chart, "0.0", "0.0", "0.0", "0.0", "0.0%", wl_df_empty, "Loading...", "Loading...", "Loading..."
|
| 528 |
+
|
| 529 |
+
try:
|
| 530 |
+
sp = trade_manager.smart_portfolio
|
| 531 |
+
equity = sp.state.get('current_capital', 10.0)
|
| 532 |
+
allocated = sp.state.get('allocated_capital_usd', 0.0)
|
| 533 |
+
free_cap = max(0.0, equity - allocated)
|
| 534 |
+
daily_pnl = sp.state.get('daily_net_pnl', 0.0)
|
| 535 |
+
is_halted = sp.state.get('is_trading_halted', False)
|
| 536 |
+
market_mood = sp.market_trend
|
| 537 |
+
fg_index = sp.fear_greed_index
|
| 538 |
+
|
| 539 |
+
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
|
| 540 |
+
active_trade_info = ""
|
| 541 |
+
trade_dur_str = "--:--:--"
|
| 542 |
+
|
| 543 |
+
if trade_manager.open_positions:
|
| 544 |
+
symbol = list(trade_manager.open_positions.keys())[0]
|
| 545 |
+
trade = trade_manager.open_positions[symbol]
|
| 546 |
+
entry_p = float(trade.get('entry_price', 0.0))
|
| 547 |
+
tp_p = float(trade.get('tp_price', 0.0))
|
| 548 |
+
sl_p = float(trade.get('sl_price', 0.0))
|
| 549 |
+
trade_dur_str = calculate_duration_str(trade.get('entry_time'))
|
| 550 |
+
sys_conf = trade.get('decision_data', {}).get('system_confidence', 0.0)
|
| 551 |
+
|
| 552 |
+
curr_p = await data_manager.get_latest_price_async(symbol)
|
| 553 |
+
if curr_p > 0 and entry_p > 0:
|
| 554 |
+
pnl_pct = ((curr_p - entry_p) / entry_p) * 100
|
| 555 |
+
size = float(trade.get('entry_capital', 0.0))
|
| 556 |
+
pnl_val_unrealized = size * (pnl_pct / 100)
|
| 557 |
+
|
| 558 |
+
active_trade_info = f"""
|
| 559 |
+
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc; margin-top:5px;'>
|
| 560 |
+
<span>⏱️ {symbol}:</span> <span style='color: #ffff00;'>{trade_dur_str}</span>
|
| 561 |
+
</div>
|
| 562 |
+
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc; margin-top:5px;'>
|
| 563 |
+
<span>🔮 Conf:</span> <span style='color: #00e5ff;'>{sys_conf:.1%}</span>
|
| 564 |
+
</div>
|
| 565 |
+
"""
|
| 566 |
+
|
| 567 |
+
virtual_equity = equity + pnl_val_unrealized
|
| 568 |
+
active_trade_pnl_val = pnl_val_unrealized
|
| 569 |
+
active_pnl_color = "#00ff00" if active_trade_pnl_val >= 0 else "#ff0000"
|
| 570 |
+
portfolio = await r2.get_portfolio_state_async()
|
| 571 |
+
total_t = portfolio.get('total_trades', 0)
|
| 572 |
+
wins = portfolio.get('winning_trades', 0)
|
| 573 |
+
losses = portfolio.get('losing_trades', 0)
|
| 574 |
+
if losses == 0 and total_t > 0: losses = total_t - wins
|
| 575 |
+
tot_prof = portfolio.get('total_profit_usd', 0.0)
|
| 576 |
+
tot_loss = portfolio.get('total_loss_usd', 0.0)
|
| 577 |
+
net_prof = tot_prof - tot_loss
|
| 578 |
+
win_rate = (wins / total_t * 100) if total_t > 0 else 0.0
|
| 579 |
+
color = "#00ff00" if daily_pnl >= 0 else "#ff0000"
|
| 580 |
+
halt_status = "<span style='color:red; font-weight:bold;'>HALTED</span>" if is_halted else "<span style='color:#00ff00;'>ACTIVE</span>"
|
| 581 |
+
current_regime = getattr(SystemLimits, 'CURRENT_REGIME', 'N/A')
|
| 582 |
+
|
| 583 |
+
wallet_md = f"""
|
| 584 |
+
<div style='background-color: #1a1a1a; padding: 15px; border-radius: 8px; border: 1px solid #333; text-align:center;'>
|
| 585 |
+
<h3 style='margin:0; color:#888; font-size:14px;'>💼 Smart Portfolio</h3>
|
| 586 |
+
<div style='font-size: 24px; font-weight: bold; color: white; margin: 5px 0 0 0;'>${virtual_equity:,.2f}</div>
|
| 587 |
+
<div style='font-size: 14px; color: {active_pnl_color}; margin-bottom: 5px;'>({active_trade_pnl_val:+,.2f} USD)</div>
|
| 588 |
+
|
| 589 |
+
<table style='width:100%; font-size:12px; margin-top:5px; color:#ccc;'>
|
| 590 |
+
<tr><td>Allocated:</td><td style='text-align:right; color:#ffa500;'>${allocated:.2f}</td></tr>
|
| 591 |
+
<tr><td>Free Cap:</td><td style='text-align:right; color:#00ff00;'>${free_cap:.2f}</td></tr>
|
| 592 |
+
<tr><td>Daily PnL:</td><td style='text-align:right; color:{color};'>${daily_pnl:+.2f}</td></tr>
|
| 593 |
+
</table>
|
| 594 |
+
|
| 595 |
+
<hr style='border-color:#444; margin: 10px 0;'>
|
| 596 |
+
|
| 597 |
+
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc;'>
|
| 598 |
+
<span>🦅 Market:</span> <span style='color: white;'>{market_mood} ({fg_index})</span>
|
| 599 |
+
</div>
|
| 600 |
+
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc; margin-top:3px;'>
|
| 601 |
+
<span>🧬 Regime:</span> <span style='color: #00e5ff; font-weight:bold;'>{current_regime}</span>
|
| 602 |
+
</div>
|
| 603 |
+
<div style='display: flex; justify-content: space-between; font-size: 12px; color: #ccc; margin-top:5px;'>
|
| 604 |
+
<span>🛡️ Status:</span> {halt_status}
|
| 605 |
+
</div>
|
| 606 |
+
{active_trade_info}
|
| 607 |
+
</div>
|
| 608 |
+
"""
|
| 609 |
+
|
| 610 |
+
key_map = {
|
| 611 |
+
"Dual-Core (Hybrid)": "hybrid",
|
| 612 |
+
"Hydra: Crash (Panic)": "crash",
|
| 613 |
+
"Hydra: Giveback (Profit)": "giveback",
|
| 614 |
+
"Hydra: Stagnation (Time)": "stagnation"
|
| 615 |
}
|
| 616 |
+
target_key = key_map.get(selected_view, "hybrid")
|
| 617 |
+
stats_data = trade_manager.ai_stats.get(target_key, {"total":0, "good":0, "saved":0.0, "missed":0.0})
|
| 618 |
+
|
| 619 |
+
tot_ds = stats_data['total']
|
| 620 |
+
ds_acc = (stats_data['good'] / tot_ds * 100) if tot_ds > 0 else 0.0
|
| 621 |
+
|
| 622 |
+
history_md = f"""
|
| 623 |
+
<div style='background-color: #1a1a1a; padding: 10px; border-radius: 8px; border: 1px solid #333; font-size: 12px;'>
|
| 624 |
+
<h3 style='margin:0 0 5px 0; color:#888; font-size:14px;'>📊 Performance</h3>
|
| 625 |
+
<table style='width:100%; color:white;'>
|
| 626 |
+
<tr><td>Trades:</td><td style='text-align:right;'>{total_t}</td></tr>
|
| 627 |
+
<tr><td>Win Rate:</td><td style='text-align:right; color:{"#00ff00" if win_rate>=50 else "#ff0000"};'>{win_rate:.1f}%</td></tr>
|
| 628 |
+
<tr><td>Wins:</td><td style='text-align:right; color:#00ff00;'>{wins} (+${tot_prof:,.2f})</td></tr>
|
| 629 |
+
<tr><td>Losses:</td><td style='text-align:right; color:#ff0000;'>{losses} (-${tot_loss:,.2f})</td></tr>
|
| 630 |
+
<tr><td style='border-top:1px solid #444;'>Net:</td><td style='border-top:1px solid #444; text-align:right; color:{"#00ff00" if net_prof>=0 else "#ff0000"};'>${net_prof:,.2f}</td></tr>
|
| 631 |
+
</table>
|
| 632 |
+
<hr style='border-color:#444; margin: 8px 0;'>
|
| 633 |
+
<h3 style='margin:0 0 5px 0; color: #00e5ff; font-size:14px;'>🛡️ Guard IQ ({target_key})</h3>
|
| 634 |
+
<table style='width:100%; color:white;'>
|
| 635 |
+
<tr><td>Interventions:</td><td style='text-align:right;'>{tot_ds}</td></tr>
|
| 636 |
+
<tr><td>Accuracy:</td><td style='text-align:right; color:#00e5ff;'>{ds_acc:.1f}%</td></tr>
|
| 637 |
+
<tr><td>Saved:</td><td style='text-align:right; color:#00ff00;'>${stats_data['saved']:.2f}</td></tr>
|
| 638 |
+
<tr><td>Missed:</td><td style='text-align:right; color:#ff0000;'>${stats_data['missed']:.2f}</td></tr>
|
| 639 |
+
</table>
|
| 640 |
+
</div>
|
| 641 |
+
"""
|
| 642 |
+
|
| 643 |
+
# --- 🧠 Neural Cycles Status Construction ---
|
| 644 |
+
fast_learn_prog = "0/100"
|
| 645 |
+
if adaptive_hub:
|
| 646 |
+
if hasattr(adaptive_hub, 'get_learning_progress'):
|
| 647 |
+
fast_learn_prog = adaptive_hub.get_learning_progress()
|
| 648 |
+
else:
|
| 649 |
+
fast_learn_prog = "N/A"
|
| 650 |
+
|
| 651 |
+
sch_w_time = "Wait"; sch_w_cnt = 0
|
| 652 |
+
sch_m_time = "Wait"; sch_m_cnt = 0
|
| 653 |
+
sch_running = False
|
| 654 |
+
|
| 655 |
+
if scheduler:
|
| 656 |
+
metrics = scheduler.get_status_metrics()
|
| 657 |
+
sch_w_time = metrics["weekly_timer"]
|
| 658 |
+
sch_w_cnt = metrics["weekly_count"]
|
| 659 |
+
sch_m_time = metrics["monthly_timer"]
|
| 660 |
+
sch_m_cnt = metrics["monthly_count"]
|
| 661 |
+
sch_running = metrics["is_running"]
|
| 662 |
+
|
| 663 |
+
running_badge = "<span style='color:#00ff00; float:right; animation: blink 1s infinite;'>RUNNING ⚙️</span>" if sch_running else ""
|
| 664 |
+
|
| 665 |
+
neural_md = f"""
|
| 666 |
+
<div style='background-color: #1a1a1a; padding: 10px; border-radius: 8px; border: 1px solid #333; font-size: 12px; margin-top: 10px;'>
|
| 667 |
+
<div style='display:flex; justify-content:space-between; align-items:center; margin-bottom:5px;'>
|
| 668 |
+
<h3 style='margin:0; color:#00e5ff; font-size:14px;'>🧠 Neural Cycles</h3>
|
| 669 |
+
{running_badge}
|
| 670 |
+
</div>
|
| 671 |
+
<table style='width:100%; color:#ccc;'>
|
| 672 |
+
<tr style='border-bottom: 1px solid #333;'>
|
| 673 |
+
<td style='padding:4px 0;'>⚡ Fast Learner:</td>
|
| 674 |
+
<td style='text-align:right; color:#ffff00; font-weight:bold;'>{fast_learn_prog}</td>
|
| 675 |
+
<td style='text-align:right; font-size:10px; color:#666;'>Trades</td>
|
| 676 |
+
</tr>
|
| 677 |
+
<tr style='border-bottom: 1px solid #333;'>
|
| 678 |
+
<td style='padding:4px 0;'>📅 Weekly Tune:</td>
|
| 679 |
+
<td style='text-align:right; color:#fff;'>{sch_w_time}</td>
|
| 680 |
+
<td style='text-align:right; color:#00ff00;'>#{sch_w_cnt}</td>
|
| 681 |
+
</tr>
|
| 682 |
+
<tr>
|
| 683 |
+
<td style='padding:4px 0;'>🗓️ Monthly Evo:</td>
|
| 684 |
+
<td style='text-align:right; color:#fff;'>{sch_m_time}</td>
|
| 685 |
+
<td style='text-align:right; color:#00ff00;'>#{sch_m_cnt}</td>
|
| 686 |
+
</tr>
|
| 687 |
+
</table>
|
| 688 |
+
<div style='margin-top:5px; font-size:10px; color:#555; text-align:center;'>
|
| 689 |
+
Adaptive DNA Active: {getattr(SystemLimits, 'CURRENT_REGIME', 'N/A')}
|
| 690 |
+
</div>
|
| 691 |
+
</div>
|
| 692 |
+
"""
|
| 693 |
+
|
| 694 |
+
wl_data = [[k, f"{v.get('final_total_score',0):.2f}"] for k, v in trade_manager.watchlist.items()]
|
| 695 |
+
wl_df = pd.DataFrame(wl_data, columns=["Coin", "Score"])
|
| 696 |
+
|
| 697 |
+
status_txt = sys_state.last_cycle_logs
|
| 698 |
+
status_line = f"Cycle: {'RUNNING' if sys_state.cycle_running else 'IDLE'} | Auto-Pilot: {'ON' if sys_state.auto_pilot else 'OFF'}"
|
| 699 |
+
|
| 700 |
+
fig = empty_chart
|
| 701 |
+
if symbol and curr_p > 0:
|
| 702 |
+
ohlcv = await data_manager.get_latest_ohlcv(symbol, '5m', 120)
|
| 703 |
+
if ohlcv:
|
| 704 |
+
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
|
| 705 |
+
df['datetime'] = pd.to_datetime(df['timestamp'], unit='ms')
|
| 706 |
+
fig = go.Figure(data=[go.Candlestick(
|
| 707 |
+
x=df['datetime'], open=df['open'], high=df['high'], low=df['low'], close=df['close'],
|
| 708 |
+
increasing_line_color='#00ff00', decreasing_line_color='#ff0000', name=symbol
|
| 709 |
+
)])
|
| 710 |
+
if entry_p > 0:
|
| 711 |
+
fig.add_hline(y=entry_p, line_dash="dash", line_color="white", annotation_text="ENTRY", annotation_position="top left")
|
| 712 |
+
if tp_p > 0:
|
| 713 |
+
fig.add_hline(y=tp_p, line_color="#00ff00", line_width=2, annotation_text="TARGET (TP)", annotation_position="top left")
|
| 714 |
+
if sl_p > 0:
|
| 715 |
+
fig.add_hline(y=sl_p, line_color="#ff0000", line_width=2, annotation_text="STOP LOSS", annotation_position="bottom left")
|
| 716 |
+
|
| 717 |
+
fig.update_layout(
|
| 718 |
+
template="plotly_dark",
|
| 719 |
+
paper_bgcolor="#0b0f19",
|
| 720 |
+
plot_bgcolor="#0b0f19",
|
| 721 |
+
margin=dict(l=0, r=40, t=30, b=0),
|
| 722 |
+
height=400,
|
| 723 |
+
xaxis_rangeslider_visible=False,
|
| 724 |
+
title=dict(text=f"{symbol} (Spot Long) | PnL: {pnl_pct:+.2f}%", font=dict(color="white"))
|
| 725 |
+
)
|
| 726 |
+
|
| 727 |
+
train_status = sys_state.training_status_msg
|
| 728 |
+
if sys_state.training_running: train_status = "🧪 Backtest Running..."
|
| 729 |
+
|
| 730 |
+
return (status_txt, status_line, fig, f"{curr_p:.6f}", f"{entry_p:.6f}", f"{tp_p:.6f}", f"{sl_p:.6f}",
|
| 731 |
+
f"{pnl_pct:+.2f}%", wl_df, wallet_md, history_md, neural_md)
|
| 732 |
+
|
| 733 |
+
except Exception:
|
| 734 |
+
traceback.print_exc()
|
| 735 |
+
return "Error", "Error", empty_chart, "0", "0", "0", "0", "0%", wl_df_empty, "Err", "Err", "Err"
|
| 736 |
+
|
| 737 |
+
# ------------------------------------------------------------------------------
|
| 738 |
+
# Gradio UI Construction
|
| 739 |
+
# ------------------------------------------------------------------------------
|
| 740 |
+
def create_gradio_ui():
|
| 741 |
+
custom_css = ".gradio-container {background:#0b0f19} .dataframe {background:#1a1a1a!important} .html-box {min-height:180px}"
|
| 742 |
+
|
| 743 |
+
with gr.Blocks(title="Titan V36.3 (Neural Dashboard)") as demo:
|
| 744 |
+
gr.HTML(f"<style>{custom_css}</style>")
|
| 745 |
+
|
| 746 |
+
gr.Markdown("# 🚀 Titan V36.3 (Cybernetic: Neural Dashboard)")
|
| 747 |
+
|
| 748 |
+
with gr.Row():
|
| 749 |
+
with gr.Column(scale=3):
|
| 750 |
+
live_chart = gr.Plot(label="Chart")
|
| 751 |
+
with gr.Row():
|
| 752 |
+
t_price = gr.Textbox(label="Price", interactive=False)
|
| 753 |
+
t_pnl = gr.Textbox(label="PnL %", interactive=False)
|
| 754 |
+
with gr.Row():
|
| 755 |
+
t_entry = gr.Textbox(label="Entry", interactive=False)
|
| 756 |
+
t_tp = gr.Textbox(label="TP", interactive=False)
|
| 757 |
+
t_sl = gr.Textbox(label="SL", interactive=False)
|
| 758 |
+
|
| 759 |
+
with gr.Column(scale=1):
|
| 760 |
+
wallet_out = gr.HTML(label="Smart Wallet", elem_classes="html-box")
|
| 761 |
+
# 🔥 إضافة المخرج الجديد
|
| 762 |
+
neural_out = gr.HTML(label="Neural Cycles", elem_classes="html-box")
|
| 763 |
+
|
| 764 |
+
stats_dd = gr.Dropdown([
|
| 765 |
+
"Dual-Core (Hybrid)",
|
| 766 |
+
"Hydra: Crash (Panic)",
|
| 767 |
+
"Hydra: Giveback (Profit)",
|
| 768 |
+
"Hydra: Stagnation (Time)"
|
| 769 |
+
], value="Dual-Core (Hybrid)", label="View Guard Stats")
|
| 770 |
+
history_out = gr.HTML(label="Stats", elem_classes="html-box")
|
| 771 |
+
watchlist_out = gr.DataFrame(label="Watchlist")
|
| 772 |
+
|
| 773 |
+
gr.HTML("<hr style='border-color:#333'>")
|
| 774 |
+
|
| 775 |
+
with gr.Row():
|
| 776 |
+
with gr.Column(scale=1):
|
| 777 |
+
auto_pilot = gr.Checkbox(label="✈️ Auto-Pilot", value=True)
|
| 778 |
+
with gr.Row():
|
| 779 |
+
btn_run = gr.Button("🚀 Scan", variant="primary")
|
| 780 |
+
btn_close = gr.Button("🚨 Close", variant="stop")
|
| 781 |
+
with gr.Row():
|
| 782 |
+
btn_train = gr.Button("🤖 Status", variant="secondary")
|
| 783 |
+
btn_backtest = gr.Button("🧪 Run Strategic Backtest", variant="secondary")
|
| 784 |
+
with gr.Row():
|
| 785 |
+
btn_history_reset = gr.Button("🗑️ Clear History", variant="secondary")
|
| 786 |
+
btn_cap_reset = gr.Button("💰 Reset Capital", variant="secondary")
|
| 787 |
+
|
| 788 |
+
status = gr.Markdown("Init...")
|
| 789 |
+
alert = gr.Textbox(label="Alerts", interactive=False)
|
| 790 |
+
|
| 791 |
+
with gr.Column(scale=3):
|
| 792 |
+
logs = gr.Textbox(label="Logs", lines=14, autoscroll=True, elem_classes="log-box", type="text")
|
| 793 |
+
gr.HTML("<style>.log-box textarea { font-family: 'Consolas', 'Monaco', monospace !important; font-size: 12px !important; white-space: pre !important; }</style>")
|
| 794 |
+
|
| 795 |
+
# Event Handlers
|
| 796 |
+
btn_run.click(fn=run_cycle_from_gradio, outputs=alert)
|
| 797 |
+
btn_close.click(fn=manual_close_current_trade, outputs=alert)
|
| 798 |
+
btn_history_reset.click(fn=reset_history_handler, outputs=alert)
|
| 799 |
+
btn_cap_reset.click(fn=reset_capital_handler, outputs=alert)
|
| 800 |
+
btn_train.click(fn=trigger_training_cycle, outputs=alert)
|
| 801 |
+
btn_backtest.click(fn=trigger_strategic_backtest, outputs=alert)
|
| 802 |
+
auto_pilot.change(fn=toggle_auto_pilot, inputs=auto_pilot, outputs=alert)
|
| 803 |
+
|
| 804 |
+
gr.Timer(3).tick(fn=check_live_pnl_and_status, inputs=stats_dd,
|
| 805 |
+
outputs=[logs, status, live_chart, t_price, t_entry, t_tp, t_sl, t_pnl, watchlist_out, wallet_out, history_out, neural_out])
|
| 806 |
+
return demo
|
| 807 |
+
|
| 808 |
+
fast_api_server = FastAPI(lifespan=lifespan)
|
| 809 |
+
gradio_dashboard = create_gradio_ui()
|
| 810 |
+
app = gr.mount_gradio_app(app=fast_api_server, blocks=gradio_dashboard, path="/")
|
| 811 |
|
| 812 |
if __name__ == "__main__":
|
| 813 |
+
import uvicorn
|
| 814 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|