Riy777 commited on
Commit
3bc03f3
·
verified ·
1 Parent(s): ef7928c

Upload 2 files

Browse files
ml_engine/processor (71) (1).py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # 🧠 ml_engine/processor.py
3
+ # (V66.0 - GEM-Architect: Direct Context Injection Fixed)
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 .titan_engine import TitanEngine
16
+ except ImportError: TitanEngine = None
17
+ try: from .patterns import ChartPatternAnalyzer
18
+ except ImportError: ChartPatternAnalyzer = None
19
+ try: from .monte_carlo import MonteCarloEngine
20
+ except ImportError: MonteCarloEngine = None
21
+ try: from .oracle_engine import OracleEngine
22
+ except ImportError: OracleEngine = None
23
+ try: from .sniper_engine import SniperEngine
24
+ except ImportError: SniperEngine = None
25
+ try: from .hybrid_guardian import HybridDeepSteward
26
+ except ImportError: HybridDeepSteward = None
27
+ try: from .guardian_hydra import GuardianHydra
28
+ except ImportError: GuardianHydra = None
29
+
30
+ # ============================================================
31
+ # 📂 مسارات النماذج
32
+ # ============================================================
33
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
34
+ MODELS_L2_DIR = os.path.join(BASE_DIR, "ml_models", "layer2")
35
+ MODELS_PATTERN_DIR = os.path.join(BASE_DIR, "ml_models", "xgboost_pattern2")
36
+ MODELS_UNIFIED_DIR = os.path.join(BASE_DIR, "ml_models", "Unified_Models_V1")
37
+ MODELS_SNIPER_DIR = os.path.join(BASE_DIR, "ml_models", "guard_v2")
38
+ MODELS_HYDRA_DIR = os.path.join(BASE_DIR, "ml_models", "guard_v1")
39
+ MODEL_V2_PATH = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V2_Production.json")
40
+ MODEL_V3_PATH = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V3_Production.json")
41
+ MODEL_V3_FEAT = os.path.join(BASE_DIR, "ml_models", "DeepSteward_V3_Features.json")
42
+
43
+ # ============================================================
44
+ # 🎛️ SYSTEM LIMITS (Fallback Only)
45
+ # ============================================================
46
+ class SystemLimits:
47
+ """
48
+ GEM-Architect: Fallback Values.
49
+ The real values are now injected dynamically via 'dynamic_limits' per Coin Type.
50
+ """
51
+
52
+ # --- Layer 1 ---
53
+ L1_MIN_AFFINITY_SCORE = 15.0
54
+
55
+ # --- Layer 2 Weights ---
56
+ L2_WEIGHT_TITAN = 0.40
57
+ L2_WEIGHT_PATTERNS = 0.30
58
+ L2_WEIGHT_MC = 0.10
59
+
60
+ # Pattern Config
61
+ PATTERN_TF_WEIGHTS = {'15m': 0.40, '1h': 0.30, '5m': 0.20, '4h': 0.10, '1d': 0.00}
62
+ PATTERN_THRESH_BULLISH = 0.60
63
+ PATTERN_THRESH_BEARISH = 0.40
64
+
65
+ # --- Layer 3 ---
66
+ L3_CONFIDENCE_THRESHOLD = 0.65
67
+ L3_WHALE_IMPACT_MAX = 0.10
68
+ L3_NEWS_IMPACT_MAX = 0.05
69
+ L3_MC_ADVANCED_MAX = 0.10
70
+
71
+ # --- Layer 4 ---
72
+ L4_ENTRY_THRESHOLD = 0.40
73
+ L4_WEIGHT_ML = 0.60
74
+ L4_WEIGHT_OB = 0.40
75
+ L4_OB_WALL_RATIO = 0.40
76
+
77
+ # --- Layer 0: Hydra & Guardian Defaults ---
78
+ HYDRA_CRASH_THRESH = 0.85
79
+ HYDRA_GIVEBACK_THRESH = 0.85
80
+ HYDRA_STAGNATION_THRESH = 0.80
81
+
82
+ LEGACY_V2_PANIC_THRESH = 0.95
83
+ LEGACY_V3_HARD_THRESH = 0.95
84
+ LEGACY_V3_SOFT_THRESH = 0.88
85
+ LEGACY_V3_ULTRA_THRESH = 0.99
86
+
87
+ @classmethod
88
+ def to_dict(cls) -> Dict[str, Any]:
89
+ return {k: v for k, v in cls.__dict__.items() if not k.startswith('__') and not callable(v)}
90
+
91
+ # ============================================================
92
+ # 🧠 MLProcessor Class
93
+ # ============================================================
94
+ class MLProcessor:
95
+ def __init__(self, data_manager=None):
96
+ self.data_manager = data_manager
97
+ self.initialized = False
98
+
99
+ self.titan = TitanEngine(model_dir=MODELS_L2_DIR) if TitanEngine else None
100
+ self.pattern_engine = ChartPatternAnalyzer(models_dir=MODELS_PATTERN_DIR) if ChartPatternAnalyzer else None
101
+ self.mc_analyzer = MonteCarloEngine() if MonteCarloEngine else None
102
+ self.oracle = OracleEngine(model_dir=MODELS_UNIFIED_DIR) if OracleEngine else None
103
+ self.sniper = SniperEngine(models_dir=MODELS_SNIPER_DIR) if SniperEngine else None
104
+
105
+ self.guardian_hydra = None
106
+ if GuardianHydra:
107
+ self.guardian_hydra = GuardianHydra(model_dir=MODELS_HYDRA_DIR)
108
+
109
+ self.guardian_legacy = None
110
+ if HybridDeepSteward:
111
+ self.guardian_legacy = HybridDeepSteward(
112
+ v2_model_path=MODEL_V2_PATH,
113
+ v3_model_path=MODEL_V3_PATH,
114
+ v3_features_map_path=MODEL_V3_FEAT
115
+ )
116
+
117
+ print(f"🧠 [MLProcessor V66.0] Context-Aware Injection Active.")
118
+
119
+ async def initialize(self):
120
+ if self.initialized: return
121
+ print("⚙️ [Processor] Initializing Neural Grid...")
122
+ try:
123
+ tasks = []
124
+ if self.titan: tasks.append(self.titan.initialize())
125
+
126
+ if self.pattern_engine:
127
+ self.pattern_engine.configure_thresholds(
128
+ weights=SystemLimits.PATTERN_TF_WEIGHTS,
129
+ bull_thresh=SystemLimits.PATTERN_THRESH_BULLISH,
130
+ bear_thresh=SystemLimits.PATTERN_THRESH_BEARISH
131
+ )
132
+ tasks.append(self.pattern_engine.initialize())
133
+
134
+ if self.oracle:
135
+ if hasattr(self.oracle, 'set_threshold'):
136
+ self.oracle.set_threshold(SystemLimits.L3_CONFIDENCE_THRESHOLD)
137
+ tasks.append(self.oracle.initialize())
138
+
139
+ if self.sniper:
140
+ if hasattr(self.sniper, 'configure_settings'):
141
+ self.sniper.configure_settings(
142
+ threshold=SystemLimits.L4_ENTRY_THRESHOLD,
143
+ wall_ratio=SystemLimits.L4_OB_WALL_RATIO,
144
+ w_ml=SystemLimits.L4_WEIGHT_ML,
145
+ w_ob=SystemLimits.L4_WEIGHT_OB
146
+ )
147
+ tasks.append(self.sniper.initialize())
148
+
149
+ if tasks: await asyncio.gather(*tasks)
150
+
151
+ if self.guardian_hydra:
152
+ self.guardian_hydra.initialize()
153
+ print(" 🛡️ [Guard 1] Hydra X-Ray: Active")
154
+
155
+ if self.guardian_legacy:
156
+ if asyncio.iscoroutinefunction(self.guardian_legacy.initialize):
157
+ await self.guardian_legacy.initialize()
158
+ else:
159
+ self.guardian_legacy.initialize()
160
+
161
+ # Default init
162
+ self.guardian_legacy.configure_thresholds(
163
+ v2_panic=SystemLimits.LEGACY_V2_PANIC_THRESH,
164
+ v3_hard=SystemLimits.LEGACY_V3_HARD_THRESH,
165
+ v3_soft=SystemLimits.LEGACY_V3_SOFT_THRESH,
166
+ v3_ultra=SystemLimits.LEGACY_V3_ULTRA_THRESH
167
+ )
168
+ print(f" 🛡️ [Guard 2] Legacy Steward: Active")
169
+
170
+ self.initialized = True
171
+ print("✅ [Processor] All Systems Operational.")
172
+
173
+ except Exception as e:
174
+ print(f"❌ [Processor FATAL] Init failed: {e}")
175
+ traceback.print_exc()
176
+
177
+ async def process_compound_signal(self, raw_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
178
+ """
179
+ L2 Processing with Dynamic Weight Injection
180
+ """
181
+ if not self.initialized: await self.initialize()
182
+
183
+ symbol = raw_data.get('symbol')
184
+ ohlcv_data = raw_data.get('ohlcv')
185
+ current_price = raw_data.get('current_price', 0.0)
186
+
187
+ # ✅ الحقن المباشر للقيم
188
+ limits = raw_data.get('dynamic_limits', {})
189
+
190
+ if not symbol or not ohlcv_data: return None
191
+
192
+ try:
193
+ # 1. Titan
194
+ score_titan = 0.5
195
+ titan_res = {}
196
+ if self.titan:
197
+ titan_res = await asyncio.to_thread(self.titan.predict, ohlcv_data)
198
+ score_titan = titan_res.get('score', 0.5)
199
+
200
+ # 2. Pattern
201
+ score_patterns = 0.5
202
+ pattern_res = {}
203
+ pattern_name = "Neutral"
204
+ if self.pattern_engine:
205
+ pattern_res = await self.pattern_engine.detect_chart_patterns(ohlcv_data)
206
+ score_patterns = pattern_res.get('pattern_confidence', 0.5)
207
+ pattern_name = pattern_res.get('pattern_detected', 'Neutral')
208
+
209
+ # 3. MC
210
+ mc_score = 0.5
211
+ if self.mc_analyzer and '1h' in ohlcv_data:
212
+ closes = [c[4] for c in ohlcv_data['1h']]
213
+ raw_mc = self.mc_analyzer.run_light_check(closes)
214
+ mc_score = 0.5 + (raw_mc * 5.0)
215
+ mc_score = max(0.0, min(1.0, mc_score))
216
+
217
+ # 4. Hybrid Calc (Dynamic Injection)
218
+ w_titan = limits.get('w_titan', SystemLimits.L2_WEIGHT_TITAN)
219
+ w_patt = limits.get('w_patt', SystemLimits.L2_WEIGHT_PATTERNS)
220
+ w_mc = SystemLimits.L2_WEIGHT_MC
221
+
222
+ total_w = w_titan + w_patt + w_mc
223
+ if total_w <= 0: total_w = 1.0
224
+
225
+ hybrid_score = ((score_titan * w_titan) + (score_patterns * w_patt) + (mc_score * w_mc)) / total_w
226
+
227
+ return {
228
+ 'symbol': symbol,
229
+ 'current_price': current_price,
230
+ 'enhanced_final_score': hybrid_score,
231
+ 'dynamic_limits': limits, # تمرير الحدود للطبقات التالية
232
+ 'asset_regime': raw_data.get('asset_regime', 'UNKNOWN'),
233
+ 'strategy_type': raw_data.get('strategy_type', 'NORMAL'),
234
+ 'titan_score': score_titan,
235
+ 'patterns_score': score_patterns,
236
+ 'mc_score': mc_score,
237
+ 'components': {
238
+ 'titan_score': score_titan,
239
+ 'patterns_score': score_patterns,
240
+ 'mc_score': mc_score
241
+ },
242
+ 'pattern_name': pattern_name,
243
+ 'ohlcv': ohlcv_data,
244
+ 'titan_details': titan_res,
245
+ 'pattern_details': pattern_res.get('details', {})
246
+ }
247
+ except Exception as e:
248
+ print(f"❌ [Processor] Error processing {symbol}: {e}")
249
+ return None
250
+
251
+ async def consult_oracle(self, symbol_data: Dict[str, Any]) -> Dict[str, Any]:
252
+ if not self.initialized: await self.initialize()
253
+
254
+ # ✅ الحقن المباشر للعتبة
255
+ limits = symbol_data.get('dynamic_limits', {})
256
+ threshold = limits.get('l3_oracle_thresh', SystemLimits.L3_CONFIDENCE_THRESHOLD)
257
+
258
+ if self.oracle:
259
+ if hasattr(self.oracle, 'set_threshold'):
260
+ self.oracle.set_threshold(threshold)
261
+
262
+ decision = await self.oracle.predict(symbol_data)
263
+ conf = decision.get('confidence', 0.0)
264
+
265
+ if decision.get('action') in ['WATCH', 'BUY'] and conf < threshold:
266
+ decision['action'] = 'WAIT'
267
+ decision['reason'] = f"Context Veto: Conf {conf:.2f} < Limit {threshold:.2f}"
268
+
269
+ return decision
270
+ return {'action': 'WAIT', 'reason': 'Oracle Engine Missing'}
271
+
272
+ async def check_sniper_entry(self, ohlcv_1m_data: List, order_book_data: Dict[str, Any], context_data: Dict = None) -> Dict[str, Any]:
273
+ if not self.initialized: await self.initialize()
274
+
275
+ # ✅ الحقن المباشر
276
+ limits = context_data.get('dynamic_limits', {}) if context_data else {}
277
+
278
+ thresh = limits.get('l4_sniper_thresh', SystemLimits.L4_ENTRY_THRESHOLD)
279
+ wall_r = limits.get('l4_ob_wall_ratio', SystemLimits.L4_OB_WALL_RATIO)
280
+
281
+ if self.sniper:
282
+ if hasattr(self.sniper, 'configure_settings'):
283
+ self.sniper.configure_settings(
284
+ threshold=thresh,
285
+ wall_ratio=wall_r,
286
+ w_ml=SystemLimits.L4_WEIGHT_ML,
287
+ w_ob=SystemLimits.L4_WEIGHT_OB
288
+ )
289
+ return await self.sniper.check_entry_signal_async(ohlcv_1m_data, order_book_data)
290
+
291
+ return {'signal': 'WAIT', 'reason': 'Sniper Engine Missing'}
292
+
293
+ def consult_dual_guardians(self, symbol, ohlcv_1m, ohlcv_5m, ohlcv_15m, trade_context, order_book_snapshot=None):
294
+ """
295
+ 💎 GEM-Architect: الحقن المباشر لعتبات الحراس من سياق الصفقة
296
+ يضمن أن كل نوع عملة يتم حمايته بالعتبات الخاصة به (High Precision)
297
+ """
298
+ response = {'action': 'HOLD', 'detailed_log': '', 'probs': {}}
299
+
300
+ # 1. استخراج الحدود الديناميكية من سياق الصفقة
301
+ # trade_context يمرر من TradeManager ويحتوي على dynamic_limits
302
+ limits = trade_context.get('dynamic_limits', {})
303
+
304
+ # ✅ سحب القيم مع Fallback آمن
305
+ h_crash_thresh = limits.get('hydra_crash', SystemLimits.HYDRA_CRASH_THRESH)
306
+ h_giveback_thresh = limits.get('hydra_giveback', SystemLimits.HYDRA_GIVEBACK_THRESH)
307
+ h_stag_thresh = limits.get('hydra_stagnation', SystemLimits.HYDRA_STAGNATION_THRESH)
308
+
309
+ l_v2_thresh = limits.get('legacy_v2', SystemLimits.LEGACY_V2_PANIC_THRESH)
310
+ l_v3_hard = limits.get('legacy_v3_hard', SystemLimits.LEGACY_V3_HARD_THRESH)
311
+ l_v3_soft = limits.get('legacy_v3_soft', SystemLimits.LEGACY_V3_SOFT_THRESH)
312
+ l_v3_ultra = limits.get('legacy_v3_ultra', SystemLimits.LEGACY_V3_ULTRA_THRESH)
313
+
314
+ # -----------------------------------------------
315
+ # 1. Hydra Execution
316
+ # -----------------------------------------------
317
+ hydra_result = {'action': 'HOLD', 'reason': 'Disabled', 'probs': {}}
318
+ if self.guardian_hydra and self.guardian_hydra.initialized:
319
+ hydra_result = self.guardian_hydra.analyze_position(symbol, ohlcv_1m, ohlcv_5m, ohlcv_15m, trade_context)
320
+ h_probs = hydra_result.get('probs', {})
321
+
322
+ p_crash = h_probs.get('crash', 0.0)
323
+ p_giveback = h_probs.get('giveback', 0.0)
324
+
325
+ # 🔥 استخدام العتبات المحقونة
326
+ if hydra_result['action'] == 'HOLD':
327
+ if p_crash >= h_crash_thresh:
328
+ hydra_result['action'] = 'EXIT_HARD'
329
+ hydra_result['reason'] = f"Hydra Crash Risk {p_crash:.2f} >= {h_crash_thresh}"
330
+ elif p_giveback >= h_giveback_thresh:
331
+ hydra_result['action'] = 'EXIT_SOFT'
332
+ hydra_result['reason'] = f"Hydra Giveback Risk {p_giveback:.2f} >= {h_giveback_thresh}"
333
+
334
+ # -----------------------------------------------
335
+ # 2. Legacy Execution
336
+ # -----------------------------------------------
337
+ legacy_result = {'action': 'HOLD', 'reason': 'Disabled', 'scores': {}}
338
+ if self.guardian_legacy and self.guardian_legacy.initialized:
339
+ # 🔥 حقن الإعدادات ديناميكياً قبل التشغيل
340
+ self.guardian_legacy.configure_thresholds(
341
+ v2_panic=l_v2_thresh,
342
+ v3_hard=l_v3_hard,
343
+ v3_soft=l_v3_soft,
344
+ v3_ultra=l_v3_ultra
345
+ )
346
+
347
+ entry_price = float(trade_context.get('entry_price', 0.0))
348
+ vol_30m = trade_context.get('volume_30m_usd', 0.0)
349
+
350
+ legacy_result = self.guardian_legacy.analyze_position(
351
+ ohlcv_1m, ohlcv_5m, ohlcv_15m, entry_price,
352
+ order_book=order_book_snapshot,
353
+ volume_30m_usd=vol_30m
354
+ )
355
+
356
+ # -----------------------------------------------
357
+ # 3. Final Arbitration
358
+ # -----------------------------------------------
359
+ h_probs = hydra_result.get('probs', {})
360
+ l_scores = legacy_result.get('scores', {})
361
+
362
+ h_c = h_probs.get('crash', 0.0)
363
+ h_g = h_probs.get('giveback', 0.0)
364
+ h_s = h_probs.get('stagnation', 0.0)
365
+ l_v2 = l_scores.get('v2', 0.0)
366
+ l_v3 = l_scores.get('v3', 0.0)
367
+
368
+ stamp_str = f"🐲[C:{h_c:.0%}|G:{h_g:.0%}] 🕸️[V2:{l_v2:.0%}]"
369
+
370
+ final_action = 'HOLD'
371
+ final_reason = f"Safe. {stamp_str}"
372
+
373
+ if hydra_result['action'] in ['EXIT_HARD', 'EXIT_SOFT', 'TIGHTEN_SL', 'TRAIL_SL']:
374
+ final_action = hydra_result['action']
375
+ final_reason = f"🐲 HYDRA: {hydra_result['reason']}"
376
+ elif legacy_result['action'] in ['EXIT_HARD', 'EXIT_SOFT']:
377
+ final_action = legacy_result['action']
378
+ final_reason = f"🕸️ LEGACY: {legacy_result['reason']}"
379
+
380
+ return {
381
+ 'action': final_action,
382
+ 'reason': final_reason,
383
+ 'detailed_log': f"{final_action} | {stamp_str}",
384
+ 'probs': h_probs,
385
+ 'scores': l_scores
386
+ }
387
+
388
+ async def run_advanced_monte_carlo(self, symbol, timeframe='1h'):
389
+ if self.mc_analyzer and self.data_manager:
390
+ try:
391
+ ohlcv = await self.data_manager.get_latest_ohlcv(symbol, timeframe, limit=300)
392
+ if ohlcv: return self.mc_analyzer.run_advanced_simulation([c[4] for c in ohlcv])
393
+ except Exception: pass
394
+ return 0.0
ml_engine/sniper_engine (17) (1).py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # 🎯 ml_engine/sniper_engine.py
3
+ # (V2.0 - GEM-Architect: Weighted Depth & Smart Microstructure)
4
+ # ============================================================
5
+
6
+ import os
7
+ import time
8
+ import numpy as np
9
+ import pandas as pd
10
+ import pandas_ta as ta
11
+ import lightgbm as lgb
12
+ import traceback
13
+ from typing import List, Dict, Any, Optional
14
+
15
+ N_SPLITS = 5
16
+ LOOKBACK_WINDOW = 500
17
+
18
+ # ============================================================
19
+ # 🔧 1. Feature Engineering (Standard + Liquidity Proxies)
20
+ # ============================================================
21
+
22
+ def _z_score_rolling(x, w=500):
23
+ r = x.rolling(w).mean()
24
+ s = x.rolling(w).std().replace(0, np.nan)
25
+ z = (x - r) / s
26
+ return z.fillna(0)
27
+
28
+ def _add_liquidity_proxies(df):
29
+ """حساب مؤشرات السيولة المتقدمة (Amihud, VPIN, OFI, etc.)"""
30
+ df_proxy = df.copy()
31
+ if 'datetime' not in df_proxy.index:
32
+ if 'timestamp' in df_proxy.columns:
33
+ df_proxy['datetime'] = pd.to_datetime(df_proxy['timestamp'], unit='ms')
34
+ df_proxy = df_proxy.set_index('datetime')
35
+
36
+ df_proxy['ret'] = df_proxy['close'].pct_change().fillna(0)
37
+ df_proxy['dollar_vol'] = df_proxy['close'] * df_proxy['volume']
38
+
39
+ # Amihud Illiquidity Ratio
40
+ df_proxy['amihud'] = (df_proxy['ret'].abs() / df_proxy['dollar_vol'].replace(0, np.nan)).fillna(np.inf)
41
+
42
+ # Roll Spread Proxy
43
+ dp = df_proxy['close'].diff()
44
+ roll_cov = dp.rolling(64).cov(dp.shift(1))
45
+ df_proxy['roll_spread'] = (2 * np.sqrt(np.maximum(0, -roll_cov))).bfill()
46
+
47
+ # Order Flow Imbalance (Volume-based proxy)
48
+ sign = np.sign(df_proxy['close'].diff()).fillna(0)
49
+ df_proxy['signed_vol'] = sign * df_proxy['volume']
50
+ df_proxy['ofi'] = df_proxy['signed_vol'].rolling(30).sum().fillna(0)
51
+
52
+ # VPIN-like Imbalance
53
+ buy_vol = (sign > 0) * df_proxy['volume']
54
+ sell_vol = (sign < 0) * df_proxy['volume']
55
+ imb = (buy_vol.rolling(60).sum() - sell_vol.rolling(60).sum()).abs()
56
+ tot = df_proxy['volume'].rolling(60).sum()
57
+ df_proxy['vpin'] = (imb / tot.replace(0, np.nan)).fillna(0)
58
+
59
+ # Volatility Estimator (Garman-Klass)
60
+ df_proxy['rv_gk'] = (np.log(df_proxy['high'] / df_proxy['low'])**2) / 2 - \
61
+ (2 * np.log(2) - 1) * (np.log(df_proxy['close'] / df_proxy['open'])**2)
62
+
63
+ # VWAP Deviation
64
+ vwap_window = 20
65
+ df_proxy['vwap'] = (df_proxy['close'] * df_proxy['volume']).rolling(vwap_window).sum() / \
66
+ df_proxy['volume'].rolling(vwap_window).sum()
67
+ df_proxy['vwap_dev'] = (df_proxy['close'] - df_proxy['vwap']).fillna(0)
68
+
69
+ # Composite Liquidity Score
70
+ df_proxy['L_score'] = (
71
+ _z_score_rolling(df_proxy['volume']) +
72
+ _z_score_rolling(1 / df_proxy['amihud'].replace(np.inf, np.nan)) +
73
+ _z_score_rolling(-df_proxy['roll_spread']) +
74
+ _z_score_rolling(-df_proxy['rv_gk'].abs()) +
75
+ _z_score_rolling(-df_proxy['vwap_dev'].abs()) +
76
+ _z_score_rolling(df_proxy['ofi'])
77
+ )
78
+ return df_proxy
79
+
80
+ def _add_standard_features(df):
81
+ """المؤشرات الفنية القياسية"""
82
+ df_feat = df.copy()
83
+
84
+ df_feat['return_1m'] = df_feat['close'].pct_change(1)
85
+ df_feat['return_3m'] = df_feat['close'].pct_change(3)
86
+ df_feat['return_5m'] = df_feat['close'].pct_change(5)
87
+ df_feat['return_15m'] = df_feat['close'].pct_change(15)
88
+
89
+ df_feat['rsi_14'] = ta.rsi(df_feat['close'], length=14)
90
+
91
+ ema_9 = ta.ema(df_feat['close'], length=9)
92
+ ema_21 = ta.ema(df_feat['close'], length=21)
93
+
94
+ if ema_9 is not None:
95
+ df_feat['ema_9_slope'] = (ema_9 - ema_9.shift(1)) / ema_9.shift(1)
96
+ else:
97
+ df_feat['ema_9_slope'] = 0
98
+
99
+ if ema_21 is not None:
100
+ df_feat['ema_21_dist'] = (df_feat['close'] - ema_21) / ema_21
101
+ else:
102
+ df_feat['ema_21_dist'] = 0
103
+
104
+ df_feat['atr'] = ta.atr(df_feat['high'], df_feat['low'], df_feat['close'], length=100)
105
+ df_feat['vol_zscore_50'] = _z_score_rolling(df_feat['volume'], w=50)
106
+
107
+ df_feat['candle_range'] = df_feat['high'] - df_feat['low']
108
+ df_feat['close_pos_in_range'] = (df_feat['close'] - df_feat['low']) / (df_feat['candle_range'].replace(0, np.nan))
109
+
110
+ return df_feat
111
+
112
+ # ============================================================
113
+ # 🎯 2. SniperEngine Class (Refactored)
114
+ # ============================================================
115
+
116
+ class SniperEngine:
117
+
118
+ def __init__(self, models_dir: str):
119
+ self.models_dir = models_dir
120
+ self.models: List[lgb.Booster] = []
121
+ self.feature_names: List[str] = []
122
+
123
+ # --- Configurable Thresholds (Defaults) ---
124
+ self.entry_threshold = 0.40
125
+ self.wall_ratio_limit = 0.40 # Veto threshold for sell wall
126
+ self.weight_ml = 0.60
127
+ self.weight_ob = 0.40
128
+
129
+ # --- Advanced OB Settings (New in V2.0) ---
130
+ self.ob_depth_decay = 0.15 # Decay factor for weighted depth
131
+ self.max_wall_dist = 0.005 # 0.5% max distance to consider a wall
132
+ self.max_spread_pct = 0.002 # 0.2% max spread allowed
133
+ self.spoof_patience = 0 # How many previous checks to ignore a new wall (0 = Instant Veto)
134
+
135
+ self.initialized = False
136
+ self.LOOKBACK_WINDOW = LOOKBACK_WINDOW
137
+ self.ORDER_BOOK_DEPTH = 20
138
+
139
+ # --- Persistence Cache for Anti-Spoofing ---
140
+ # Format: {symbol: {'last_check': timestamp, 'wall_counter': int}}
141
+ self._wall_cache = {}
142
+
143
+ print("🎯 [SniperEngine V2.0] Weighted Depth & Smart Microstructure Ready.")
144
+
145
+ def configure_settings(self,
146
+ threshold: float,
147
+ wall_ratio: float,
148
+ w_ml: float = 0.60,
149
+ w_ob: float = 0.40,
150
+ max_wall_dist: float = 0.005,
151
+ max_spread: float = 0.002):
152
+ """Dynamic configuration injection"""
153
+ self.entry_threshold = threshold
154
+ self.wall_ratio_limit = wall_ratio
155
+ self.weight_ml = w_ml
156
+ self.weight_ob = w_ob
157
+ self.max_wall_dist = max_wall_dist
158
+ self.max_spread_pct = max_spread
159
+
160
+ async def initialize(self):
161
+ """Load LightGBM Models"""
162
+ print(f"🎯 [SniperEngine] Loading models from {self.models_dir}...")
163
+ try:
164
+ model_files = [f for f in os.listdir(self.models_dir) if f.startswith('lgbm_guard_v3_fold_')]
165
+
166
+ if len(model_files) < N_SPLITS:
167
+ print(f"❌ [SniperEngine] Error: Found {len(model_files)} models, need {N_SPLITS}.")
168
+ # Don't return, allow initialization without models (fallback mode)
169
+
170
+ for f in sorted(model_files):
171
+ model_path = os.path.join(self.models_dir, f)
172
+ self.models.append(lgb.Booster(model_file=model_path))
173
+
174
+ if self.models:
175
+ self.feature_names = self.models[0].feature_name()
176
+
177
+ self.initialized = True
178
+ print(f"✅ [SniperEngine] Active. WallLimit: {self.wall_ratio_limit}, MaxDist: {self.max_wall_dist*100}%")
179
+
180
+ except Exception as e:
181
+ print(f"❌ [SniperEngine] Init failed: {e}")
182
+ traceback.print_exc()
183
+ self.initialized = False
184
+
185
+ def _calculate_features_live(self, df_1m: pd.DataFrame) -> pd.DataFrame:
186
+ try:
187
+ df_with_std_feats = _add_standard_features(df_1m)
188
+ df_with_all_feats = _add_liquidity_proxies(df_with_std_feats)
189
+ df_final = df_with_all_feats.replace([np.inf, -np.inf], np.nan)
190
+ return df_final
191
+ except Exception as e:
192
+ print(f"❌ [SniperEngine] Feature calc error: {e}")
193
+ return pd.DataFrame()
194
+
195
+ # ==============================================================================
196
+ # 📊 3. Smart Order Book Logic (The Architect's Upgrade)
197
+ # ==============================================================================
198
+ def _score_order_book(self, order_book: Dict[str, Any], symbol: str = None) -> Dict[str, Any]:
199
+ try:
200
+ bids = order_book.get('bids', [])
201
+ asks = order_book.get('asks', [])
202
+
203
+ if not bids or not asks:
204
+ return {'score': 0.0, 'imbalance': 0.0, 'veto': True, 'reason': 'Empty OB'}
205
+
206
+ # --- 1. Spread Check ---
207
+ best_bid = float(bids[0][0])
208
+ best_ask = float(asks[0][0])
209
+ spread_pct = (best_ask - best_bid) / best_bid
210
+
211
+ if spread_pct > self.max_spread_pct:
212
+ return {
213
+ 'score': 0.0,
214
+ 'veto': True,
215
+ 'reason': f"Wide Spread ({spread_pct:.2%})"
216
+ }
217
+
218
+ # --- 2. Weighted Depth Imbalance ---
219
+ # Calculates imbalance giving higher weight to prices closer to spread
220
+ w_bid_vol = 0.0
221
+ w_ask_vol = 0.0
222
+ total_raw_ask_vol = 0.0 # for wall calculation
223
+
224
+ # Limit depth processing to configured depth
225
+ depth = min(len(bids), len(asks), self.ORDER_BOOK_DEPTH)
226
+
227
+ for i in range(depth):
228
+ # Decay Function: 1 / (1 + k * rank)
229
+ weight = 1.0 / (1.0 + (self.ob_depth_decay * i))
230
+
231
+ bid_vol = float(bids[i][1])
232
+ ask_vol = float(asks[i][1])
233
+
234
+ w_bid_vol += bid_vol * weight
235
+ w_ask_vol += ask_vol * weight
236
+ total_raw_ask_vol += ask_vol
237
+
238
+ total_w_vol = w_bid_vol + w_ask_vol
239
+ weighted_imbalance = w_bid_vol / total_w_vol if total_w_vol > 0 else 0.5
240
+
241
+ # --- 3. Distance-Aware Wall Detection ---
242
+ max_valid_wall = 0.0
243
+ limit_price = best_ask * (1 + self.max_wall_dist)
244
+
245
+ for price, vol in asks[:depth]:
246
+ p = float(price)
247
+ v = float(vol)
248
+ if p <= limit_price:
249
+ if v > max_valid_wall: max_valid_wall = v
250
+
251
+ wall_ratio = max_valid_wall / total_raw_ask_vol if total_raw_ask_vol > 0 else 0
252
+
253
+ # --- 4. Anti-Spoofing / Persistence Logic ---
254
+ veto_wall = False
255
+ veto_reason = "OK"
256
+
257
+ if wall_ratio >= self.wall_ratio_limit:
258
+ # Wall Detected
259
+ veto_wall = True
260
+ veto_reason = f"Sell Wall ({wall_ratio:.2f})"
261
+
262
+ if symbol:
263
+ curr_time = time.time()
264
+ cache = self._wall_cache.get(symbol, {'last_check': 0, 'count': 0})
265
+
266
+ # If this is a NEW wall (seen less than 1 second ago)
267
+ if curr_time - cache['last_check'] > 5.0:
268
+ # Reset counter if too much time passed
269
+ cache['count'] = 1
270
+ else:
271
+ cache['count'] += 1
272
+
273
+ cache['last_check'] = curr_time
274
+ self._wall_cache[symbol] = cache
275
+
276
+ # Optional: Logic to IGNORE flashing walls could go here
277
+ # For now, we block on first sight (Safety First)
278
+ else:
279
+ # No wall, clear cache slightly
280
+ if symbol and symbol in self._wall_cache:
281
+ self._wall_cache[symbol]['count'] = 0
282
+
283
+ return {
284
+ 'score': float(weighted_imbalance),
285
+ 'imbalance': float(weighted_imbalance), # Now Weighted
286
+ 'wall_ratio': float(wall_ratio),
287
+ 'veto': veto_wall,
288
+ 'spread_ok': True,
289
+ 'reason': veto_reason
290
+ }
291
+
292
+ except Exception as e:
293
+ return {'score': 0.0, 'veto': True, 'reason': f"OB Error: {e}"}
294
+
295
+ # ==============================================================================
296
+ # 🎯 4. Main Signal Check (Async)
297
+ # ==============================================================================
298
+ async def check_entry_signal_async(self,
299
+ ohlcv_1m_data: List[List],
300
+ order_book_data: Dict[str, Any] = None,
301
+ symbol: str = None) -> Dict[str, Any]:
302
+
303
+ if not self.initialized:
304
+ return {'signal': 'WAIT', 'reason': 'Not initialized'}
305
+
306
+ # --- ML Prediction ---
307
+ ml_score = 0.5
308
+ ml_reason = "No Data"
309
+
310
+ if len(ohlcv_1m_data) >= self.LOOKBACK_WINDOW and self.models:
311
+ try:
312
+ df = pd.DataFrame(ohlcv_1m_data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
313
+ df[['open', 'high', 'low', 'close', 'volume']] = df[['open', 'high', 'low', 'close', 'volume']].astype(float)
314
+
315
+ df_features = self._calculate_features_live(df)
316
+ if not df_features.empty:
317
+ X_live = df_features.iloc[-1:][self.feature_names].fillna(0)
318
+ preds = [m.predict(X_live)[0][1] for m in self.models]
319
+ ml_score = float(np.mean(preds))
320
+ ml_reason = f"ML:{ml_score:.2f}"
321
+ except Exception as e:
322
+ print(f"❌ [Sniper] ML Error: {e}")
323
+ ml_reason = "ML Err"
324
+
325
+ # --- Smart Order Book Analysis ---
326
+ ob_res = {'score': 0.5, 'imbalance': 0.5, 'veto': False, 'reason': 'No OB'}
327
+ if order_book_data:
328
+ ob_res = self._score_order_book(order_book_data, symbol=symbol)
329
+
330
+ # --- Final Hybrid Score ---
331
+ # If OB vetos (Spread too high OR Sell Wall), we force score down or WAIT
332
+ if ob_res.get('veto', False):
333
+ final_score = 0.0
334
+ signal = 'WAIT'
335
+ reason_str = f"⛔ {ob_res['reason']} | {ml_reason}"
336
+ else:
337
+ final_score = (ml_score * self.weight_ml) + (ob_res['score'] * self.weight_ob)
338
+
339
+ if final_score >= self.entry_threshold:
340
+ signal = 'BUY'
341
+ reason_str = f"✅ GO: {final_score:.2f} | {ml_reason} | OB:{ob_res['score']:.2f}"
342
+ else:
343
+ signal = 'WAIT'
344
+ reason_str = f"📉 Low Score: {final_score:.2f} | {ml_reason}"
345
+
346
+ return {
347
+ 'signal': signal,
348
+ 'confidence_prob': final_score,
349
+ 'ml_score': ml_score,
350
+ 'ob_score': ob_res['score'],
351
+ 'entry_price': float(order_book_data['asks'][0][0]) if order_book_data and order_book_data.get('asks') else 0.0,
352
+ 'reason': reason_str
353
+ }