Riy777 commited on
Commit
c09e7c4
·
verified ·
1 Parent(s): 199562d

Update ml_engine/oracle_engine.py

Browse files
Files changed (1) hide show
  1. ml_engine/oracle_engine.py +64 -39
ml_engine/oracle_engine.py CHANGED
@@ -16,10 +16,7 @@ CONFIDENCE_THRESHOLD = 0.65
16
  class OracleEngine:
17
  def __init__(self, model_dir: str = "ml_models/Unified_Models_V1"):
18
  """
19
- Oracle V4.0: Spot-Only Strategic Brain
20
- - يحلل الاتجاه (صعود/هبوط).
21
- - يمرر فقط فرص الصعود (Long) للتنفيذ.
22
- - يحجب فرص الهبوط (Short) ويعتبرها "مخاطرة" (WAIT).
23
  """
24
  self.model_dir = model_dir
25
  self.model_direction = None
@@ -28,7 +25,7 @@ class OracleEngine:
28
 
29
  self.feature_cols = []
30
  self.initialized = False
31
- print("🧠 [Oracle V4 - Spot] Engine Instance Created.")
32
 
33
  async def initialize(self):
34
  """تحميل النماذج وخريطة الميزات"""
@@ -65,24 +62,30 @@ class OracleEngine:
65
  print(f"❌ [Oracle] Init Error: {e}")
66
  return False
67
 
68
- # ==========================================================================
69
- # 🛠️ هندسة الميزات (مطابقة لـ DataFactory)
70
- # ==========================================================================
71
  def _calculate_snapshot_features(self, df, tf_prefix):
72
  df = df.copy()
73
  df['close'] = df['close'].astype(float)
74
  df['volume'] = df['volume'].astype(float)
75
 
76
- df[f'{tf_prefix}_slope'] = ta.slope(df['close'], length=7)
77
- df[f'{tf_prefix}_rsi'] = ta.rsi(df['close'], length=14)
78
- atr = ta.atr(df['high'], df['low'], df['close'], length=14)
79
- df[f'{tf_prefix}_atr_pct'] = atr / df['close']
80
- vol_mean = df['volume'].rolling(20).mean()
81
- vol_std = df['volume'].rolling(20).std()
82
- df[f'{tf_prefix}_vol_z'] = (df['volume'] - vol_mean) / (vol_std + 1e-9)
83
-
84
- cols = [f'{tf_prefix}_slope', f'{tf_prefix}_rsi', f'{tf_prefix}_atr_pct', f'{tf_prefix}_vol_z']
85
- return df[cols].ffill().bfill()
 
 
 
 
 
 
 
 
 
86
 
87
  def _create_feature_vector(self, ohlcv_data: Dict[str, Any], titan_score: float, mc_score: float, pattern_score: float) -> Optional[pd.DataFrame]:
88
  try:
@@ -106,6 +109,8 @@ class OracleEngine:
106
  feats_4h = pd.DataFrame(np.zeros((1, 4)), columns=[f'4h_{c}' for c in ['slope', 'rsi', 'atr_pct', 'vol_z']])
107
 
108
  vector = pd.concat([feats_1h, feats_15m, feats_4h], axis=1)
 
 
109
  vector['sim_titan_score'] = float(titan_score)
110
  vector['sim_mc_score'] = float(mc_score)
111
  vector['sim_pattern_score'] = float(pattern_score)
@@ -113,13 +118,16 @@ class OracleEngine:
113
  final_vector = pd.DataFrame(columns=self.feature_cols)
114
  for col in self.feature_cols:
115
  if col in vector.columns:
116
- final_vector.at[0, col] = vector[col].iloc[0]
 
 
117
  else:
118
  final_vector.at[0, col] = 0.0
119
 
120
  return final_vector.astype(float)
121
 
122
  except Exception as e:
 
123
  return None
124
 
125
  # ==========================================================================
@@ -128,38 +136,50 @@ class OracleEngine:
128
  async def predict(self, symbol_data: Dict[str, Any]) -> Dict[str, Any]:
129
  """تحليل الفرصة: هل هي صالحة للشراء (SPOT)؟"""
130
  if not self.initialized:
131
- return {'action': 'WAIT', 'reason': 'Not initialized'}
132
 
133
  try:
134
  ohlcv = symbol_data.get('ohlcv')
135
  current_price = symbol_data.get('current_price', 0.0)
136
- titan = symbol_data.get('titan_score', 0.5)
137
- mc = symbol_data.get('mc_score', 0.5)
138
- patt = symbol_data.get('patterns_score', 0.5)
 
 
 
 
 
 
139
 
140
  features = self._create_feature_vector(ohlcv, titan, mc, patt)
141
  if features is None:
142
- return {'action': 'WAIT', 'reason': 'Features failed'}
143
 
144
  # 1. التنبؤ بالاتجاه (Direction)
145
  # 0=Long (Buy), 1=Short (Drop/Avoid)
146
  dir_probs = self.model_direction.predict(features)[0]
147
 
148
  if isinstance(dir_probs, (np.ndarray, list)):
149
- prob_long = dir_probs[0]
150
- prob_short = dir_probs[1]
151
  else:
152
- prob_short = dir_probs
153
- prob_long = 1.0 - dir_probs
 
 
 
154
 
155
  # --- [SPOT LOGIC ENFORCEMENT] ---
156
- # إذا كان احتمال الهبوط (Short) أعلى، فهذا يعني "تجنب العملة".
157
- # لا نفتح صفقة Short، بل نقول WAIT.
 
158
  if prob_short > prob_long:
159
  return {
160
  'action': 'WAIT',
161
- 'reason': f'Bearish Forecast (Short Prob: {prob_short:.2f})',
162
- 'direction': 'SHORT' # For debugging only
 
 
163
  }
164
 
165
  # إذا وصلنا هنا، فالاتجاه هو LONG (شراء)
@@ -169,8 +189,10 @@ class OracleEngine:
169
  if confidence < CONFIDENCE_THRESHOLD:
170
  return {
171
  'action': 'WAIT',
172
- 'reason': f'Low Buy Confidence ({confidence:.2f})',
173
- 'direction': 'LONG'
 
 
174
  }
175
 
176
  # 3. التنبؤ بالأهداف والقوة
@@ -187,8 +209,11 @@ class OracleEngine:
187
  tp_labels = ['TP1', 'TP2', 'TP3', 'TP4']
188
  target_profile = tp_labels[tp_class_idx]
189
 
190
- # 4. حساب المستويات السعرية (للاتجاه الصاعد فقط)
191
  atr_pct_val = features['1h_atr_pct'].iloc[0]
 
 
 
192
  atr_abs = atr_pct_val * current_price
193
 
194
  tp_map = {
@@ -199,11 +224,11 @@ class OracleEngine:
199
  }
200
 
201
  primary_tp = tp_map[target_profile]
202
- sl_price = current_price - (1.2 * atr_abs) # وقف الخسارة تحت السعر
203
 
204
  return {
205
- 'action': 'WATCH', # إشارة شراء صالحة
206
- 'action_type': 'BUY', # دائماً BUY في Spot
207
  'confidence': float(confidence),
208
  'strength': float(strength),
209
  'target_class': target_profile,
@@ -215,4 +240,4 @@ class OracleEngine:
215
 
216
  except Exception as e:
217
  print(f"❌ [Oracle] Prediction Error: {e}")
218
- return {'action': 'WAIT', 'reason': 'Error'}
 
16
  class OracleEngine:
17
  def __init__(self, model_dir: str = "ml_models/Unified_Models_V1"):
18
  """
19
+ Oracle V4.1: Spot-Only Strategic Brain (Fixed Logging)
 
 
 
20
  """
21
  self.model_dir = model_dir
22
  self.model_direction = None
 
25
 
26
  self.feature_cols = []
27
  self.initialized = False
28
+ print("🧠 [Oracle V4.1] Engine Instance Created.")
29
 
30
  async def initialize(self):
31
  """تحميل النماذج وخريطة الميزات"""
 
62
  print(f"❌ [Oracle] Init Error: {e}")
63
  return False
64
 
 
 
 
65
  def _calculate_snapshot_features(self, df, tf_prefix):
66
  df = df.copy()
67
  df['close'] = df['close'].astype(float)
68
  df['volume'] = df['volume'].astype(float)
69
 
70
+ # تجنب الأخطاء إذا كانت البيانات قصيرة جداً
71
+ if len(df) < 15:
72
+ return pd.DataFrame()
73
+
74
+ try:
75
+ df[f'{tf_prefix}_slope'] = ta.slope(df['close'], length=7)
76
+ df[f'{tf_prefix}_rsi'] = ta.rsi(df['close'], length=14)
77
+ atr = ta.atr(df['high'], df['low'], df['close'], length=14)
78
+ df[f'{tf_prefix}_atr_pct'] = atr / df['close']
79
+ vol_mean = df['volume'].rolling(20).mean()
80
+ vol_std = df['volume'].rolling(20).std()
81
+ df[f'{tf_prefix}_vol_z'] = (df['volume'] - vol_mean) / (vol_std + 1e-9)
82
+
83
+ cols = [f'{tf_prefix}_slope', f'{tf_prefix}_rsi', f'{tf_prefix}_atr_pct', f'{tf_prefix}_vol_z']
84
+ # استخدام fillna(0) لضمان عدم وجود قيم فارغة
85
+ return df[cols].ffill().bfill().fillna(0)
86
+ except Exception as e:
87
+ # print(f"⚠️ Feature Calc Error ({tf_prefix}): {e}")
88
+ return pd.DataFrame()
89
 
90
  def _create_feature_vector(self, ohlcv_data: Dict[str, Any], titan_score: float, mc_score: float, pattern_score: float) -> Optional[pd.DataFrame]:
91
  try:
 
109
  feats_4h = pd.DataFrame(np.zeros((1, 4)), columns=[f'4h_{c}' for c in ['slope', 'rsi', 'atr_pct', 'vol_z']])
110
 
111
  vector = pd.concat([feats_1h, feats_15m, feats_4h], axis=1)
112
+
113
+ # التأكد من أن البيانات الرقمية (Scores) تُمرر بشكل صحيح
114
  vector['sim_titan_score'] = float(titan_score)
115
  vector['sim_mc_score'] = float(mc_score)
116
  vector['sim_pattern_score'] = float(pattern_score)
 
118
  final_vector = pd.DataFrame(columns=self.feature_cols)
119
  for col in self.feature_cols:
120
  if col in vector.columns:
121
+ val = vector[col].iloc[0]
122
+ # حماية إضافية ضد NaN
123
+ final_vector.at[0, col] = float(val) if not pd.isna(val) else 0.0
124
  else:
125
  final_vector.at[0, col] = 0.0
126
 
127
  return final_vector.astype(float)
128
 
129
  except Exception as e:
130
+ print(f"❌ Vector Creation Error: {e}")
131
  return None
132
 
133
  # ==========================================================================
 
136
  async def predict(self, symbol_data: Dict[str, Any]) -> Dict[str, Any]:
137
  """تحليل الفرصة: هل هي صالحة للشراء (SPOT)؟"""
138
  if not self.initialized:
139
+ return {'action': 'WAIT', 'reason': 'Not initialized', 'confidence': 0.0}
140
 
141
  try:
142
  ohlcv = symbol_data.get('ohlcv')
143
  current_price = symbol_data.get('current_price', 0.0)
144
+
145
+ # استخراج القيم والتأكد منها (DEBUG)
146
+ titan = symbol_data.get('titan_score', 0.0)
147
+ mc = symbol_data.get('mc_score', 0.0)
148
+ patt = symbol_data.get('patterns_score', 0.0)
149
+
150
+ # طباعة تصحيحية لمرة واحدة إذا كانت القيم صفرية بشكل مريب
151
+ if titan == 0 and patt == 0:
152
+ print(f"⚠️ [Oracle Warning] Input scores are ZERO for {symbol_data.get('symbol')}. Check upstream.")
153
 
154
  features = self._create_feature_vector(ohlcv, titan, mc, patt)
155
  if features is None:
156
+ return {'action': 'WAIT', 'reason': 'Features failed', 'confidence': 0.0}
157
 
158
  # 1. التنبؤ بالاتجاه (Direction)
159
  # 0=Long (Buy), 1=Short (Drop/Avoid)
160
  dir_probs = self.model_direction.predict(features)[0]
161
 
162
  if isinstance(dir_probs, (np.ndarray, list)):
163
+ prob_long = float(dir_probs[0])
164
+ prob_short = float(dir_probs[1])
165
  else:
166
+ # إذا كانت النتيجة قيمة واحدة (Binary output for Class 1)
167
+ # نفترض أن Class 1 هو Short (حسب تدريبك السابق) أو العكس.
168
+ # حسب الكود الأصلي: prob_short = dir_probs
169
+ prob_short = float(dir_probs)
170
+ prob_long = 1.0 - prob_short
171
 
172
  # --- [SPOT LOGIC ENFORCEMENT] ---
173
+ # التصحيح: نعيد قيمة confidence حتى لو كانت الحالة WAIT
174
+ # لكي تظهر في السجلات (Logs)
175
+
176
  if prob_short > prob_long:
177
  return {
178
  'action': 'WAIT',
179
+ 'reason': f'Bearish (Short Prob: {prob_short:.2f})',
180
+ 'direction': 'SHORT',
181
+ 'confidence': prob_long, # ✅ إضافة احتمالية الصعود (ستكون منخفضة)
182
+ 'short_confidence': prob_short
183
  }
184
 
185
  # إذا وصلنا هنا، فالاتجاه هو LONG (شراء)
 
189
  if confidence < CONFIDENCE_THRESHOLD:
190
  return {
191
  'action': 'WAIT',
192
+ 'reason': f'Low Confidence ({confidence:.2f})',
193
+ 'direction': 'LONG',
194
+ 'confidence': confidence, # ✅ إضافة القيمة للعرض
195
+ 'short_confidence': prob_short
196
  }
197
 
198
  # 3. التنبؤ بالأهداف والقوة
 
209
  tp_labels = ['TP1', 'TP2', 'TP3', 'TP4']
210
  target_profile = tp_labels[tp_class_idx]
211
 
212
+ # 4. حساب المستويات السعرية
213
  atr_pct_val = features['1h_atr_pct'].iloc[0]
214
+ # حماية من القيم الصفرية للـ ATR
215
+ if atr_pct_val == 0: atr_pct_val = 0.02
216
+
217
  atr_abs = atr_pct_val * current_price
218
 
219
  tp_map = {
 
224
  }
225
 
226
  primary_tp = tp_map[target_profile]
227
+ sl_price = current_price - (1.2 * atr_abs)
228
 
229
  return {
230
+ 'action': 'WATCH',
231
+ 'action_type': 'BUY',
232
  'confidence': float(confidence),
233
  'strength': float(strength),
234
  'target_class': target_profile,
 
240
 
241
  except Exception as e:
242
  print(f"❌ [Oracle] Prediction Error: {e}")
243
+ return {'action': 'WAIT', 'reason': 'Error', 'confidence': 0.0}