Spaces:
Paused
Paused
Update ml_engine/processor.py
Browse files- ml_engine/processor.py +54 -8
ml_engine/processor.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
-
#
|
| 2 |
-
# (V35.
|
|
|
|
| 3 |
|
| 4 |
import asyncio
|
| 5 |
import traceback
|
|
@@ -9,6 +10,7 @@ import sys
|
|
| 9 |
import numpy as np
|
| 10 |
from typing import Dict, Any, List, Optional
|
| 11 |
|
|
|
|
| 12 |
try: from .titan_engine import TitanEngine
|
| 13 |
except ImportError: TitanEngine = None
|
| 14 |
try: from .patterns import ChartPatternAnalyzer
|
|
@@ -24,6 +26,9 @@ except ImportError: HybridDeepSteward = None
|
|
| 24 |
try: from .guardian_hydra import GuardianHydra
|
| 25 |
except ImportError: GuardianHydra = None
|
| 26 |
|
|
|
|
|
|
|
|
|
|
| 27 |
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 28 |
MODELS_L2_DIR = os.path.join(BASE_DIR, "ml_models", "layer2")
|
| 29 |
MODELS_PATTERN_DIR = os.path.join(BASE_DIR, "ml_models", "xgboost_pattern2")
|
|
@@ -34,29 +39,52 @@ MODEL_V2_PATH = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V2_Production.j
|
|
| 34 |
MODEL_V3_PATH = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V3_Production.json")
|
| 35 |
MODEL_V3_FEAT = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V3_Features.json")
|
| 36 |
|
|
|
|
|
|
|
|
|
|
| 37 |
class SystemLimits:
|
|
|
|
|
|
|
|
|
|
| 38 |
L1_MIN_AFFINITY_SCORE = 10
|
|
|
|
|
|
|
| 39 |
L2_WEIGHT_TITAN = 0.50
|
| 40 |
L2_WEIGHT_PATTERNS = 0.40
|
| 41 |
L2_WEIGHT_MC = 0.10
|
|
|
|
| 42 |
PATTERN_TF_WEIGHTS = {'15m': 0.40, '1h': 0.30, '5m': 0.20, '4h': 0.10, '1d': 0.00}
|
| 43 |
PATTERN_THRESH_BULLISH = 0.60
|
| 44 |
PATTERN_THRESH_BEARISH = 0.40
|
|
|
|
|
|
|
| 45 |
L3_CONFIDENCE_THRESHOLD = 0.65
|
| 46 |
L3_WHALE_IMPACT_MAX = 0.10
|
| 47 |
L3_NEWS_IMPACT_MAX = 0.05
|
| 48 |
L3_MC_ADVANCED_MAX = 0.10
|
|
|
|
|
|
|
| 49 |
L4_ENTRY_THRESHOLD = 0.30
|
| 50 |
L4_WEIGHT_ML = 0.60
|
| 51 |
L4_WEIGHT_OB = 0.40
|
| 52 |
L4_OB_WALL_RATIO = 0.40
|
|
|
|
|
|
|
| 53 |
HYDRA_CRASH_THRESH = 0.60
|
| 54 |
HYDRA_GIVEBACK_THRESH = 0.70
|
| 55 |
HYDRA_STAGNATION_THRESH = 0.50
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
@classmethod
|
| 58 |
def to_dict(cls) -> Dict[str, Any]:
|
| 59 |
return {k: v for k, v in cls.__dict__.items() if not k.startswith('__') and not callable(v)}
|
|
|
|
| 60 |
@classmethod
|
| 61 |
def update_from_dict(cls, config: Dict[str, Any]):
|
| 62 |
if not config: return
|
|
@@ -64,10 +92,14 @@ class SystemLimits:
|
|
| 64 |
if hasattr(cls, k): setattr(cls, k, v)
|
| 65 |
print("🔄 [SystemLimits] Config Updated.")
|
| 66 |
|
|
|
|
|
|
|
|
|
|
| 67 |
class MLProcessor:
|
| 68 |
def __init__(self, data_manager=None):
|
| 69 |
self.data_manager = data_manager
|
| 70 |
self.initialized = False
|
|
|
|
| 71 |
self.titan = TitanEngine(model_dir=MODELS_L2_DIR) if TitanEngine else None
|
| 72 |
self.pattern_engine = ChartPatternAnalyzer(models_dir=MODELS_PATTERN_DIR) if ChartPatternAnalyzer else None
|
| 73 |
self.mc_analyzer = MonteCarloEngine() if MonteCarloEngine else None
|
|
@@ -85,10 +117,12 @@ class MLProcessor:
|
|
| 85 |
v3_model_path=MODEL_V3_PATH,
|
| 86 |
v3_features_map_path=MODEL_V3_FEAT
|
| 87 |
)
|
| 88 |
-
|
|
|
|
| 89 |
|
| 90 |
async def initialize(self):
|
| 91 |
if self.initialized: return
|
|
|
|
| 92 |
try:
|
| 93 |
tasks = []
|
| 94 |
if self.titan: tasks.append(self.titan.initialize())
|
|
@@ -107,15 +141,30 @@ class MLProcessor:
|
|
| 107 |
w_ob=SystemLimits.L4_WEIGHT_OB
|
| 108 |
)
|
| 109 |
tasks.append(self.sniper.initialize())
|
|
|
|
| 110 |
if tasks: await asyncio.gather(*tasks)
|
| 111 |
|
| 112 |
if self.guardian_hydra:
|
| 113 |
self.guardian_hydra.initialize()
|
|
|
|
|
|
|
| 114 |
if self.guardian_legacy:
|
| 115 |
-
if asyncio.iscoroutinefunction(self.guardian_legacy.initialize):
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
self.initialized = True
|
|
|
|
| 119 |
|
| 120 |
except Exception as e:
|
| 121 |
print(f"❌ [Processor FATAL] Init failed: {e}")
|
|
@@ -189,12 +238,9 @@ class MLProcessor:
|
|
| 189 |
# 3. Final Arbitration & Display
|
| 190 |
h_probs = hydra_result.get('probs', {}); l_scores = legacy_result.get('scores', {})
|
| 191 |
h_c = h_probs.get('crash', 0.0); h_g = h_probs.get('giveback', 0.0)
|
| 192 |
-
# ✅ FIX: Extract Stagnation Score and Add to Log
|
| 193 |
h_s = h_probs.get('stagnation', 0.0)
|
| 194 |
|
| 195 |
l_v2 = l_scores.get('v2', 0.0); l_v3 = l_scores.get('v3', 0.0)
|
| 196 |
-
|
| 197 |
-
# ✅ FIX: Added |S:..%| to the string
|
| 198 |
stamp_str = f"🐲[C:{h_c:.0%}|G:{h_g:.0%}|S:{h_s:.0%}] 🕸️[V2:{l_v2:.0%}|V3:{l_v3:.0%}]"
|
| 199 |
|
| 200 |
final_action = 'HOLD'; final_reason = f"Safe. {stamp_str}"
|
|
|
|
| 1 |
+
# ============================================================
|
| 2 |
+
# 🧠 ml_engine/processor.py (V35.4 - GEM-Architect: Centralized Limits)
|
| 3 |
+
# ============================================================
|
| 4 |
|
| 5 |
import asyncio
|
| 6 |
import traceback
|
|
|
|
| 10 |
import numpy as np
|
| 11 |
from typing import Dict, Any, List, Optional
|
| 12 |
|
| 13 |
+
# --- استيراد المحركات (كما هي) ---
|
| 14 |
try: from .titan_engine import TitanEngine
|
| 15 |
except ImportError: TitanEngine = None
|
| 16 |
try: from .patterns import ChartPatternAnalyzer
|
|
|
|
| 26 |
try: from .guardian_hydra import GuardianHydra
|
| 27 |
except ImportError: GuardianHydra = None
|
| 28 |
|
| 29 |
+
# ============================================================
|
| 30 |
+
# 📂 مسارات النماذج
|
| 31 |
+
# ============================================================
|
| 32 |
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 33 |
MODELS_L2_DIR = os.path.join(BASE_DIR, "ml_models", "layer2")
|
| 34 |
MODELS_PATTERN_DIR = os.path.join(BASE_DIR, "ml_models", "xgboost_pattern2")
|
|
|
|
| 39 |
MODEL_V3_PATH = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V3_Production.json")
|
| 40 |
MODEL_V3_FEAT = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V3_Features.json")
|
| 41 |
|
| 42 |
+
# ============================================================
|
| 43 |
+
# 🎛️ SYSTEM LIMITS & THRESHOLDS (UPDATED)
|
| 44 |
+
# ============================================================
|
| 45 |
class SystemLimits:
|
| 46 |
+
"""GEM-Architect: The Central Constitution (Updated)."""
|
| 47 |
+
|
| 48 |
+
# --- Layer 1 (Data Manager Control) ---
|
| 49 |
L1_MIN_AFFINITY_SCORE = 10
|
| 50 |
+
|
| 51 |
+
# --- Layer 2 Weights ---
|
| 52 |
L2_WEIGHT_TITAN = 0.50
|
| 53 |
L2_WEIGHT_PATTERNS = 0.40
|
| 54 |
L2_WEIGHT_MC = 0.10
|
| 55 |
+
|
| 56 |
PATTERN_TF_WEIGHTS = {'15m': 0.40, '1h': 0.30, '5m': 0.20, '4h': 0.10, '1d': 0.00}
|
| 57 |
PATTERN_THRESH_BULLISH = 0.60
|
| 58 |
PATTERN_THRESH_BEARISH = 0.40
|
| 59 |
+
|
| 60 |
+
# --- Layer 3 ---
|
| 61 |
L3_CONFIDENCE_THRESHOLD = 0.65
|
| 62 |
L3_WHALE_IMPACT_MAX = 0.10
|
| 63 |
L3_NEWS_IMPACT_MAX = 0.05
|
| 64 |
L3_MC_ADVANCED_MAX = 0.10
|
| 65 |
+
|
| 66 |
+
# --- Layer 4 ---
|
| 67 |
L4_ENTRY_THRESHOLD = 0.30
|
| 68 |
L4_WEIGHT_ML = 0.60
|
| 69 |
L4_WEIGHT_OB = 0.40
|
| 70 |
L4_OB_WALL_RATIO = 0.40
|
| 71 |
+
|
| 72 |
+
# --- Layer 0: Hydra Thresholds ---
|
| 73 |
HYDRA_CRASH_THRESH = 0.60
|
| 74 |
HYDRA_GIVEBACK_THRESH = 0.70
|
| 75 |
HYDRA_STAGNATION_THRESH = 0.50
|
| 76 |
|
| 77 |
+
# --- ✅ NEW: Legacy Guardian Config (Moved Here) ---
|
| 78 |
+
# Processor is now the MASTER of these thresholds.
|
| 79 |
+
LEGACY_V2_PANIC_THRESH = 0.95
|
| 80 |
+
LEGACY_V3_HARD_THRESH = 0.95
|
| 81 |
+
LEGACY_V3_SOFT_THRESH = 0.85
|
| 82 |
+
LEGACY_V3_ULTRA_THRESH = 0.98
|
| 83 |
+
|
| 84 |
@classmethod
|
| 85 |
def to_dict(cls) -> Dict[str, Any]:
|
| 86 |
return {k: v for k, v in cls.__dict__.items() if not k.startswith('__') and not callable(v)}
|
| 87 |
+
|
| 88 |
@classmethod
|
| 89 |
def update_from_dict(cls, config: Dict[str, Any]):
|
| 90 |
if not config: return
|
|
|
|
| 92 |
if hasattr(cls, k): setattr(cls, k, v)
|
| 93 |
print("🔄 [SystemLimits] Config Updated.")
|
| 94 |
|
| 95 |
+
# ============================================================
|
| 96 |
+
# 🧠 MLProcessor Class
|
| 97 |
+
# ============================================================
|
| 98 |
class MLProcessor:
|
| 99 |
def __init__(self, data_manager=None):
|
| 100 |
self.data_manager = data_manager
|
| 101 |
self.initialized = False
|
| 102 |
+
|
| 103 |
self.titan = TitanEngine(model_dir=MODELS_L2_DIR) if TitanEngine else None
|
| 104 |
self.pattern_engine = ChartPatternAnalyzer(models_dir=MODELS_PATTERN_DIR) if ChartPatternAnalyzer else None
|
| 105 |
self.mc_analyzer = MonteCarloEngine() if MonteCarloEngine else None
|
|
|
|
| 117 |
v3_model_path=MODEL_V3_PATH,
|
| 118 |
v3_features_map_path=MODEL_V3_FEAT
|
| 119 |
)
|
| 120 |
+
|
| 121 |
+
print(f"🧠 [MLProcessor V35.4] Centralized Control Active.")
|
| 122 |
|
| 123 |
async def initialize(self):
|
| 124 |
if self.initialized: return
|
| 125 |
+
print("⚙️ [Processor] Initializing Neural Grid...")
|
| 126 |
try:
|
| 127 |
tasks = []
|
| 128 |
if self.titan: tasks.append(self.titan.initialize())
|
|
|
|
| 141 |
w_ob=SystemLimits.L4_WEIGHT_OB
|
| 142 |
)
|
| 143 |
tasks.append(self.sniper.initialize())
|
| 144 |
+
|
| 145 |
if tasks: await asyncio.gather(*tasks)
|
| 146 |
|
| 147 |
if self.guardian_hydra:
|
| 148 |
self.guardian_hydra.initialize()
|
| 149 |
+
print(" 🛡️ [Guard 1] Hydra X-Ray: Active")
|
| 150 |
+
|
| 151 |
if self.guardian_legacy:
|
| 152 |
+
if asyncio.iscoroutinefunction(self.guardian_legacy.initialize):
|
| 153 |
+
await self.guardian_legacy.initialize()
|
| 154 |
+
else:
|
| 155 |
+
self.guardian_legacy.initialize()
|
| 156 |
+
|
| 157 |
+
# ✅ GEM-Architect: Inject Thresholds from SystemLimits
|
| 158 |
+
self.guardian_legacy.configure_thresholds(
|
| 159 |
+
v2_panic=SystemLimits.LEGACY_V2_PANIC_THRESH,
|
| 160 |
+
v3_hard=SystemLimits.LEGACY_V3_HARD_THRESH,
|
| 161 |
+
v3_soft=SystemLimits.LEGACY_V3_SOFT_THRESH,
|
| 162 |
+
v3_ultra=SystemLimits.LEGACY_V3_ULTRA_THRESH
|
| 163 |
+
)
|
| 164 |
+
print(f" 🛡️ [Guard 2] Legacy Steward: Active (Limits Injected)")
|
| 165 |
|
| 166 |
self.initialized = True
|
| 167 |
+
print("✅ [Processor] All Systems Operational.")
|
| 168 |
|
| 169 |
except Exception as e:
|
| 170 |
print(f"❌ [Processor FATAL] Init failed: {e}")
|
|
|
|
| 238 |
# 3. Final Arbitration & Display
|
| 239 |
h_probs = hydra_result.get('probs', {}); l_scores = legacy_result.get('scores', {})
|
| 240 |
h_c = h_probs.get('crash', 0.0); h_g = h_probs.get('giveback', 0.0)
|
|
|
|
| 241 |
h_s = h_probs.get('stagnation', 0.0)
|
| 242 |
|
| 243 |
l_v2 = l_scores.get('v2', 0.0); l_v3 = l_scores.get('v3', 0.0)
|
|
|
|
|
|
|
| 244 |
stamp_str = f"🐲[C:{h_c:.0%}|G:{h_g:.0%}|S:{h_s:.0%}] 🕸️[V2:{l_v2:.0%}|V3:{l_v3:.0%}]"
|
| 245 |
|
| 246 |
final_action = 'HOLD'; final_reason = f"Safe. {stamp_str}"
|