Spaces:
Paused
Paused
Update ml_engine/processor.py
Browse files- ml_engine/processor.py +38 -84
ml_engine/processor.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
-
# ============================================================
|
| 4 |
|
| 5 |
import asyncio
|
| 6 |
import traceback
|
|
@@ -10,39 +9,21 @@ import sys
|
|
| 10 |
import numpy as np
|
| 11 |
from typing import Dict, Any, List, Optional
|
| 12 |
|
| 13 |
-
|
| 14 |
-
try:
|
| 15 |
-
from .titan_engine import TitanEngine
|
| 16 |
except ImportError: TitanEngine = None
|
| 17 |
-
|
| 18 |
-
try:
|
| 19 |
-
from .patterns import ChartPatternAnalyzer
|
| 20 |
except ImportError: ChartPatternAnalyzer = None
|
| 21 |
-
|
| 22 |
-
try:
|
| 23 |
-
from .monte_carlo import MonteCarloEngine
|
| 24 |
except ImportError: MonteCarloEngine = None
|
| 25 |
-
|
| 26 |
-
try:
|
| 27 |
-
from .oracle_engine import OracleEngine
|
| 28 |
except ImportError: OracleEngine = None
|
| 29 |
-
|
| 30 |
-
try:
|
| 31 |
-
from .sniper_engine import SniperEngine
|
| 32 |
except ImportError: SniperEngine = None
|
| 33 |
-
|
| 34 |
-
# ✅ استيراد الحارسين
|
| 35 |
-
try:
|
| 36 |
-
from .hybrid_guardian import HybridDeepSteward
|
| 37 |
except ImportError: HybridDeepSteward = None
|
| 38 |
-
|
| 39 |
-
try:
|
| 40 |
-
from .guardian_hydra import GuardianHydra
|
| 41 |
except ImportError: GuardianHydra = None
|
| 42 |
|
| 43 |
-
# ============================================================
|
| 44 |
-
# 📂 مسارات النماذج (كما هي)
|
| 45 |
-
# ============================================================
|
| 46 |
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 47 |
MODELS_L2_DIR = os.path.join(BASE_DIR, "ml_models", "layer2")
|
| 48 |
MODELS_PATTERN_DIR = os.path.join(BASE_DIR, "ml_models", "xgboost_pattern2")
|
|
@@ -53,39 +34,22 @@ MODEL_V2_PATH = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V2_Production.j
|
|
| 53 |
MODEL_V3_PATH = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V3_Production.json")
|
| 54 |
MODEL_V3_FEAT = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V3_Features.json")
|
| 55 |
|
| 56 |
-
# ============================================================
|
| 57 |
-
# 🎛️ SYSTEM LIMITS & THRESHOLDS (UPDATED)
|
| 58 |
-
# ============================================================
|
| 59 |
class SystemLimits:
|
| 60 |
-
"""GEM-Architect: The Central Constitution (Updated for Affinity Logic)."""
|
| 61 |
-
|
| 62 |
-
# --- Layer 1 (Data Manager Control) ---
|
| 63 |
-
# هذا هو المتغير الجديد الذي سيتحكم به النظام التكيفي
|
| 64 |
-
# كلما زاد الرقم، زادت صرامة الفلتر (يتطلب توافقاً أعلى مع النماذج)
|
| 65 |
L1_MIN_AFFINITY_SCORE = 10
|
| 66 |
-
|
| 67 |
-
# --- Layer 2 Weights ---
|
| 68 |
L2_WEIGHT_TITAN = 0.50
|
| 69 |
L2_WEIGHT_PATTERNS = 0.40
|
| 70 |
L2_WEIGHT_MC = 0.10
|
| 71 |
-
|
| 72 |
PATTERN_TF_WEIGHTS = {'15m': 0.40, '1h': 0.30, '5m': 0.20, '4h': 0.10, '1d': 0.00}
|
| 73 |
PATTERN_THRESH_BULLISH = 0.60
|
| 74 |
PATTERN_THRESH_BEARISH = 0.40
|
| 75 |
-
|
| 76 |
-
# --- Layer 3 ---
|
| 77 |
L3_CONFIDENCE_THRESHOLD = 0.65
|
| 78 |
L3_WHALE_IMPACT_MAX = 0.10
|
| 79 |
L3_NEWS_IMPACT_MAX = 0.05
|
| 80 |
L3_MC_ADVANCED_MAX = 0.10
|
| 81 |
-
|
| 82 |
-
# --- Layer 4 ---
|
| 83 |
L4_ENTRY_THRESHOLD = 0.30
|
| 84 |
L4_WEIGHT_ML = 0.60
|
| 85 |
L4_WEIGHT_OB = 0.40
|
| 86 |
L4_OB_WALL_RATIO = 0.40
|
| 87 |
-
|
| 88 |
-
# --- Layer 0: Hydra Thresholds ---
|
| 89 |
HYDRA_CRASH_THRESH = 0.60
|
| 90 |
HYDRA_GIVEBACK_THRESH = 0.70
|
| 91 |
HYDRA_STAGNATION_THRESH = 0.50
|
|
@@ -93,7 +57,6 @@ class SystemLimits:
|
|
| 93 |
@classmethod
|
| 94 |
def to_dict(cls) -> Dict[str, Any]:
|
| 95 |
return {k: v for k, v in cls.__dict__.items() if not k.startswith('__') and not callable(v)}
|
| 96 |
-
|
| 97 |
@classmethod
|
| 98 |
def update_from_dict(cls, config: Dict[str, Any]):
|
| 99 |
if not config: return
|
|
@@ -101,14 +64,10 @@ class SystemLimits:
|
|
| 101 |
if hasattr(cls, k): setattr(cls, k, v)
|
| 102 |
print("🔄 [SystemLimits] Config Updated.")
|
| 103 |
|
| 104 |
-
# ============================================================
|
| 105 |
-
# 🧠 MLProcessor Class (باقي الكود كما هو تماماً)
|
| 106 |
-
# ============================================================
|
| 107 |
class MLProcessor:
|
| 108 |
def __init__(self, data_manager=None):
|
| 109 |
self.data_manager = data_manager
|
| 110 |
self.initialized = False
|
| 111 |
-
|
| 112 |
self.titan = TitanEngine(model_dir=MODELS_L2_DIR) if TitanEngine else None
|
| 113 |
self.pattern_engine = ChartPatternAnalyzer(models_dir=MODELS_PATTERN_DIR) if ChartPatternAnalyzer else None
|
| 114 |
self.mc_analyzer = MonteCarloEngine() if MonteCarloEngine else None
|
|
@@ -126,12 +85,10 @@ class MLProcessor:
|
|
| 126 |
v3_model_path=MODEL_V3_PATH,
|
| 127 |
v3_features_map_path=MODEL_V3_FEAT
|
| 128 |
)
|
| 129 |
-
|
| 130 |
-
print(f"🧠 [MLProcessor V35.1] Affinity-Ready Limits Online.")
|
| 131 |
|
| 132 |
async def initialize(self):
|
| 133 |
if self.initialized: return
|
| 134 |
-
print("⚙️ [Processor] Initializing Neural Grid...")
|
| 135 |
try:
|
| 136 |
tasks = []
|
| 137 |
if self.titan: tasks.append(self.titan.initialize())
|
|
@@ -143,7 +100,6 @@ class MLProcessor:
|
|
| 143 |
tasks.append(self.oracle.initialize())
|
| 144 |
if self.sniper:
|
| 145 |
if hasattr(self.sniper, 'configure_settings'):
|
| 146 |
-
# ✅ GEM-Architect Update: Pass Weights explicitly
|
| 147 |
self.sniper.configure_settings(
|
| 148 |
threshold=SystemLimits.L4_ENTRY_THRESHOLD,
|
| 149 |
wall_ratio=SystemLimits.L4_OB_WALL_RATIO,
|
|
@@ -151,33 +107,23 @@ class MLProcessor:
|
|
| 151 |
w_ob=SystemLimits.L4_WEIGHT_OB
|
| 152 |
)
|
| 153 |
tasks.append(self.sniper.initialize())
|
| 154 |
-
|
| 155 |
if tasks: await asyncio.gather(*tasks)
|
| 156 |
|
| 157 |
if self.guardian_hydra:
|
| 158 |
self.guardian_hydra.initialize()
|
| 159 |
-
print(" 🛡️ [Guard 1] Hydra X-Ray: Active")
|
| 160 |
-
|
| 161 |
if self.guardian_legacy:
|
| 162 |
-
if asyncio.iscoroutinefunction(self.guardian_legacy.initialize):
|
| 163 |
-
|
| 164 |
-
else:
|
| 165 |
-
self.guardian_legacy.initialize()
|
| 166 |
-
print(" 🛡️ [Guard 2] Legacy Steward: Active")
|
| 167 |
|
| 168 |
self.initialized = True
|
| 169 |
-
print("✅ [Processor] All Systems Operational.")
|
| 170 |
|
| 171 |
except Exception as e:
|
| 172 |
print(f"❌ [Processor FATAL] Init failed: {e}")
|
| 173 |
traceback.print_exc()
|
| 174 |
|
| 175 |
async def process_compound_signal(self, raw_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
| 176 |
-
# (نفس المنطق السابق تماماً - لم يتغير)
|
| 177 |
if not self.initialized: await self.initialize()
|
| 178 |
-
symbol = raw_data.get('symbol')
|
| 179 |
-
ohlcv_data = raw_data.get('ohlcv')
|
| 180 |
-
current_price = raw_data.get('current_price', 0.0)
|
| 181 |
if not symbol or not ohlcv_data: return None
|
| 182 |
try:
|
| 183 |
score_titan = 0.5; titan_res = {}
|
|
@@ -198,7 +144,6 @@ class MLProcessor:
|
|
| 198 |
return {'symbol': symbol, 'current_price': current_price, 'enhanced_final_score': hybrid_score, 'titan_score': score_titan, 'patterns_score': score_patterns, 'mc_score': mc_score, 'components': {'titan_score': score_titan, 'patterns_score': score_patterns, 'mc_score': mc_score}, 'pattern_name': pattern_name, 'ohlcv': ohlcv_data, 'titan_details': titan_res, 'pattern_details': pattern_res.get('details', {})}
|
| 199 |
except Exception: return None
|
| 200 |
|
| 201 |
-
# (باقي الدوال: consult_oracle, check_sniper_entry, consult_dual_guardians, run_advanced_monte_carlo كما هي)
|
| 202 |
async def consult_oracle(self, symbol_data: Dict[str, Any]) -> Dict[str, Any]:
|
| 203 |
if not self.initialized: await self.initialize()
|
| 204 |
if self.oracle:
|
|
@@ -215,36 +160,47 @@ class MLProcessor:
|
|
| 215 |
if self.sniper: return await self.sniper.check_entry_signal_async(ohlcv_1m_data, order_book_data)
|
| 216 |
return {'signal': 'WAIT', 'reason': 'Sniper Engine Missing'}
|
| 217 |
|
| 218 |
-
|
| 219 |
-
|
| 220 |
response = {'action': 'HOLD', 'detailed_log': '', 'probs': {}}
|
|
|
|
|
|
|
| 221 |
hydra_result = {'action': 'HOLD', 'reason': 'Disabled', 'probs': {}}
|
| 222 |
if self.guardian_hydra and self.guardian_hydra.initialized:
|
| 223 |
hydra_result = self.guardian_hydra.analyze_position(symbol, ohlcv_1m, ohlcv_5m, ohlcv_15m, trade_context)
|
| 224 |
h_probs = hydra_result.get('probs', {})
|
| 225 |
-
p_crash = h_probs.get('crash', 0.0)
|
| 226 |
-
p_giveback = h_probs.get('giveback', 0.0)
|
| 227 |
if hydra_result['action'] == 'HOLD':
|
| 228 |
if p_crash >= SystemLimits.HYDRA_CRASH_THRESH:
|
| 229 |
hydra_result['action'] = 'EXIT_HARD'; hydra_result['reason'] = f"Hydra Crash Risk {p_crash:.2f}"
|
| 230 |
elif p_giveback >= SystemLimits.HYDRA_GIVEBACK_THRESH:
|
| 231 |
hydra_result['action'] = 'EXIT_SOFT'; hydra_result['reason'] = f"Hydra Giveback Risk {p_giveback:.2f}"
|
| 232 |
|
|
|
|
| 233 |
legacy_result = {'action': 'HOLD', 'reason': 'Disabled', 'scores': {}}
|
| 234 |
if self.guardian_legacy and self.guardian_legacy.initialized:
|
| 235 |
entry_price = float(trade_context.get('entry_price', 0.0))
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
| 241 |
|
| 242 |
final_action = 'HOLD'; final_reason = f"Safe. {stamp_str}"
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
elif legacy_result['action']
|
| 247 |
-
|
| 248 |
|
| 249 |
return {'action': final_action, 'reason': final_reason, 'detailed_log': f"{final_action} | {stamp_str}", 'probs': h_probs, 'scores': l_scores}
|
| 250 |
|
|
@@ -252,8 +208,6 @@ class MLProcessor:
|
|
| 252 |
if self.mc_analyzer and self.data_manager:
|
| 253 |
try:
|
| 254 |
ohlcv = await self.data_manager.get_latest_ohlcv(symbol, timeframe, limit=300)
|
| 255 |
-
if ohlcv:
|
| 256 |
-
closes = [c[4] for c in ohlcv]
|
| 257 |
-
return self.mc_analyzer.run_advanced_simulation(closes)
|
| 258 |
except Exception: pass
|
| 259 |
return 0.0
|
|
|
|
| 1 |
+
# ml_engine/processor.py
|
| 2 |
+
# (V35.2 - GEM-Architect: Volume Flow Aware)
|
|
|
|
| 3 |
|
| 4 |
import asyncio
|
| 5 |
import traceback
|
|
|
|
| 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
|
|
|
|
|
|
|
| 15 |
except ImportError: ChartPatternAnalyzer = None
|
| 16 |
+
try: from .monte_carlo import MonteCarloEngine
|
|
|
|
|
|
|
| 17 |
except ImportError: MonteCarloEngine = None
|
| 18 |
+
try: from .oracle_engine import OracleEngine
|
|
|
|
|
|
|
| 19 |
except ImportError: OracleEngine = None
|
| 20 |
+
try: from .sniper_engine import SniperEngine
|
|
|
|
|
|
|
| 21 |
except ImportError: SniperEngine = None
|
| 22 |
+
try: from .hybrid_guardian import HybridDeepSteward
|
|
|
|
|
|
|
|
|
|
| 23 |
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 |
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
|
|
|
|
| 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 |
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 |
v3_model_path=MODEL_V3_PATH,
|
| 86 |
v3_features_map_path=MODEL_V3_FEAT
|
| 87 |
)
|
| 88 |
+
print(f"🧠 [MLProcessor V35.2] 30m-Depth Logic Ready.")
|
|
|
|
| 89 |
|
| 90 |
async def initialize(self):
|
| 91 |
if self.initialized: return
|
|
|
|
| 92 |
try:
|
| 93 |
tasks = []
|
| 94 |
if self.titan: tasks.append(self.titan.initialize())
|
|
|
|
| 100 |
tasks.append(self.oracle.initialize())
|
| 101 |
if self.sniper:
|
| 102 |
if hasattr(self.sniper, 'configure_settings'):
|
|
|
|
| 103 |
self.sniper.configure_settings(
|
| 104 |
threshold=SystemLimits.L4_ENTRY_THRESHOLD,
|
| 105 |
wall_ratio=SystemLimits.L4_OB_WALL_RATIO,
|
|
|
|
| 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): await self.guardian_legacy.initialize()
|
| 116 |
+
else: self.guardian_legacy.initialize()
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
self.initialized = True
|
|
|
|
| 119 |
|
| 120 |
except Exception as e:
|
| 121 |
print(f"❌ [Processor FATAL] Init failed: {e}")
|
| 122 |
traceback.print_exc()
|
| 123 |
|
| 124 |
async def process_compound_signal(self, raw_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
|
|
| 125 |
if not self.initialized: await self.initialize()
|
| 126 |
+
symbol = raw_data.get('symbol'); ohlcv_data = raw_data.get('ohlcv'); current_price = raw_data.get('current_price', 0.0)
|
|
|
|
|
|
|
| 127 |
if not symbol or not ohlcv_data: return None
|
| 128 |
try:
|
| 129 |
score_titan = 0.5; titan_res = {}
|
|
|
|
| 144 |
return {'symbol': symbol, 'current_price': current_price, 'enhanced_final_score': hybrid_score, 'titan_score': score_titan, 'patterns_score': score_patterns, 'mc_score': mc_score, 'components': {'titan_score': score_titan, 'patterns_score': score_patterns, 'mc_score': mc_score}, 'pattern_name': pattern_name, 'ohlcv': ohlcv_data, 'titan_details': titan_res, 'pattern_details': pattern_res.get('details', {})}
|
| 145 |
except Exception: return None
|
| 146 |
|
|
|
|
| 147 |
async def consult_oracle(self, symbol_data: Dict[str, Any]) -> Dict[str, Any]:
|
| 148 |
if not self.initialized: await self.initialize()
|
| 149 |
if self.oracle:
|
|
|
|
| 160 |
if self.sniper: return await self.sniper.check_entry_signal_async(ohlcv_1m_data, order_book_data)
|
| 161 |
return {'signal': 'WAIT', 'reason': 'Sniper Engine Missing'}
|
| 162 |
|
| 163 |
+
# ✅ GEM-Architect Update: Now accepts volume_30m from context
|
| 164 |
+
def consult_dual_guardians(self, symbol, ohlcv_1m, ohlcv_5m, ohlcv_15m, trade_context, order_book_snapshot=None):
|
| 165 |
response = {'action': 'HOLD', 'detailed_log': '', 'probs': {}}
|
| 166 |
+
|
| 167 |
+
# 1. Hydra (Unchanged)
|
| 168 |
hydra_result = {'action': 'HOLD', 'reason': 'Disabled', 'probs': {}}
|
| 169 |
if self.guardian_hydra and self.guardian_hydra.initialized:
|
| 170 |
hydra_result = self.guardian_hydra.analyze_position(symbol, ohlcv_1m, ohlcv_5m, ohlcv_15m, trade_context)
|
| 171 |
h_probs = hydra_result.get('probs', {})
|
| 172 |
+
p_crash = h_probs.get('crash', 0.0); p_giveback = h_probs.get('giveback', 0.0)
|
|
|
|
| 173 |
if hydra_result['action'] == 'HOLD':
|
| 174 |
if p_crash >= SystemLimits.HYDRA_CRASH_THRESH:
|
| 175 |
hydra_result['action'] = 'EXIT_HARD'; hydra_result['reason'] = f"Hydra Crash Risk {p_crash:.2f}"
|
| 176 |
elif p_giveback >= SystemLimits.HYDRA_GIVEBACK_THRESH:
|
| 177 |
hydra_result['action'] = 'EXIT_SOFT'; hydra_result['reason'] = f"Hydra Giveback Risk {p_giveback:.2f}"
|
| 178 |
|
| 179 |
+
# 2. Legacy (Volume-Aware Veto)
|
| 180 |
legacy_result = {'action': 'HOLD', 'reason': 'Disabled', 'scores': {}}
|
| 181 |
if self.guardian_legacy and self.guardian_legacy.initialized:
|
| 182 |
entry_price = float(trade_context.get('entry_price', 0.0))
|
| 183 |
+
# Extract 30m Volume from Context
|
| 184 |
+
vol_30m = trade_context.get('volume_30m_usd', 0.0)
|
| 185 |
+
|
| 186 |
+
legacy_result = self.guardian_legacy.analyze_position(
|
| 187 |
+
ohlcv_1m, ohlcv_5m, ohlcv_15m, entry_price,
|
| 188 |
+
order_book=order_book_snapshot,
|
| 189 |
+
volume_30m_usd=vol_30m
|
| 190 |
+
)
|
| 191 |
|
| 192 |
+
# 3. Final Arbitration
|
| 193 |
+
h_probs = hydra_result.get('probs', {}); l_scores = legacy_result.get('scores', {})
|
| 194 |
+
h_c = h_probs.get('crash', 0.0); h_g = h_probs.get('giveback', 0.0)
|
| 195 |
+
l_v2 = l_scores.get('v2', 0.0); l_v3 = l_scores.get('v3', 0.0)
|
| 196 |
+
stamp_str = f"🐲[C:{h_c:.0%}|G:{h_g:.0%}] 🕸️[V2:{l_v2:.0%}|V3:{l_v3:.0%}]"
|
| 197 |
|
| 198 |
final_action = 'HOLD'; final_reason = f"Safe. {stamp_str}"
|
| 199 |
+
|
| 200 |
+
if hydra_result['action'] in ['EXIT_HARD', 'EXIT_SOFT', 'TIGHTEN_SL', 'TRAIL_SL']:
|
| 201 |
+
final_action = hydra_result['action']; final_reason = f"🐲 HYDRA: {hydra_result['reason']} | {stamp_str}"
|
| 202 |
+
elif legacy_result['action'] in ['EXIT_HARD', 'EXIT_SOFT']:
|
| 203 |
+
final_action = legacy_result['action']; final_reason = f"🕸️ LEGACY: {legacy_result['reason']} | {stamp_str}"
|
| 204 |
|
| 205 |
return {'action': final_action, 'reason': final_reason, 'detailed_log': f"{final_action} | {stamp_str}", 'probs': h_probs, 'scores': l_scores}
|
| 206 |
|
|
|
|
| 208 |
if self.mc_analyzer and self.data_manager:
|
| 209 |
try:
|
| 210 |
ohlcv = await self.data_manager.get_latest_ohlcv(symbol, timeframe, limit=300)
|
| 211 |
+
if ohlcv: return self.mc_analyzer.run_advanced_simulation([c[4] for c in ohlcv])
|
|
|
|
|
|
|
| 212 |
except Exception: pass
|
| 213 |
return 0.0
|