Spaces:
Sleeping
Sleeping
Update ml_engine/processor.py
Browse files- ml_engine/processor.py +149 -306
ml_engine/processor.py
CHANGED
|
@@ -1,23 +1,17 @@
|
|
| 1 |
# ============================================================
|
| 2 |
# 🧠 ml_engine/processor.py
|
| 3 |
-
# (
|
| 4 |
# ============================================================
|
| 5 |
|
| 6 |
import asyncio
|
| 7 |
import traceback
|
| 8 |
-
import logging
|
| 9 |
import os
|
| 10 |
-
import sys
|
| 11 |
import numpy as np
|
| 12 |
from typing import Dict, Any, List, Optional
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
try: from .
|
| 16 |
-
except ImportError:
|
| 17 |
-
|
| 18 |
-
# تم الإبقاء على الاستيراد لمنع أخطاء التبعية، لكن لن يتم استخدامه
|
| 19 |
-
try: from .patterns import ChartPatternAnalyzer
|
| 20 |
-
except ImportError: ChartPatternAnalyzer = None
|
| 21 |
|
| 22 |
try: from .monte_carlo import MonteCarloEngine
|
| 23 |
except ImportError: MonteCarloEngine = None
|
|
@@ -30,11 +24,8 @@ except ImportError: HybridDeepSteward = None
|
|
| 30 |
try: from .guardian_hydra import GuardianHydra
|
| 31 |
except ImportError: GuardianHydra = None
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
# 📂 مسارات النماذج
|
| 35 |
-
# ============================================================
|
| 36 |
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 37 |
-
MODELS_L2_DIR = os.path.join(BASE_DIR, "ml_models", "layer2")
|
| 38 |
MODELS_UNIFIED_DIR = os.path.join(BASE_DIR, "ml_models", "Unified_Models_V1")
|
| 39 |
MODELS_SNIPER_DIR = os.path.join(BASE_DIR, "ml_models", "guard_v2")
|
| 40 |
MODELS_HYDRA_DIR = os.path.join(BASE_DIR, "ml_models", "guard_v1")
|
|
@@ -43,59 +34,40 @@ MODEL_V3_PATH = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V3_Production.j
|
|
| 43 |
MODEL_V3_FEAT = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V3_Features.json")
|
| 44 |
|
| 45 |
# ============================================================
|
| 46 |
-
# 🎛️ SYSTEM LIMITS (
|
| 47 |
# ============================================================
|
| 48 |
class SystemLimits:
|
| 49 |
"""
|
| 50 |
-
GEM-Architect:
|
| 51 |
-
Titan V2 is conservative, so Gate is lowered to 0.40.
|
| 52 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
# --- Layer
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
L2_GATE_PATTERN = 0.00 # Disabled (Pattern Engine Removed)
|
| 61 |
-
L2_GATE_MC = 0.00
|
| 62 |
|
| 63 |
-
|
| 64 |
-
L2_MIN_SCORE = 40.0 # Score is now 0-100 based
|
| 65 |
-
|
| 66 |
-
# ✅ المعادلة الجديدة: الاعتماد الكلي على تيتان
|
| 67 |
-
L2_WEIGHT_TITAN = 0.90
|
| 68 |
-
L2_WEIGHT_PATTERNS = 0.00
|
| 69 |
-
L2_WEIGHT_MC = 0.10
|
| 70 |
-
|
| 71 |
-
# Pattern Config (Kept for compatibility, effectively unused)
|
| 72 |
-
PATTERN_TF_WEIGHTS = {'1h': 0.35, '15m': 0.25, '1d': 0.20, '5m': 0.10, '4h': 0.10}
|
| 73 |
-
PATTERN_THRESH_BULLISH = 0.50
|
| 74 |
-
PATTERN_THRESH_BEARISH = 0.40
|
| 75 |
|
| 76 |
-
# --- Layer 3
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
L3_NEWS_IMPACT_MAX = 10.0
|
| 80 |
-
L3_MC_ADVANCED_MAX = 10.0
|
| 81 |
|
| 82 |
-
# --- Layer 4
|
| 83 |
-
L4_ENTRY_THRESHOLD = 0.
|
| 84 |
L4_WEIGHT_ML = 0.60
|
| 85 |
L4_WEIGHT_OB = 0.40
|
| 86 |
-
L4_OB_WALL_RATIO = 0.35
|
| 87 |
|
| 88 |
-
# ---
|
| 89 |
HYDRA_CRASH_THRESH = 0.60
|
| 90 |
HYDRA_GIVEBACK_THRESH = 0.80
|
| 91 |
HYDRA_STAGNATION_THRESH = 0.60
|
| 92 |
|
| 93 |
-
# Fixed Legacy Guards
|
| 94 |
-
LEGACY_V2_PANIC_THRESH = 0.98
|
| 95 |
-
LEGACY_V3_HARD_THRESH = 0.95
|
| 96 |
-
LEGACY_V3_SOFT_THRESH = 0.88
|
| 97 |
-
LEGACY_V3_ULTRA_THRESH = 0.99
|
| 98 |
-
|
| 99 |
@classmethod
|
| 100 |
def to_dict(cls) -> Dict[str, Any]:
|
| 101 |
return {k: v for k, v in cls.__dict__.items() if not k.startswith('__') and not callable(v)}
|
|
@@ -107,295 +79,166 @@ class MLProcessor:
|
|
| 107 |
def __init__(self, data_manager=None):
|
| 108 |
self.data_manager = data_manager
|
| 109 |
self.initialized = False
|
| 110 |
-
self.initialization_attempted = False
|
| 111 |
|
| 112 |
-
# ✅
|
| 113 |
-
self.
|
| 114 |
-
|
| 115 |
-
# ✅ 2. Oracle V4.5 (LightGBM) - The Strategist
|
| 116 |
self.oracle = OracleEngine(model_dir=MODELS_UNIFIED_DIR) if OracleEngine else None
|
| 117 |
-
|
| 118 |
-
# 3. Monte Carlo (Safety Check)
|
| 119 |
self.mc_analyzer = MonteCarloEngine() if MonteCarloEngine else None
|
| 120 |
|
| 121 |
-
#
|
| 122 |
self.sniper = SniperEngine(models_dir=MODELS_SNIPER_DIR) if SniperEngine else None
|
| 123 |
|
| 124 |
-
#
|
| 125 |
-
self.guardian_hydra = None
|
| 126 |
-
|
| 127 |
-
self.guardian_hydra = GuardianHydra(model_dir=MODELS_HYDRA_DIR)
|
| 128 |
-
|
| 129 |
-
self.guardian_legacy = None
|
| 130 |
if HybridDeepSteward:
|
| 131 |
-
self.guardian_legacy = HybridDeepSteward(
|
| 132 |
-
v2_model_path=MODEL_V2_PATH,
|
| 133 |
-
v3_model_path=MODEL_V3_PATH,
|
| 134 |
-
v3_features_map_path=MODEL_V3_FEAT
|
| 135 |
-
)
|
| 136 |
|
| 137 |
-
print(f"🧠 [
|
| 138 |
|
| 139 |
async def initialize(self):
|
| 140 |
if self.initialized: return True
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
self.initialization_attempted = True
|
| 144 |
-
print("⚙️ [Processor] Initializing Neural Grid...")
|
| 145 |
-
|
| 146 |
try:
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
-
if self.titan: init_tasks.append(self.titan.initialize())
|
| 150 |
-
if self.oracle:
|
| 151 |
-
# Oracle settings are handled in its class now
|
| 152 |
-
init_tasks.append(self.oracle.initialize())
|
| 153 |
-
if self.mc_analyzer and hasattr(self.mc_analyzer, 'initialize'):
|
| 154 |
-
# Check if async
|
| 155 |
-
if asyncio.iscoroutinefunction(self.mc_analyzer.initialize):
|
| 156 |
-
init_tasks.append(self.mc_analyzer.initialize())
|
| 157 |
-
|
| 158 |
-
if self.sniper:
|
| 159 |
-
self.sniper.configure_settings(
|
| 160 |
-
threshold=SystemLimits.L4_ENTRY_THRESHOLD,
|
| 161 |
-
wall_ratio=SystemLimits.L4_OB_WALL_RATIO,
|
| 162 |
-
w_ml=SystemLimits.L4_WEIGHT_ML,
|
| 163 |
-
w_ob=SystemLimits.L4_WEIGHT_OB
|
| 164 |
-
)
|
| 165 |
-
init_tasks.append(self.sniper.initialize())
|
| 166 |
-
|
| 167 |
-
# Await all async inits
|
| 168 |
-
await asyncio.gather(*init_tasks)
|
| 169 |
-
|
| 170 |
-
# Sync Guardians (usually sync methods)
|
| 171 |
if self.guardian_hydra: self.guardian_hydra.initialize()
|
| 172 |
-
if self.guardian_legacy:
|
| 173 |
-
|
| 174 |
-
await self.guardian_legacy.initialize()
|
| 175 |
-
else:
|
| 176 |
-
self.guardian_legacy.initialize()
|
| 177 |
-
|
| 178 |
-
self.guardian_legacy.configure_thresholds(
|
| 179 |
-
v2_panic=SystemLimits.LEGACY_V2_PANIC_THRESH,
|
| 180 |
-
v3_hard=SystemLimits.LEGACY_V3_HARD_THRESH,
|
| 181 |
-
v3_soft=SystemLimits.LEGACY_V3_SOFT_THRESH,
|
| 182 |
-
v3_ultra=SystemLimits.LEGACY_V3_ULTRA_THRESH
|
| 183 |
-
)
|
| 184 |
-
|
| 185 |
self.initialized = True
|
| 186 |
-
print("✅ [Processor] All Systems Operational.")
|
| 187 |
return True
|
| 188 |
-
|
| 189 |
except Exception as e:
|
| 190 |
-
print(f"❌ [Processor
|
| 191 |
-
traceback.print_exc()
|
| 192 |
-
self.initialized = False
|
| 193 |
return False
|
| 194 |
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
| 196 |
"""
|
| 197 |
-
|
| 198 |
-
|
|
|
|
| 199 |
"""
|
| 200 |
if not self.initialized: await self.initialize()
|
| 201 |
|
| 202 |
symbol = raw_data.get('symbol')
|
| 203 |
-
|
| 204 |
-
current_price = raw_data.get('current_price', 0.0)
|
| 205 |
-
limits = raw_data.get('dynamic_limits', {})
|
| 206 |
-
|
| 207 |
-
if not symbol or not ohlcv_data: return None
|
| 208 |
|
| 209 |
try:
|
| 210 |
-
# 1.
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
#
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
raw_mc = self.mc_analyzer.run_light_check(closes)
|
| 229 |
-
# Normalize MC (-0.1 to +0.1) -> (0.0 to 1.0) approx
|
| 230 |
-
mc_score = 0.5 + (raw_mc * 5.0)
|
| 231 |
-
mc_score = max(0.0, min(1.0, mc_score))
|
| 232 |
-
except: pass
|
| 233 |
-
|
| 234 |
-
# --- 3. Gated Logic (Titan V2 Focused) ---
|
| 235 |
-
gate_titan = limits.get('l2_gate_titan', SystemLimits.L2_GATE_TITAN)
|
| 236 |
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
# Hard Gate: Titan Only
|
| 241 |
-
if score_titan < gate_titan:
|
| 242 |
-
is_valid = False
|
| 243 |
-
rejection_reason = f"Titan Weak ({score_titan:.2f} < {gate_titan})"
|
| 244 |
-
|
| 245 |
-
# Weighted Score (Titan 90%, MC 10%)
|
| 246 |
-
hybrid_score = (score_titan * 90) + (mc_score * 10) # 0-100 scale
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
# الحقن المباشر للعتبة من Limits
|
| 276 |
-
limits = symbol_data.get('dynamic_limits', {})
|
| 277 |
-
threshold = limits.get('l3_oracle_thresh', SystemLimits.L3_CONFIDENCE_THRESHOLD)
|
| 278 |
-
|
| 279 |
-
if self.oracle:
|
| 280 |
-
try:
|
| 281 |
-
# Update threshold dynamically
|
| 282 |
-
if hasattr(self.oracle, 'set_threshold'):
|
| 283 |
-
self.oracle.set_threshold(threshold)
|
| 284 |
-
|
| 285 |
-
decision = await self.oracle.predict(symbol_data)
|
| 286 |
-
|
| 287 |
-
# Oracle V4.5 decision is based on Expected Return (oracle_score)
|
| 288 |
-
# But we map it to standard keys for app.py
|
| 289 |
-
return decision
|
| 290 |
-
except Exception as e:
|
| 291 |
-
print(f"❌ [Processor] Oracle error: {e}")
|
| 292 |
-
return {'action': 'WAIT', 'reason': f'Oracle error: {str(e)}'}
|
| 293 |
-
return {'action': 'WAIT', 'reason': 'Oracle Engine Missing'}
|
| 294 |
|
| 295 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
if not self.initialized: await self.initialize()
|
| 297 |
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
wall_r = limits.get('l4_ob_wall_ratio', SystemLimits.L4_OB_WALL_RATIO)
|
| 301 |
-
|
| 302 |
-
if self.sniper:
|
| 303 |
-
try:
|
| 304 |
-
self.sniper.configure_settings(
|
| 305 |
-
threshold=thresh,
|
| 306 |
-
wall_ratio=wall_r,
|
| 307 |
-
w_ml=SystemLimits.L4_WEIGHT_ML,
|
| 308 |
-
w_ob=SystemLimits.L4_WEIGHT_OB
|
| 309 |
-
)
|
| 310 |
-
return await self.sniper.check_entry_signal_async(ohlcv_1m_data, order_book_data)
|
| 311 |
-
except Exception as e:
|
| 312 |
-
return {'signal': 'WAIT', 'reason': f'Sniper error: {str(e)}'}
|
| 313 |
|
| 314 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
|
| 323 |
-
|
| 324 |
-
limits = trade_context.get('dynamic_limits', {})
|
| 325 |
-
h_crash_thresh = limits.get('hydra_crash', SystemLimits.HYDRA_CRASH_THRESH)
|
| 326 |
-
h_giveback_thresh = limits.get('hydra_giveback', SystemLimits.HYDRA_GIVEBACK_THRESH)
|
| 327 |
-
h_stag_thresh = limits.get('hydra_stagnation', SystemLimits.HYDRA_STAGNATION_THRESH)
|
| 328 |
-
|
| 329 |
-
# Context
|
| 330 |
-
entry_price = float(trade_context.get('entry_price', 0.0))
|
| 331 |
-
highest_price = trade_context.get('highest_price', entry_price)
|
| 332 |
-
max_pnl_pct = ((highest_price - entry_price) / entry_price) * 100 if entry_price > 0 else 0.0
|
| 333 |
-
time_in_trade_mins = trade_context.get('time_in_trade_mins', 0.0)
|
| 334 |
-
|
| 335 |
-
# A. Hydra Execution
|
| 336 |
-
hydra_result = {'action': 'HOLD', 'reason': 'Disabled', 'probs': {}}
|
| 337 |
if self.guardian_hydra:
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
if p_crash >= h_crash_thresh:
|
| 346 |
-
hydra_result['action'] = 'EXIT_HARD'
|
| 347 |
-
hydra_result['reason'] = f"Hydra Crash Risk {p_crash:.2f}"
|
| 348 |
-
elif p_giveback >= h_giveback_thresh and max_pnl_pct >= 0.6:
|
| 349 |
-
hydra_result['action'] = 'EXIT_SOFT'
|
| 350 |
-
hydra_result['reason'] = f"Hydra Giveback {p_giveback:.2f}"
|
| 351 |
-
elif p_stagnation >= h_stag_thresh and time_in_trade_mins > 90:
|
| 352 |
-
hydra_result['action'] = 'EXIT_SOFT'
|
| 353 |
-
hydra_result['reason'] = f"Hydra Stagnation {p_stagnation:.2f}"
|
| 354 |
-
except Exception as e:
|
| 355 |
-
print(f"⚠️ [Processor] Hydra error: {e}")
|
| 356 |
-
|
| 357 |
-
# B. Legacy Execution
|
| 358 |
-
legacy_result = {'action': 'HOLD', 'reason': 'Disabled', 'scores': {}}
|
| 359 |
if self.guardian_legacy:
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
# C. Arbitration
|
| 371 |
-
h_probs = hydra_result.get('probs', {})
|
| 372 |
-
l_scores = legacy_result.get('scores', {})
|
| 373 |
-
|
| 374 |
-
final_action = 'HOLD'
|
| 375 |
-
final_reason = f"Safe."
|
| 376 |
-
|
| 377 |
-
hydra_act = hydra_result.get('action', 'HOLD')
|
| 378 |
-
legacy_act = legacy_result.get('action', 'HOLD')
|
| 379 |
-
|
| 380 |
-
if hydra_act in ['EXIT_HARD', 'EXIT_SOFT', 'TIGHTEN_SL', 'TRAIL_SL']:
|
| 381 |
-
final_action = hydra_act
|
| 382 |
-
final_reason = f"🐲 {hydra_result.get('reason')}"
|
| 383 |
-
elif legacy_act in ['EXIT_HARD', 'EXIT_SOFT']:
|
| 384 |
-
final_action = legacy_act
|
| 385 |
-
final_reason = f"🕸️ {legacy_result.get('reason')}"
|
| 386 |
-
|
| 387 |
-
return {
|
| 388 |
-
'action': final_action,
|
| 389 |
-
'reason': final_reason,
|
| 390 |
-
'probs': h_probs,
|
| 391 |
-
'scores': l_scores
|
| 392 |
-
}
|
| 393 |
-
|
| 394 |
-
async def run_advanced_monte_carlo(self, symbol, timeframe='1h'):
|
| 395 |
-
if self.mc_analyzer and self.data_manager:
|
| 396 |
-
try:
|
| 397 |
-
ohlcv = await self.data_manager.get_latest_ohlcv(symbol, timeframe, limit=300)
|
| 398 |
-
if ohlcv:
|
| 399 |
-
return self.mc_analyzer.run_advanced_simulation([c[4] for c in ohlcv])
|
| 400 |
-
except: pass
|
| 401 |
-
return 0.0
|
|
|
|
| 1 |
# ============================================================
|
| 2 |
# 🧠 ml_engine/processor.py
|
| 3 |
+
# (V70.0 - GEM-Architect: 5-Layer Precision Logic)
|
| 4 |
# ============================================================
|
| 5 |
|
| 6 |
import asyncio
|
| 7 |
import traceback
|
|
|
|
| 8 |
import os
|
|
|
|
| 9 |
import numpy as np
|
| 10 |
from typing import Dict, Any, List, Optional
|
| 11 |
|
| 12 |
+
# Imports
|
| 13 |
+
try: from .pattern_engine import PatternEngine # Renamed from Titan
|
| 14 |
+
except ImportError: PatternEngine = None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
try: from .monte_carlo import MonteCarloEngine
|
| 17 |
except ImportError: MonteCarloEngine = None
|
|
|
|
| 24 |
try: from .guardian_hydra import GuardianHydra
|
| 25 |
except ImportError: GuardianHydra = None
|
| 26 |
|
| 27 |
+
# Base Paths
|
|
|
|
|
|
|
| 28 |
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
| 29 |
MODELS_UNIFIED_DIR = os.path.join(BASE_DIR, "ml_models", "Unified_Models_V1")
|
| 30 |
MODELS_SNIPER_DIR = os.path.join(BASE_DIR, "ml_models", "guard_v2")
|
| 31 |
MODELS_HYDRA_DIR = os.path.join(BASE_DIR, "ml_models", "guard_v1")
|
|
|
|
| 34 |
MODEL_V3_FEAT = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V3_Features.json")
|
| 35 |
|
| 36 |
# ============================================================
|
| 37 |
+
# 🎛️ SYSTEM LIMITS (Calibrated for 5-Layer Pipeline)
|
| 38 |
# ============================================================
|
| 39 |
class SystemLimits:
|
| 40 |
"""
|
| 41 |
+
GEM-Architect: Logic Gates Configuration.
|
|
|
|
| 42 |
"""
|
| 43 |
+
# --- Layer 2: Pattern Net Gate ---
|
| 44 |
+
# The PatternNet (ResNet) outputs a probability (0.0 - 1.0).
|
| 45 |
+
# We set the gate to 0.40 as requested.
|
| 46 |
+
L2_GATE_PATTERN_NET = 0.40
|
| 47 |
|
| 48 |
+
# --- Layer 2: Composite Score Weights ---
|
| 49 |
+
# Score = (Pattern * W1) + (Oracle * W2) + (MC * W3)
|
| 50 |
+
# Total should sum to roughly 1.0 for normalized scoring
|
| 51 |
+
L2_WEIGHT_PATTERN = 0.50
|
| 52 |
+
L2_WEIGHT_ORACLE = 0.30
|
| 53 |
+
L2_WEIGHT_MC = 0.20
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
L2_MIN_COMPOSITE_SCORE = 50.0 # Out of 100
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
+
# --- Layer 3: External Data Impact ---
|
| 58 |
+
L3_WHALE_IMPACT_MAX = 15.0 # Additive points
|
| 59 |
+
L3_NEWS_IMPACT_MAX = 10.0 # Additive points
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
# --- Layer 4: Sniper ---
|
| 62 |
+
L4_ENTRY_THRESHOLD = 0.50 # Higher confidence needed for final selection
|
| 63 |
L4_WEIGHT_ML = 0.60
|
| 64 |
L4_WEIGHT_OB = 0.40
|
|
|
|
| 65 |
|
| 66 |
+
# --- Guardians (Exit Logic) ---
|
| 67 |
HYDRA_CRASH_THRESH = 0.60
|
| 68 |
HYDRA_GIVEBACK_THRESH = 0.80
|
| 69 |
HYDRA_STAGNATION_THRESH = 0.60
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
@classmethod
|
| 72 |
def to_dict(cls) -> Dict[str, Any]:
|
| 73 |
return {k: v for k, v in cls.__dict__.items() if not k.startswith('__') and not callable(v)}
|
|
|
|
| 79 |
def __init__(self, data_manager=None):
|
| 80 |
self.data_manager = data_manager
|
| 81 |
self.initialized = False
|
|
|
|
| 82 |
|
| 83 |
+
# ✅ Layer 2 Engines
|
| 84 |
+
self.pattern_net = PatternEngine(model_dir=MODELS_UNIFIED_DIR) if PatternEngine else None
|
|
|
|
|
|
|
| 85 |
self.oracle = OracleEngine(model_dir=MODELS_UNIFIED_DIR) if OracleEngine else None
|
|
|
|
|
|
|
| 86 |
self.mc_analyzer = MonteCarloEngine() if MonteCarloEngine else None
|
| 87 |
|
| 88 |
+
# ✅ Layer 4 Engine
|
| 89 |
self.sniper = SniperEngine(models_dir=MODELS_SNIPER_DIR) if SniperEngine else None
|
| 90 |
|
| 91 |
+
# ✅ Layer 0 (Guardians)
|
| 92 |
+
self.guardian_hydra = GuardianHydra(model_dir=MODELS_HYDRA_DIR) if GuardianHydra else None
|
| 93 |
+
self.guardian_legacy = None
|
|
|
|
|
|
|
|
|
|
| 94 |
if HybridDeepSteward:
|
| 95 |
+
self.guardian_legacy = HybridDeepSteward(MODEL_V2_PATH, MODEL_V3_PATH, MODEL_V3_FEAT)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
print(f"🧠 [Processor V70.0] 5-Layer Architecture Initialized.")
|
| 98 |
|
| 99 |
async def initialize(self):
|
| 100 |
if self.initialized: return True
|
| 101 |
+
print("⚙️ [Processor] Starting Neural Grid...")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
try:
|
| 103 |
+
tasks = []
|
| 104 |
+
if self.pattern_net: tasks.append(self.pattern_net.initialize())
|
| 105 |
+
if self.oracle: tasks.append(self.oracle.initialize())
|
| 106 |
+
if self.sniper: tasks.append(self.sniper.initialize())
|
| 107 |
+
if tasks: await asyncio.gather(*tasks)
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
if self.guardian_hydra: self.guardian_hydra.initialize()
|
| 110 |
+
if self.guardian_legacy: self.guardian_legacy.initialize()
|
| 111 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
self.initialized = True
|
|
|
|
| 113 |
return True
|
|
|
|
| 114 |
except Exception as e:
|
| 115 |
+
print(f"❌ [Processor] Init Error: {e}")
|
|
|
|
|
|
|
| 116 |
return False
|
| 117 |
|
| 118 |
+
# ============================================================
|
| 119 |
+
# 🏢 LAYER 2: Pattern + Oracle + MC (The Filter)
|
| 120 |
+
# ============================================================
|
| 121 |
+
async def execute_layer2_analysis(self, raw_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
| 122 |
"""
|
| 123 |
+
Calculates the Composite Score for Layer 2.
|
| 124 |
+
Input: Symbol Data from Layer 1.
|
| 125 |
+
Output: Enriched Data with Score if passed, else None.
|
| 126 |
"""
|
| 127 |
if not self.initialized: await self.initialize()
|
| 128 |
|
| 129 |
symbol = raw_data.get('symbol')
|
| 130 |
+
ohlcv = raw_data.get('ohlcv')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
try:
|
| 133 |
+
# 1. Pattern Net Analysis (The Neural Core)
|
| 134 |
+
pattern_res = {'score': 0.0, 'probs': [0,0,0]}
|
| 135 |
+
if self.pattern_net:
|
| 136 |
+
pattern_res = await asyncio.to_thread(self.pattern_net.predict, ohlcv)
|
| 137 |
|
| 138 |
+
nn_score = pattern_res.get('score', 0.0)
|
| 139 |
+
pattern_probs = pattern_res.get('probs', [0,0,0]) # [Neutral, Loss, Win]
|
| 140 |
+
|
| 141 |
+
# 🛑 Hard Gate: Pattern Net
|
| 142 |
+
if nn_score < SystemLimits.L2_GATE_PATTERN_NET:
|
| 143 |
+
return None # REJECT immediately
|
| 144 |
+
|
| 145 |
+
# 2. Oracle Analysis (Strategic Return)
|
| 146 |
+
# We must pass 'titan_probs' key because Oracle expects it, even if we renamed variable locally
|
| 147 |
+
# or update Oracle to accept 'pattern_probs' if modified. Let's send both.
|
| 148 |
+
oracle_input = raw_data.copy()
|
| 149 |
+
oracle_input['titan_probs'] = pattern_probs
|
| 150 |
+
oracle_input['pattern_probs'] = pattern_probs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
+
oracle_res = {'oracle_score': 0.0}
|
| 153 |
+
if self.oracle:
|
| 154 |
+
oracle_res = await self.oracle.predict(oracle_input)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
+
# Oracle score is Expected Return (e.g. 0.01 for 1%). Normalize it roughly 0-1 for scoring
|
| 157 |
+
# 1% return = 1.0 score contribution (capped)
|
| 158 |
+
oracle_val = max(0.0, min(1.0, oracle_res.get('oracle_score', 0.0) * 100))
|
| 159 |
+
|
| 160 |
+
# 3. Monte Carlo (Light Check)
|
| 161 |
+
mc_val = 0.5
|
| 162 |
+
if self.mc_analyzer and '1h' in ohlcv:
|
| 163 |
+
closes = [c[4] for c in ohlcv['1h']]
|
| 164 |
+
raw_mc = self.mc_analyzer.run_light_check(closes) # -0.1 to +0.1
|
| 165 |
+
mc_val = 0.5 + (raw_mc * 5.0) # Map to 0.0-1.0
|
| 166 |
+
mc_val = max(0.0, min(1.0, mc_val))
|
| 167 |
+
|
| 168 |
+
# 4. Composite Scoring
|
| 169 |
+
# Weights: Pattern(50%) + Oracle(30%) + MC(20%)
|
| 170 |
+
composite_score = (
|
| 171 |
+
(nn_score * SystemLimits.L2_WEIGHT_PATTERN) +
|
| 172 |
+
(oracle_val * SystemLimits.L2_WEIGHT_ORACLE) +
|
| 173 |
+
(mc_val * SystemLimits.L2_WEIGHT_MC)
|
| 174 |
+
) * 100 # Scale to 0-100
|
| 175 |
+
|
| 176 |
+
if composite_score < SystemLimits.L2_MIN_COMPOSITE_SCORE:
|
| 177 |
+
return None # REJECT Weak Score
|
| 178 |
+
|
| 179 |
+
# Pass to Layer 3
|
| 180 |
+
result = raw_data.copy()
|
| 181 |
+
result.update({
|
| 182 |
+
'l2_score': composite_score,
|
| 183 |
+
'pattern_score': nn_score,
|
| 184 |
+
'oracle_score': oracle_res.get('oracle_score', 0.0),
|
| 185 |
+
'mc_score': mc_val,
|
| 186 |
+
'pattern_probs': pattern_probs
|
| 187 |
+
})
|
| 188 |
+
return result
|
| 189 |
|
| 190 |
+
except Exception as e:
|
| 191 |
+
print(f"❌ [Layer 2] Error {symbol}: {e}")
|
| 192 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
+
# ============================================================
|
| 195 |
+
# 🎯 LAYER 4: Sniper Analysis (The Executor)
|
| 196 |
+
# ============================================================
|
| 197 |
+
async def execute_layer4_sniper(self, symbol: str, ohlcv_1m: List, order_book: Dict) -> Dict[str, Any]:
|
| 198 |
+
"""
|
| 199 |
+
Runs the Sniper Engine on the Top Candidates.
|
| 200 |
+
"""
|
| 201 |
if not self.initialized: await self.initialize()
|
| 202 |
|
| 203 |
+
if not self.sniper:
|
| 204 |
+
return {'signal': 'WAIT', 'confidence_prob': 0.0, 'reason': 'No Sniper'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
+
try:
|
| 207 |
+
self.sniper.configure_settings(
|
| 208 |
+
threshold=SystemLimits.L4_ENTRY_THRESHOLD,
|
| 209 |
+
wall_ratio=0.35, # Strict wall check
|
| 210 |
+
w_ml=SystemLimits.L4_WEIGHT_ML,
|
| 211 |
+
w_ob=SystemLimits.L4_WEIGHT_OB
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
result = await self.sniper.check_entry_signal_async(ohlcv_1m, order_book, symbol=symbol)
|
| 215 |
+
return result
|
| 216 |
+
except Exception as e:
|
| 217 |
+
return {'signal': 'WAIT', 'confidence_prob': 0.0, 'reason': f"Sniper Error: {e}"}
|
| 218 |
|
| 219 |
+
# ============================================================
|
| 220 |
+
# 🛡️ Guardians (Exit Logic)
|
| 221 |
+
# ============================================================
|
| 222 |
+
def consult_guardians(self, symbol, ohlcv_1m, ohlcv_5m, ohlcv_15m, trade_context, ob_snapshot=None):
|
| 223 |
+
"""Dual-Core Guardian Logic (Hydra + Legacy)"""
|
| 224 |
+
if not self.initialized: return {'action': 'HOLD', 'reason': 'Not Init'}
|
| 225 |
|
| 226 |
+
hydra_res = {'action': 'HOLD'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
if self.guardian_hydra:
|
| 228 |
+
hydra_res = self.guardian_hydra.analyze_position(symbol, ohlcv_1m, ohlcv_5m, ohlcv_15m, trade_context)
|
| 229 |
+
|
| 230 |
+
# Prioritize Hydra
|
| 231 |
+
if hydra_res['action'] != 'HOLD':
|
| 232 |
+
return hydra_res
|
| 233 |
+
|
| 234 |
+
# Fallback to Legacy if Hydra says HOLD
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
if self.guardian_legacy:
|
| 236 |
+
legacy_res = self.guardian_legacy.analyze_position(
|
| 237 |
+
ohlcv_1m, ohlcv_5m, ohlcv_15m,
|
| 238 |
+
float(trade_context.get('entry_price', 0)),
|
| 239 |
+
order_book=ob_snapshot,
|
| 240 |
+
volume_30m_usd=trade_context.get('volume_30m_usd', 0)
|
| 241 |
+
)
|
| 242 |
+
return legacy_res
|
| 243 |
+
|
| 244 |
+
return {'action': 'HOLD', 'reason': 'Default'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|