Riy777 commited on
Commit
0d4a74c
·
1 Parent(s): 0bf918d

Create strategies.py

Browse files
Files changed (1) hide show
  1. ml_engine/strategies.py +334 -0
ml_engine/strategies.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ml_engine/strategies.py
2
+ import asyncio
3
+
4
+ # الاستيراد من الوحدات الداخلية في نفس المجلد
5
+ from .patterns import ChartPatternAnalyzer
6
+
7
+ class PatternEnhancedStrategyEngine:
8
+ def __init__(self, data_manager, learning_engine):
9
+ self.data_manager = data_manager
10
+ self.learning_engine = learning_engine
11
+ self.pattern_analyzer = ChartPatternAnalyzer()
12
+
13
+ async def enhance_strategy_with_patterns(self, strategy_scores, pattern_analysis, symbol):
14
+ """تعزيز الاستراتيجيات بناءً على الأنماط المكتشفة"""
15
+ if not pattern_analysis or pattern_analysis.get('pattern_detected') in ['no_clear_pattern', 'insufficient_data']:
16
+ return strategy_scores
17
+
18
+ pattern_confidence = pattern_analysis.get('pattern_confidence', 0)
19
+ pattern_name = pattern_analysis.get('pattern_detected', '')
20
+ predicted_direction = pattern_analysis.get('predicted_direction', '')
21
+
22
+ if pattern_confidence >= 0.6:
23
+ enhancement_factor = self._calculate_pattern_enhancement(pattern_confidence, pattern_name)
24
+ enhanced_strategies = self._get_pattern_appropriate_strategies(pattern_name, predicted_direction)
25
+
26
+ print(f"🎯 تعزيز استراتيجيات {symbol} بناءً على نمط {pattern_name} (ثقة: {pattern_confidence:.2f})")
27
+
28
+ for strategy in enhanced_strategies:
29
+ if strategy in strategy_scores:
30
+ original_score = strategy_scores[strategy]
31
+ strategy_scores[strategy] = min(original_score * enhancement_factor, 1.0)
32
+ print(f" 📈 {strategy}: {original_score:.3f} → {strategy_scores[strategy]:.3f}")
33
+
34
+ return strategy_scores
35
+
36
+ def _calculate_pattern_enhancement(self, pattern_confidence, pattern_name):
37
+ """حساب عامل التعزيز بناءً على ثقة النمط ونوعه"""
38
+ base_enhancement = 1.0 + (pattern_confidence * 0.3)
39
+ high_reliability_patterns = ['Double Top', 'Double Bottom', 'Head & Shoulders', 'Cup and Handle']
40
+ if pattern_name in high_reliability_patterns:
41
+ base_enhancement *= 1.1
42
+ return min(base_enhancement, 1.5)
43
+
44
+ def _get_pattern_appropriate_strategies(self, pattern_name, direction):
45
+ """تحديد الاستراتيجيات المناسبة للنمط المكتشف"""
46
+ reversal_patterns = ['Double Top', 'Double Bottom', 'Head & Shoulders', 'Triple Top', 'Triple Bottom']
47
+ continuation_patterns = ['Flags', 'Pennants', 'Triangles', 'Rectangles']
48
+
49
+ if pattern_name in reversal_patterns:
50
+ if direction == 'down':
51
+ return ['breakout_momentum', 'trend_following']
52
+ else:
53
+ return ['mean_reversion', 'breakout_momentum']
54
+ elif pattern_name in continuation_patterns:
55
+ return ['trend_following', 'breakout_momentum']
56
+ else:
57
+ return ['breakout_momentum', 'hybrid_ai']
58
+
59
+ class MultiStrategyEngine:
60
+ def __init__(self, data_manager, learning_engine):
61
+ self.data_manager = data_manager
62
+ self.learning_engine = learning_engine
63
+
64
+ # 🔴 ملاحظة: تم إزالة مُهيِئات (constructors) التحليل غير المستخدمة من هنا
65
+ # الاستراتيجيات تستهلك البيانات المحسوبة مسبقاً من (symbol_data)
66
+ # التي يوفرها (MLProcessor) الرئيسي
67
+
68
+ self.pattern_enhancer = PatternEnhancedStrategyEngine(data_manager, learning_engine)
69
+
70
+ self.strategies = {
71
+ 'trend_following': self._trend_following_strategy,
72
+ 'mean_reversion': self._mean_reversion_strategy,
73
+ 'breakout_momentum': self._breakout_momentum_strategy,
74
+ 'volume_spike': self._volume_spike_strategy,
75
+ 'whale_tracking': self._whale_tracking_strategy,
76
+ 'pattern_recognition': self._pattern_recognition_strategy,
77
+ 'hybrid_ai': self._hybrid_ai_strategy
78
+ }
79
+
80
+ async def evaluate_all_strategies(self, symbol_data, market_context):
81
+ """تقييم جميع استراتيجيات التداول"""
82
+ try:
83
+ if self.learning_engine and hasattr(self.learning_engine, 'initialized') and self.learning_engine.initialized:
84
+ try:
85
+ market_condition = market_context.get('market_trend', 'sideways_market')
86
+ optimized_weights = await self.learning_engine.get_optimized_strategy_weights(market_condition)
87
+ except Exception as e:
88
+ # ❌ لا نستخدم قيم افتراضية، نستخدم الأوزان الأساسية
89
+ optimized_weights = await self.get_default_weights()
90
+ else:
91
+ optimized_weights = await self.get_default_weights()
92
+
93
+ strategy_scores = {}
94
+ base_scores = {}
95
+
96
+ for strategy_name, strategy_function in self.strategies.items():
97
+ try:
98
+ base_score = await strategy_function(symbol_data, market_context)
99
+ if base_score is None: # ❌ إذا فشلت الاستراتيجية، لا نستخدم قيم افتراضية
100
+ continue
101
+ base_scores[strategy_name] = base_score
102
+ weight = optimized_weights.get(strategy_name, 0.1)
103
+ weighted_score = base_score * weight
104
+ strategy_scores[strategy_name] = min(weighted_score, 1.0)
105
+ except Exception as error:
106
+ print(f"❌ خطأ في تقييم استراتيجية {strategy_name}: {error}")
107
+ # ❌ لا نستخدم أي محاكاة أو قيم افتراضية
108
+ continue
109
+
110
+ pattern_analysis = symbol_data.get('pattern_analysis')
111
+ if pattern_analysis:
112
+ strategy_scores = await self.pattern_enhancer.enhance_strategy_with_patterns(
113
+ strategy_scores, pattern_analysis, symbol_data.get('symbol')
114
+ )
115
+
116
+ if base_scores:
117
+ best_strategy = max(base_scores.items(), key=lambda x: x[1])
118
+ best_strategy_name = best_strategy[0]
119
+ best_strategy_score = best_strategy[1]
120
+ symbol_data['recommended_strategy'] = best_strategy_name
121
+ symbol_data['strategy_confidence'] = best_strategy_score
122
+
123
+ return strategy_scores, base_scores
124
+
125
+ except Exception as error:
126
+ print(f"❌ خطأ في تقييم الاستراتيجيات: {error}")
127
+ # ❌ لا نستخدم أي محاكاة
128
+ return {}, {}
129
+
130
+ async def get_default_weights(self):
131
+ """الأوزان الافتراضية للاستراتيجيات - هذه ليست محاكاة ولكن أوزان ابتدائية"""
132
+ return {
133
+ 'trend_following': 0.15,
134
+ 'mean_reversion': 0.12,
135
+ 'breakout_momentum': 0.18,
136
+ 'volume_spike': 0.10,
137
+ 'whale_tracking': 0.20,
138
+ 'pattern_recognition': 0.15,
139
+ 'hybrid_ai': 0.10
140
+ }
141
+
142
+ async def _trend_following_strategy(self, symbol_data, market_context):
143
+ """استراتيجية تتبع الاتجاه"""
144
+ try:
145
+ score = 0.0
146
+ indicators = symbol_data.get('advanced_indicators', {})
147
+
148
+ for timeframe in ['4h', '1h', '15m']:
149
+ if timeframe in indicators:
150
+ timeframe_indicators = indicators[timeframe]
151
+
152
+ if self._check_ema_alignment(timeframe_indicators):
153
+ score += 0.20
154
+
155
+ adx_value = timeframe_indicators.get('adx', 0)
156
+ if adx_value > 25:
157
+ score += 0.15
158
+
159
+ if (timeframe_indicators.get('ichimoku_conversion', 0) >
160
+ timeframe_indicators.get('ichimoku_base', 0)):
161
+ score += 0.10
162
+
163
+ return min(score, 1.0)
164
+ except Exception as error:
165
+ print(f"❌ خطأ في استراتيجية تتبع الاتجاه: {error}")
166
+ return None # ❌ لا نرجع قيمة افتراضية
167
+
168
+ def _check_ema_alignment(self, indicators):
169
+ """التحقق من محاذاة المتوسطات المتحركة"""
170
+ required_emas = ['ema_9', 'ema_21', 'ema_50']
171
+ if all(ema in indicators for ema in required_emas):
172
+ return (indicators['ema_9'] > indicators['ema_21'] > indicators['ema_50'])
173
+ return False
174
+
175
+ async def _mean_reversion_strategy(self, symbol_data, market_context):
176
+ """استراتيجية العودة للمتوسط"""
177
+ try:
178
+ score = 0.0
179
+ current_price = symbol_data['current_price']
180
+ indicators = symbol_data.get('advanced_indicators', {})
181
+
182
+ if '1h' in indicators:
183
+ hourly_indicators = indicators['1h']
184
+
185
+ if all(key in hourly_indicators for key in ['bb_upper', 'bb_lower', 'bb_middle']):
186
+ position_in_band = (current_price - hourly_indicators['bb_lower']) / (
187
+ hourly_indicators['bb_upper'] - hourly_indicators['bb_lower'])
188
+
189
+ if position_in_band < 0.1 and hourly_indicators.get('rsi', 50) < 35:
190
+ score += 0.45
191
+ if position_in_band > 0.9 and hourly_indicators.get('rsi', 50) > 65:
192
+ score += 0.45
193
+
194
+ rsi_value = hourly_indicators.get('rsi', 50)
195
+ if rsi_value < 30:
196
+ score += 0.35
197
+ elif rsi_value > 70:
198
+ score += 0.35
199
+
200
+ return min(score, 1.0)
201
+ except Exception as error:
202
+ print(f"❌ خطأ في استراتيجية العودة للمتوسط: {error}")
203
+ return None # ❌ لا نرجع قيمة افتراضية
204
+
205
+ async def _breakout_momentum_strategy(self, symbol_data, market_context):
206
+ """استراتيجية زخم الاختراق"""
207
+ try:
208
+ score = 0.0
209
+ indicators = symbol_data.get('advanced_indicators', {})
210
+
211
+ for timeframe in ['1h', '15m', '5m']:
212
+ if timeframe in indicators:
213
+ timeframe_indicators = indicators[timeframe]
214
+
215
+ volume_ratio = timeframe_indicators.get('volume_ratio', 0)
216
+ if volume_ratio > 1.8:
217
+ score += 0.25
218
+ elif volume_ratio > 1.3:
219
+ score += 0.15
220
+
221
+ if timeframe_indicators.get('macd_hist', 0) > 0:
222
+ score += 0.20
223
+
224
+ if 'vwap' in timeframe_indicators and symbol_data['current_price'] > timeframe_indicators['vwap']:
225
+ score += 0.15
226
+
227
+ rsi_value = timeframe_indicators.get('rsi', 50)
228
+ if 40 <= rsi_value <= 70:
229
+ score += 0.10
230
+
231
+ if score > 0.2:
232
+ score = max(score, 0.4)
233
+
234
+ return min(score, 1.0)
235
+ except Exception as error:
236
+ print(f"❌ خطأ في استراتيجية زخم الاختراق: {error}")
237
+ return None # ❌ لا نرجع قيمة افتراضية
238
+
239
+ async def _volume_spike_strategy(self, symbol_data, market_context):
240
+ """استراتيجية ارتفاع الحجم"""
241
+ try:
242
+ score = 0.0
243
+ indicators = symbol_data.get('advanced_indicators', {})
244
+
245
+ for timeframe in ['1h', '15m', '5m']:
246
+ if timeframe in indicators:
247
+ volume_ratio = indicators[timeframe].get('volume_ratio', 0)
248
+ if volume_ratio > 3.0:
249
+ score += 0.45
250
+ elif volume_ratio > 2.0:
251
+ score += 0.25
252
+ elif volume_ratio > 1.5:
253
+ score += 0.15
254
+
255
+ return min(score, 1.0)
256
+ except Exception as error:
257
+ print(f"❌ خطأ في استراتيجية ارتفاع الحجم: {error}")
258
+ return None # ❌ لا نرجع قيمة افتراضية
259
+
260
+ async def _whale_tracking_strategy(self, symbol_data, market_context):
261
+ """استراتيجية تتبع الحيتان"""
262
+ try:
263
+ whale_data = symbol_data.get('whale_data', {})
264
+ if not whale_data.get('data_available', False):
265
+ return None # ❌ لا نرجع قيمة افتراضية
266
+
267
+ whale_signal = await self.data_manager.get_whale_trading_signal(
268
+ symbol_data['symbol'], whale_data, market_context
269
+ )
270
+
271
+ if whale_signal and whale_signal.get('action') != 'HOLD':
272
+ confidence = whale_signal.get('confidence', 0)
273
+ if whale_signal.get('action') in ['STRONG_BUY', 'BUY']:
274
+ return min(confidence * 1.2, 1.0)
275
+ elif whale_signal.get('action') in ['STRONG_SELL', 'SELL']:
276
+ return min(confidence * 0.8, 1.0)
277
+
278
+ return None # ❌ لا نرجع قيمة افتراضية
279
+ except Exception as error:
280
+ print(f"❌ خطأ في استراتيجية تتبع الحيتان: {error}")
281
+ return None # ❌ لا نرجع قيمة افتراضية
282
+
283
+ async def _pattern_recognition_strategy(self, symbol_data, market_context):
284
+ """استراتيجية التعرف على الأنماط"""
285
+ try:
286
+ score = 0.0
287
+ pattern_analysis = symbol_data.get('pattern_analysis')
288
+
289
+ if pattern_analysis and pattern_analysis.get('pattern_confidence', 0) > 0.6:
290
+ score += pattern_analysis.get('pattern_confidence', 0) * 0.8
291
+ else:
292
+ indicators = symbol_data.get('advanced_indicators', {})
293
+ for timeframe in ['4h', '1h']:
294
+ if timeframe in indicators:
295
+ timeframe_indicators = indicators[timeframe]
296
+ if (timeframe_indicators.get('rsi', 50) > 60 and
297
+ timeframe_indicators.get('macd_hist', 0) > 0 and
298
+ timeframe_indicators.get('volume_ratio', 0) > 1.5):
299
+ score += 0.35
300
+
301
+ return min(score, 1.0)
302
+ except Exception as error:
303
+ print(f"❌ خطأ في استراتيجية التعرف على الأنماط: {error}")
304
+ return None # ❌ لا نرجع قيمة افتراضية
305
+
306
+ async def _hybrid_ai_strategy(self, symbol_data, market_context):
307
+ """استراتيجية الهجين الذكية"""
308
+ try:
309
+ score = 0.0
310
+
311
+ monte_carlo_probability = symbol_data.get('monte_carlo_probability')
312
+ if monte_carlo_probability is not None:
313
+ score += monte_carlo_probability * 0.4
314
+
315
+ final_score = symbol_data.get('final_score', 0)
316
+ if final_score > 0:
317
+ score += final_score * 0.3
318
+
319
+ if market_context.get('btc_sentiment') == 'BULLISH':
320
+ score += 0.15
321
+ elif market_context.get('btc_sentiment') == 'BEARISH':
322
+ score -= 0.08
323
+
324
+ pattern_analysis = symbol_data.get('pattern_analysis')
325
+ if pattern_analysis and pattern_analysis.get('pattern_confidence', 0) > 0.6:
326
+ pattern_bonus = pattern_analysis.get('pattern_confidence', 0) * 0.15
327
+ score += pattern_bonus
328
+
329
+ return max(0.0, min(score, 1.0))
330
+ except Exception as error:
331
+ print(f"❌ خطأ في استراتيجية الهجين الذكية: {error}")
332
+ return None # ❌ لا نرجع قيمة افتراضية
333
+
334
+ print("✅ ML Module: Strategy Engine loaded")