Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,814 +1,290 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
-
#
|
| 4 |
|
| 5 |
-
import os
|
| 6 |
-
import sys
|
| 7 |
-
import traceback
|
| 8 |
import asyncio
|
| 9 |
-
import
|
|
|
|
|
|
|
| 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 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
#
|
| 35 |
-
#
|
| 36 |
-
|
| 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 |
-
|
| 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 |
-
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 |
-
|
| 160 |
-
|
| 161 |
-
|
| 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 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 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 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
if len(
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
-
|
|
|
|
|
|
|
| 314 |
|
| 315 |
-
|
| 316 |
-
|
| 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 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 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 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 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"❌ [
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
#
|
| 441 |
-
#
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
try:
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 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 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 551 |
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
|
|
|
|
|
|
|
|
|
| 557 |
|
| 558 |
-
|
| 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 |
-
|
| 765 |
-
|
| 766 |
-
"
|
| 767 |
-
|
| 768 |
-
"
|
| 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 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
|
|
|
| 811 |
|
| 812 |
if __name__ == "__main__":
|
| 813 |
-
|
| 814 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
# ============================================================
|
| 2 |
+
# 🗓️ periodic_tuner.py (V4.2 - GEM-Architect: Status Metrics)
|
| 3 |
+
# ============================================================
|
| 4 |
|
|
|
|
|
|
|
|
|
|
| 5 |
import asyncio
|
| 6 |
+
import numpy as np
|
| 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 |
+
from backtest_engine import HeavyDutyBacktester
|
| 17 |
+
from ml_engine.data_manager import DataManager
|
| 18 |
+
from ml_engine.processor import MLProcessor
|
| 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 |
+
# 👁️ MARKET SENSOR V3.2
|
| 40 |
+
# ============================================================
|
| 41 |
+
async def detect_dominant_regime(dm: DataManager, days_back=7):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
try:
|
| 43 |
+
required_limit = 200 + days_back + 10
|
| 44 |
+
logger.info(f"👁️ [Market Sensor] Analyzing Dominant Regime (Last {days_back} days)...")
|
| 45 |
+
|
| 46 |
+
candles = await dm.exchange.fetch_ohlcv('BTC/USDT', '1d', limit=required_limit)
|
| 47 |
+
if not candles or len(candles) < 200: return "RANGE"
|
| 48 |
+
|
| 49 |
+
df = pd.DataFrame(candles, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
|
| 50 |
+
close = df['close']
|
| 51 |
+
df['sma50'] = ta.sma(close, length=50)
|
| 52 |
+
df['sma200'] = ta.sma(close, length=200)
|
| 53 |
+
adx_df = ta.adx(df['high'], df['low'], close, length=14)
|
| 54 |
+
if adx_df is not None: df['adx'] = adx_df.iloc[:, 0]
|
| 55 |
+
else: df['adx'] = 0.0
|
| 56 |
+
df['vol_sma'] = df['volume'].rolling(30).mean()
|
| 57 |
+
|
| 58 |
+
window_df = df.iloc[-days_back:].copy()
|
| 59 |
+
if window_df.empty: return "RANGE"
|
| 60 |
+
|
| 61 |
+
regime_counts = {"BULL": 0, "BEAR": 0, "RANGE": 0, "DEAD": 0}
|
| 62 |
+
for index, row in window_df.iterrows():
|
| 63 |
+
day_regime = "RANGE"
|
| 64 |
+
price = row['close']
|
| 65 |
+
sma = row['sma200']
|
| 66 |
+
adx = row['adx']
|
| 67 |
+
vol = row['volume']
|
| 68 |
+
vol_avg = row['vol_sma']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
if pd.notna(vol_avg) and vol < (vol_avg * 0.4): day_regime = "DEAD"
|
| 71 |
+
elif pd.notna(sma) and price > sma: day_regime = "BULL" if adx > 25 else "RANGE"
|
| 72 |
+
elif pd.notna(sma) and price < sma: day_regime = "BEAR" if adx > 25 else "RANGE"
|
| 73 |
+
regime_counts[day_regime] += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
dominant_regime = max(regime_counts, key=regime_counts.get)
|
| 76 |
+
log_str = " | ".join([f"{k}:{v}" for k,v in regime_counts.items()])
|
| 77 |
+
logger.info(f" 👁️ Regime Distribution: [{log_str}] -> Winner: {dominant_regime}")
|
| 78 |
+
return dominant_regime
|
| 79 |
+
except Exception as e:
|
| 80 |
+
logger.error(f"⚠️ [Sensor Error] {e}")
|
| 81 |
+
return "RANGE"
|
| 82 |
+
|
| 83 |
+
# ============================================================
|
| 84 |
+
# 🩺 SURGICAL TUNER (Autonomous)
|
| 85 |
+
# ============================================================
|
| 86 |
+
async def run_surgical_tuning(period_type="weekly", use_fixed_list=True):
|
| 87 |
+
logger.info(f"🩺 [Auto-Tuner] Starting {period_type.upper()} optimization sequence...")
|
| 88 |
+
r2 = R2Service()
|
| 89 |
+
dm = DataManager(None, None, r2)
|
| 90 |
+
proc = MLProcessor(dm)
|
| 91 |
+
hub = AdaptiveHub(r2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
try:
|
| 93 |
+
await dm.initialize(); await proc.initialize(); await hub.initialize()
|
| 94 |
+
|
| 95 |
+
open_trades = await r2.get_open_trades_async()
|
| 96 |
+
if len(open_trades) > 0:
|
| 97 |
+
logger.warning(" ⛔ [Auto-Tuner] Aborted: Active trades present.")
|
| 98 |
+
return False
|
| 99 |
+
|
| 100 |
+
days_back = 7 if period_type == 'weekly' else 30
|
| 101 |
+
detected_regime = await detect_dominant_regime(dm, days_back=days_back)
|
| 102 |
+
hub.current_market_regime = detected_regime
|
| 103 |
+
asyncio.create_task(hub._save_state_to_r2())
|
| 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 |
+
end_date = datetime.now()
|
| 134 |
+
start_date = end_date - timedelta(days=days_back)
|
| 135 |
+
opt.set_date_range(start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d"))
|
| 136 |
|
| 137 |
+
logger.info(f" 🚀 Optimizing for {detected_regime} (Last {days_back} days)...")
|
| 138 |
+
best_config, stats = await opt.run_optimization(detected_regime)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
+
if best_config:
|
| 141 |
+
new_deltas = {}
|
| 142 |
+
new_deltas['l3_oracle_thresh'] = best_config.get('oracle_thresh') - base_filters['l3_oracle_thresh']
|
| 143 |
+
new_deltas['l4_sniper_thresh'] = best_config.get('sniper_thresh') - base_filters['l4_sniper_thresh']
|
| 144 |
+
new_deltas['hydra_crash'] = best_config.get('hydra_thresh') - base_guards['hydra_crash']
|
| 145 |
+
new_deltas['hydra_giveback'] = best_config.get('hydra_thresh') - base_guards['hydra_giveback']
|
| 146 |
+
new_deltas['legacy_v2'] = best_config.get('legacy_thresh') - base_guards['legacy_v2']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
+
logger.info(f" ✅ [Auto-Tuner] Success. Deltas: {new_deltas}")
|
| 149 |
+
hub.update_periodic_delta(detected_regime, period_type, new_deltas)
|
| 150 |
+
return True
|
| 151 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
except Exception as e:
|
| 154 |
+
logger.error(f"❌ [Auto-Tuner Error] {e}")
|
| 155 |
+
return False
|
| 156 |
+
finally:
|
| 157 |
+
await dm.close()
|
| 158 |
+
|
| 159 |
+
# ============================================================
|
| 160 |
+
# 🕰️ THE SCHEDULER CLASS (Persistent)
|
| 161 |
+
# ============================================================
|
| 162 |
+
class AutoTunerScheduler:
|
| 163 |
+
def __init__(self, trade_manager):
|
| 164 |
+
self.trade_manager = trade_manager
|
| 165 |
+
self.state_file = "scheduler_state.json"
|
| 166 |
+
|
| 167 |
+
# التوقيتات
|
| 168 |
+
self.last_weekly_run = None
|
| 169 |
+
self.last_monthly_run = None
|
| 170 |
+
|
| 171 |
+
# العدادات (Status Counters)
|
| 172 |
+
self.weekly_count = 0
|
| 173 |
+
self.monthly_count = 0
|
| 174 |
+
|
| 175 |
+
self.is_running = False
|
| 176 |
+
logger.info("🕰️ [Scheduler] Auto-Tuner Armed & Ready.")
|
| 177 |
+
|
| 178 |
+
async def start_loop(self):
|
| 179 |
+
await self._load_state()
|
| 180 |
+
while True:
|
| 181 |
+
try:
|
| 182 |
+
await asyncio.sleep(3600)
|
| 183 |
+
now = datetime.now()
|
| 184 |
+
|
| 185 |
+
# WEEKLY (Monday 03:00 AM)
|
| 186 |
+
if now.weekday() == 0 and 3 <= now.hour < 4:
|
| 187 |
+
if self._needs_run('weekly'): await self._try_run('weekly')
|
| 188 |
+
|
| 189 |
+
# MONTHLY (1st Day 04:00 AM)
|
| 190 |
+
if now.day == 1 and 4 <= now.hour < 5:
|
| 191 |
+
if self._needs_run('monthly'): await self._try_run('monthly')
|
| 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 |
+
async def _save_state(self):
|
| 215 |
+
try:
|
| 216 |
+
state = {
|
| 217 |
+
"last_weekly": self.last_weekly_run.isoformat() if self.last_weekly_run else None,
|
| 218 |
+
"last_monthly": self.last_monthly_run.isoformat() if self.last_monthly_run else None,
|
| 219 |
+
"weekly_count": self.weekly_count,
|
| 220 |
+
"monthly_count": self.monthly_count
|
| 221 |
+
}
|
| 222 |
+
if self.trade_manager.r2:
|
| 223 |
+
await self.trade_manager.r2.upload_json_async(state, self.state_file)
|
| 224 |
+
logger.info(" 💾 [Scheduler] State Saved.")
|
| 225 |
+
except Exception: pass
|
| 226 |
+
|
| 227 |
+
def _needs_run(self, period_type):
|
| 228 |
+
now = datetime.now()
|
| 229 |
+
if period_type == 'weekly':
|
| 230 |
+
if not self.last_weekly_run: return True
|
| 231 |
+
return (now - self.last_weekly_run).days >= 6
|
| 232 |
+
if period_type == 'monthly':
|
| 233 |
+
if not self.last_monthly_run: return True
|
| 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 |
+
if success:
|
| 248 |
+
# 2. Update Timestamps & Counters
|
| 249 |
+
if period_type == 'weekly':
|
| 250 |
+
self.last_weekly_run = datetime.now()
|
| 251 |
+
self.weekly_count += 1
|
| 252 |
+
else:
|
| 253 |
+
self.last_monthly_run = datetime.now()
|
| 254 |
+
self.monthly_count += 1
|
| 255 |
|
| 256 |
+
await self._save_state()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
+
# 3. 🔥 HOT RELOAD LIVE SYSTEM (The Final Sync)
|
| 259 |
+
if self.trade_manager.learning_hub:
|
| 260 |
+
logger.info(" 🔄 [Scheduler] Hot-Reloading Live DNA...")
|
| 261 |
+
await self.trade_manager.learning_hub.initialize()
|
| 262 |
+
logger.info(" ✨ [Scheduler] Live System Updated Successfully.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
+
except Exception as e:
|
| 265 |
+
logger.error(f"❌ [Scheduler Fail] {e}")
|
| 266 |
+
finally:
|
| 267 |
+
self.is_running = False
|
| 268 |
+
|
| 269 |
+
# ✅ دالة جلب المقاييس للواجهة
|
| 270 |
+
def get_status_metrics(self):
|
| 271 |
+
def _fmt_time(last_dt):
|
| 272 |
+
if not last_dt: return "Pending"
|
| 273 |
+
diff = datetime.now() - last_dt
|
| 274 |
+
d = diff.days
|
| 275 |
+
h = diff.seconds // 3600
|
| 276 |
+
return f"{d}d {h}h"
|
| 277 |
+
|
| 278 |
+
return {
|
| 279 |
+
"weekly_timer": _fmt_time(self.last_weekly_run),
|
| 280 |
+
"weekly_count": self.weekly_count,
|
| 281 |
+
"monthly_timer": _fmt_time(self.last_monthly_run),
|
| 282 |
+
"monthly_count": self.monthly_count,
|
| 283 |
+
"is_running": self.is_running
|
| 284 |
+
}
|
| 285 |
|
| 286 |
if __name__ == "__main__":
|
| 287 |
+
parser = argparse.ArgumentParser()
|
| 288 |
+
parser.add_argument('--type', type=str, default='weekly', help='weekly or monthly')
|
| 289 |
+
args = parser.parse_args()
|
| 290 |
+
asyncio.run(run_surgical_tuning(args.type, use_fixed_list=True))
|