File size: 5,366 Bytes
80c1546
ed906df
80c1546
701d42d
3a93a42
80c1546
701d42d
ed906df
80c1546
 
 
ed906df
80c1546
 
 
ed906df
701d42d
 
3a93a42
701d42d
 
3a93a42
701d42d
ed906df
80c1546
ed906df
 
 
 
 
 
 
 
 
80c1546
3e520df
80c1546
 
 
ed906df
 
 
 
 
 
 
 
 
 
 
 
 
92c2517
80c1546
1cd9326
ed906df
1cd9326
80c1546
 
ed906df
80c1546
ed906df
1cd9326
80c1546
ed906df
 
 
 
 
 
 
 
 
 
80c1546
 
 
ed906df
80c1546
ed906df
80c1546
 
ed906df
 
 
 
 
 
 
 
 
 
 
 
 
 
3a93a42
 
 
ed906df
80c1546
ed906df
 
 
 
 
 
 
 
80c1546
ed906df
80c1546
3a93a42
92c2517
3a93a42
032193e
701d42d
80c1546
3a93a42
701d42d
1cd9326
ed906df
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# ml_engine/processor.py
# (V12.3 - Hybrid Scoring Core: Titan + Patterns + Monte Carlo)

import asyncio
import traceback
import numpy as np

# استيراد المحركات الثلاثة
try:
    from ml_engine.titan_engine import TitanEngine
except ImportError:
    print("❌ [Processor] لم يتم العثور على titan_engine.py!")
    TitanEngine = None

from ml_engine.monte_carlo import MonteCarloAnalyzer
from ml_engine.patterns import ChartPatternAnalyzer # محرك الأنماط V11.1

class MLProcessor:
    def __init__(self, market_context, data_manager, learning_hub):
        self.market_context = market_context
        self.data_manager = data_manager
        self.learning_hub = learning_hub
        
        # 1. المحرك الرئيسي (Titan) - القناص (50%)
        self.titan = TitanEngine() if TitanEngine else None
        
        # 2. المحرك المساند (Patterns) - المتخصصون (40%)
        # نستخدم نفس النسخة الموجودة في DataManager لتوفير الذاكرة إذا أمكن
        if self.data_manager and self.data_manager.pattern_analyzer:
             self.pattern_engine = self.data_manager.pattern_analyzer
        else:
             self.pattern_engine = ChartPatternAnalyzer()

        # 3. المحرك الاحتمالي (Monte Carlo) - المدقق (10%)
        self.mc_analyzer = MonteCarloAnalyzer()
        
        self.initialized = False

    async def initialize(self):
        """تهيئة جميع المحركات الفرعية"""
        if not self.initialized:
            print("⚙️ [Processor] تهيئة نظام التقييم الهجين...")
            tasks = []
            if self.titan and not self.titan.initialized:
                tasks.append(self.titan.initialize())
            if self.pattern_engine and not self.pattern_engine.initialized:
                tasks.append(self.pattern_engine.initialize())
            
            if tasks:
                await asyncio.gather(*tasks)
            self.initialized = True
            print("✅ [Processor] النظام الهجين جاهز.")

    async def process_and_score_symbol_enhanced(self, raw_data):
        """
        المعالجة المركزية الهجينة (Hybrid Core Processing)
        """
        if not self.initialized: await self.initialize()
        symbol = raw_data.get('symbol')
        ohlcv_data = raw_data.get('ohlcv')
        
        if not symbol or not ohlcv_data: return None

        try:
            # --- 1. تشغيل المحركات الثلاثة بالتوازي ---
            # (للسرعة القصوى، لا ننتظر واحداً تلو الآخر)
            
            # أ. مهمة Titan
            titan_task = asyncio.to_thread(self.titan.predict, ohlcv_data) if self.titan else None
            
            # ب. مهمة الأنماط
            pattern_task = self.pattern_engine.detect_chart_patterns(ohlcv_data) if self.pattern_engine else None
            
            # ج. مهمة مونت كارلو (على فريم الساعة كمعيار)
            mc_score = 0.5
            if '1h' in ohlcv_data:
                 closes = np.array([c[4] for c in ohlcv_data['1h']])
                 # تشغيل سريع غير متزامن للمحاكاة
                 mc_res = self.mc_analyzer.generate_1h_price_distribution_simple(closes)
                 # تطبيع النتيجة لتكون بين 0 و 1 (هي أصلاً احتمالية)
                 mc_score = mc_res.get('mc_prob_gain', 0.5)

            # انتظار النتائج
            titan_res = await titan_task if titan_task else {'score': 0.0}
            pattern_res = await pattern_task if pattern_task else {'pattern_confidence': 0.0}

            # --- 2. استخراج الدرجات الخام ---
            score_titan = titan_res.get('score', 0.0)
            score_patterns = pattern_res.get('pattern_confidence', 0.0)
            score_mc = mc_score

            # --- 3. تطبيق المعادلة الهجينة (The Hybrid Formula) ---
            # Titan (50%) + Patterns (40%) + MC (10%)
            hybrid_score = (score_titan * 0.50) + (score_patterns * 0.40) + (score_mc * 0.10)

            # تجميع النتيجة النهائية
            analysis_result = {
                'symbol': symbol,
                'current_price': raw_data.get('current_price', 0.0),
                'enhanced_final_score': hybrid_score, # الدرجة النهائية المعتمدة
                
                # تفاصيل للشفافية (Audit Trail)
                'components': {
                    'titan_score': score_titan,
                    'patterns_score': score_patterns,
                    'mc_score': score_mc
                },
                'titan_details': titan_res,
                'pattern_details': pattern_res.get('details', {}),
                
                # عينة بيانات للحارس
                'ohlcv_sample': {tf: data[-1] for tf, data in ohlcv_data.items() if data}
            }

            return analysis_result

        except Exception as e:
            print(f"❌ [Processor] خطأ في معالجة {symbol}: {e}")
            traceback.print_exc()
            return None

print("✅ ML Processor V12.3 (Hybrid Core) loaded.")