Riy777 commited on
Commit
b393d8d
·
verified ·
1 Parent(s): 6c39cb4

Update learning_hub/adaptive_hub.py

Browse files
Files changed (1) hide show
  1. learning_hub/adaptive_hub.py +37 -63
learning_hub/adaptive_hub.py CHANGED
@@ -1,6 +1,6 @@
1
  # ==============================================================================
2
  # 🧠 learning_hub/adaptive_hub.py
3
- # (V52.0 - GEM-Architect: Structural DNA Link)
4
  # ==============================================================================
5
 
6
  import json
@@ -14,21 +14,16 @@ from typing import Dict, Any, List, Optional
14
  from ml_engine.processor import SystemLimits
15
 
16
  class StrategyDNA:
17
- """
18
- هيكلية البيانات لكل استراتيجية.
19
- تم إزالة scanner_weights لأن الفلتر الجديد يعتمد على المنطق الهيكلي (Structural Logic).
20
- """
21
  def __init__(self, name, model_weights, ob_settings, filters, guard_settings=None):
22
  self.name = name
23
- self.model_weights = model_weights # أوزان النماذج (Titan, Sniper, etc.)
24
  self.ob_settings = ob_settings # إعدادات دفتر الطلبات
25
  self.filters = filters # فلاتر L1 (Thresholds)
26
- self.guard_settings = guard_settings if guard_settings else {} # إعدادات الحراس
27
 
28
  self.stats = {"wins": 0, "losses": 0, "win_rate": 0.0}
29
 
30
  def to_dict(self):
31
- # نقوم بتحويل الكائن إلى قاموس للتخزين، نتجاهل أي حقول قديمة
32
  return {
33
  "name": self.name,
34
  "model_weights": self.model_weights,
@@ -41,17 +36,15 @@ class StrategyDNA:
41
  class AdaptiveHub:
42
  def __init__(self, r2_service=None):
43
  self.r2 = r2_service
44
- self.dna_file_key = "learning/strategic_dna_v4.json" # V4 for structural support
 
45
  self.current_market_regime = "RANGE"
46
  self.strategies: Dict[str, StrategyDNA] = {}
47
 
48
- # معدل التعلم التكتيكي
49
  self.TACTICAL_LEARNING_RATE = 0.05
50
-
51
- print("🧠 [AdaptiveHub V52.0] Structural Strategy Core Initialized.")
52
 
53
  async def initialize(self):
54
- """تحميل الـ DNA من R2 أو إنشاء الافتراضي"""
55
  print(f"📥 [AdaptiveHub] Loading Strategy DNA from R2...")
56
  try:
57
  if self.r2:
@@ -66,7 +59,6 @@ class AdaptiveHub:
66
  else:
67
  self._create_default_dna()
68
 
69
- # تطبيق الإعدادات فوراً (Hot Reload)
70
  self._inject_current_parameters()
71
 
72
  except Exception as e:
@@ -75,38 +67,39 @@ class AdaptiveHub:
75
  self._create_default_dna()
76
 
77
  def _create_default_dna(self):
78
- """إنشاء الإعدادات الافتراضية الذكية المتوافقة مع الفلتر الهيكلي"""
79
-
 
80
  default_guards = {
81
- "hydra_crash": 0.60, "hydra_giveback": 0.70,
82
  "legacy_v2": 0.95, "legacy_v3": 0.95
83
  }
84
 
85
- # ملاحظة: l1_min_score هنا يمثل "نسبة الثقة" (0.0 - 1.0)
86
- # سيتم تحويلها لاحقاً إلى درجة رقمية للفلتر (-50 إلى +100)
87
 
88
- # 1. BULL: هجومي، يقبل هياكل أقل كمالاً لالتقاط الزخم
89
  self.strategies["BULL"] = StrategyDNA(
90
  name="BULL",
91
- model_weights={"titan": 0.50, "patterns": 0.30, "sniper": 0.20},
 
92
  ob_settings={"wall_ratio_limit": 0.60, "imbalance_thresh": 0.5},
93
- filters={"l1_min_score": 0.55, "l3_conf_thresh": 0.60}, # 0.55 تعني تساهل متوسط
94
  guard_settings=default_guards
95
  )
96
 
97
- # 2. BEAR: دفاعي، يتطلب هيكلية مثالية (Structure Score عالي)
98
  self.strategies["BEAR"] = StrategyDNA(
99
  name="BEAR",
100
- model_weights={"titan": 0.30, "patterns": 0.20, "sniper": 0.50},
101
  ob_settings={"wall_ratio_limit": 0.30, "imbalance_thresh": 0.7},
102
- filters={"l1_min_score": 0.75, "l3_conf_thresh": 0.75}, # 0.75 تعني تطلب عالي
103
  guard_settings=default_guards
104
  )
105
 
106
- # 3. RANGE: متوازن
107
  self.strategies["RANGE"] = StrategyDNA(
108
  name="RANGE",
109
- model_weights={"titan": 0.40, "patterns": 0.40, "sniper": 0.20},
110
  ob_settings={"wall_ratio_limit": 0.40, "imbalance_thresh": 0.6},
111
  filters={"l1_min_score": 0.65, "l3_conf_thresh": 0.65},
112
  guard_settings=default_guards
@@ -115,16 +108,14 @@ class AdaptiveHub:
115
  # DEAD Mode
116
  self.strategies["DEAD"] = StrategyDNA(
117
  name="DEAD",
118
- model_weights={"titan": 0.25, "patterns": 0.25, "sniper": 0.25},
119
  ob_settings={"wall_ratio_limit": 0.20, "imbalance_thresh": 0.8},
120
- filters={"l1_min_score": 0.85, "l3_conf_thresh": 0.80}, # تطلب شديد جداً
121
  guard_settings=default_guards
122
  )
123
 
124
  def _load_from_dict(self, data):
125
- """تحويل JSON إلى كائنات StrategyDNA"""
126
  for key, val in data.get("strategies", {}).items():
127
- # تنظيف البيانات القديمة إذا وجدت (مثل scanner_weights)
128
  self.strategies[key] = StrategyDNA(
129
  name=val["name"],
130
  model_weights=val["model_weights"],
@@ -136,11 +127,7 @@ class AdaptiveHub:
136
 
137
  self.current_market_regime = data.get("current_regime", "RANGE")
138
 
139
- # ==========================================================================
140
- # ⚡ The Tactical Loop
141
- # ==========================================================================
142
  async def register_trade_outcome(self, trade_data: Dict[str, Any]):
143
- """تحديث الإحصائيات الحية"""
144
  try:
145
  pnl = trade_data.get('profit_pct', 0.0)
146
  is_win = pnl > 0
@@ -149,51 +136,41 @@ class AdaptiveHub:
149
  active_dna = self.strategies[self.current_market_regime]
150
  if is_win: active_dna.stats["wins"] += 1
151
  else: active_dna.stats["losses"] += 1
152
-
153
- # هنا يمكن إضافة منطق تعديل طفيف للأوزان (Micro-adjustments)
154
- # لكن التعديل الكبير يأتي من الباكتست
155
 
156
  except Exception as e:
157
  print(f"❌ [AdaptiveHub] Trade Analysis Error: {e}")
158
  traceback.print_exc()
159
 
160
- # ==========================================================================
161
- # 💉 Parameter Injection (The Critical Link)
162
- # ==========================================================================
163
  def _inject_current_parameters(self):
164
  """
165
- نقل الإعدادات من الـ DNA النشط إلى SystemLimits
166
- مع تحويل القيم النسبية إلى قيم مطلقة للفلتر الهيكلي.
 
167
  """
168
  if self.current_market_regime not in self.strategies:
169
  return
170
 
171
  active_dna = self.strategies[self.current_market_regime]
172
 
173
- print(f"💉 [AdaptiveHub] Injecting Structural DNA for: {self.current_market_regime}")
174
 
175
- # 1. حقن أوزان الطبقة الثانية (L2 Weights)
176
  mw = active_dna.model_weights
177
  total_w = sum(mw.values()) if sum(mw.values()) > 0 else 1.0
178
 
179
  SystemLimits.L2_WEIGHT_TITAN = mw.get("titan", 0.4) / total_w
180
- SystemLimits.L2_WEIGHT_PATTERNS = mw.get("patterns", 0.3) / total_w
181
- # نستخدم مفتاح 'patterns' مؤقتاً لوزن الهيكل إذا لم نضف مفتاحاً خاصاً
182
 
183
- # 2. 🔥 حقن عتبة الفلتر الهيكلي (L1 Score Threshold)
184
- # القيمة المخزنة في DNA هي نسبة (0.0 - 1.0) قادمة من الباكتست
185
- # القيمة المطلوبة في DataManager هي درجة (-100 إلى +100)
186
- # معادلة التحويل: (Ratio * 100) - 20
187
- # مثال: 0.65 -> (65) - 20 = 45 درجة مطلوبة
188
  thresh_ratio = active_dna.filters.get("l1_min_score", 0.65)
189
  raw_score_limit = (thresh_ratio * 100.0) - 20.0
190
-
191
  SystemLimits.L1_MIN_AFFINITY_SCORE = raw_score_limit
192
 
193
- # 3. حقن النظام الحالي
194
  SystemLimits.CURRENT_REGIME = self.current_market_regime
195
-
196
- # 4. حقن باقي الإعدادات
197
  SystemLimits.L3_CONFIDENCE_THRESHOLD = active_dna.filters.get("l3_conf_thresh", 0.65)
198
  SystemLimits.L4_OB_WALL_RATIO = active_dna.ob_settings.get("wall_ratio_limit", 0.4)
199
 
@@ -204,9 +181,6 @@ class AdaptiveHub:
204
  SystemLimits.LEGACY_V2_PANIC_THRESH = gs.get('legacy_v2', 0.95)
205
  SystemLimits.LEGACY_V3_HARD_THRESH = gs.get('legacy_v3', 0.95)
206
 
207
- # ==========================================================================
208
- # 🎮 Utilities
209
- # ==========================================================================
210
  def update_market_regime(self, new_regime: str):
211
  if new_regime in self.strategies:
212
  self.current_market_regime = new_regime
@@ -217,13 +191,13 @@ class AdaptiveHub:
217
  dna = self.strategies.get(self.current_market_regime)
218
  if not dna: return "System Initializing..."
219
 
220
- # حساب القيمة المحقونة للعرض
221
  thresh_ratio = dna.filters.get('l1_min_score', 0)
222
- raw_limit = (thresh_ratio * 100.0) - 20.0
223
 
 
224
  return (f"Regime: {self.current_market_regime} | "
225
- f"L1 Req: {raw_limit:.1f}pts ({thresh_ratio:.0%}) | "
226
- f"Titan W: {dna.model_weights.get('titan'):.2f}")
 
227
 
228
  async def _save_state_to_r2(self):
229
  if not self.r2: return
 
1
  # ==============================================================================
2
  # 🧠 learning_hub/adaptive_hub.py
3
+ # (V53.0 - GEM-Architect: Structure-Aware Core)
4
  # ==============================================================================
5
 
6
  import json
 
14
  from ml_engine.processor import SystemLimits
15
 
16
  class StrategyDNA:
 
 
 
 
17
  def __init__(self, name, model_weights, ob_settings, filters, guard_settings=None):
18
  self.name = name
19
+ self.model_weights = model_weights # أوزان النماذج (Titan, Sniper, Structure)
20
  self.ob_settings = ob_settings # إعدادات دفتر الطلبات
21
  self.filters = filters # فلاتر L1 (Thresholds)
22
+ self.guard_settings = guard_settings if guard_settings else {}
23
 
24
  self.stats = {"wins": 0, "losses": 0, "win_rate": 0.0}
25
 
26
  def to_dict(self):
 
27
  return {
28
  "name": self.name,
29
  "model_weights": self.model_weights,
 
36
  class AdaptiveHub:
37
  def __init__(self, r2_service=None):
38
  self.r2 = r2_service
39
+ # قمنا بتحديث مفتاح الملف لضمان عدم تحميل إعدادات قديمة متعارضة
40
+ self.dna_file_key = "learning/strategic_dna_v5_struct.json"
41
  self.current_market_regime = "RANGE"
42
  self.strategies: Dict[str, StrategyDNA] = {}
43
 
 
44
  self.TACTICAL_LEARNING_RATE = 0.05
45
+ print("🧠 [AdaptiveHub V53.0] Structure-Aware Core Initialized.")
 
46
 
47
  async def initialize(self):
 
48
  print(f"📥 [AdaptiveHub] Loading Strategy DNA from R2...")
49
  try:
50
  if self.r2:
 
59
  else:
60
  self._create_default_dna()
61
 
 
62
  self._inject_current_parameters()
63
 
64
  except Exception as e:
 
67
  self._create_default_dna()
68
 
69
  def _create_default_dna(self):
70
+ """
71
+ إنشاء الإعدادات الافتراضية مع دعم وزن الهيكل (Structure Weight)
72
+ """
73
  default_guards = {
74
+ "hydra_crash": 0.85, "hydra_giveback": 0.70,
75
  "legacy_v2": 0.95, "legacy_v3": 0.95
76
  }
77
 
78
+ # ملاحظة: تم استبدال 'patterns' بـ 'structure' في model_weights
 
79
 
80
+ # 1. BULL: تركيز متوازن بين Titan والهيكل
81
  self.strategies["BULL"] = StrategyDNA(
82
  name="BULL",
83
+ # Titan: الذكاء الاصطناعي | Structure: الفلتر الهندسي الجديد
84
+ model_weights={"titan": 0.50, "structure": 0.30, "sniper": 0.20},
85
  ob_settings={"wall_ratio_limit": 0.60, "imbalance_thresh": 0.5},
86
+ filters={"l1_min_score": 0.55, "l3_conf_thresh": 0.60},
87
  guard_settings=default_guards
88
  )
89
 
90
+ # 2. BEAR: اعتماد أكبر على الهيكل (Structure) لتجنب الإشارات الكاذبة
91
  self.strategies["BEAR"] = StrategyDNA(
92
  name="BEAR",
93
+ model_weights={"titan": 0.30, "structure": 0.40, "sniper": 0.30},
94
  ob_settings={"wall_ratio_limit": 0.30, "imbalance_thresh": 0.7},
95
+ filters={"l1_min_score": 0.75, "l3_conf_thresh": 0.75},
96
  guard_settings=default_guards
97
  )
98
 
99
+ # 3. RANGE: التوازن المثالي
100
  self.strategies["RANGE"] = StrategyDNA(
101
  name="RANGE",
102
+ model_weights={"titan": 0.40, "structure": 0.40, "sniper": 0.20},
103
  ob_settings={"wall_ratio_limit": 0.40, "imbalance_thresh": 0.6},
104
  filters={"l1_min_score": 0.65, "l3_conf_thresh": 0.65},
105
  guard_settings=default_guards
 
108
  # DEAD Mode
109
  self.strategies["DEAD"] = StrategyDNA(
110
  name="DEAD",
111
+ model_weights={"titan": 0.25, "structure": 0.25, "sniper": 0.25},
112
  ob_settings={"wall_ratio_limit": 0.20, "imbalance_thresh": 0.8},
113
+ filters={"l1_min_score": 0.85, "l3_conf_thresh": 0.80},
114
  guard_settings=default_guards
115
  )
116
 
117
  def _load_from_dict(self, data):
 
118
  for key, val in data.get("strategies", {}).items():
 
119
  self.strategies[key] = StrategyDNA(
120
  name=val["name"],
121
  model_weights=val["model_weights"],
 
127
 
128
  self.current_market_regime = data.get("current_regime", "RANGE")
129
 
 
 
 
130
  async def register_trade_outcome(self, trade_data: Dict[str, Any]):
 
131
  try:
132
  pnl = trade_data.get('profit_pct', 0.0)
133
  is_win = pnl > 0
 
136
  active_dna = self.strategies[self.current_market_regime]
137
  if is_win: active_dna.stats["wins"] += 1
138
  else: active_dna.stats["losses"] += 1
 
 
 
139
 
140
  except Exception as e:
141
  print(f"❌ [AdaptiveHub] Trade Analysis Error: {e}")
142
  traceback.print_exc()
143
 
 
 
 
144
  def _inject_current_parameters(self):
145
  """
146
+ نقل الإعدادات إلى SystemLimits.
147
+ الخدعة هنا: نقوم بتعيين وزن الهيكل (structure) إلى L2_WEIGHT_PATTERNS
148
+ لأن المعالج (Processor) يستخدم هذا المتغير لحساب الدرجة الهجينة.
149
  """
150
  if self.current_market_regime not in self.strategies:
151
  return
152
 
153
  active_dna = self.strategies[self.current_market_regime]
154
 
155
+ print(f"💉 [AdaptiveHub] Injecting DNA for: {self.current_market_regime}")
156
 
157
+ # 1. حقن أوزان L2
158
  mw = active_dna.model_weights
159
  total_w = sum(mw.values()) if sum(mw.values()) > 0 else 1.0
160
 
161
  SystemLimits.L2_WEIGHT_TITAN = mw.get("titan", 0.4) / total_w
 
 
162
 
163
+ # 🔥 التعديل الجوهري: نستخدم وزن 'structure' بدلاً من 'patterns'
164
+ # ونضعه في المتغير الذي يقرأه المعالج (Processor)
165
+ SystemLimits.L2_WEIGHT_PATTERNS = mw.get("structure", 0.3) / total_w
166
+
167
+ # 2. حقن عتبة الفلتر الهيكلي
168
  thresh_ratio = active_dna.filters.get("l1_min_score", 0.65)
169
  raw_score_limit = (thresh_ratio * 100.0) - 20.0
 
170
  SystemLimits.L1_MIN_AFFINITY_SCORE = raw_score_limit
171
 
172
+ # 3. باقي الإعدادات
173
  SystemLimits.CURRENT_REGIME = self.current_market_regime
 
 
174
  SystemLimits.L3_CONFIDENCE_THRESHOLD = active_dna.filters.get("l3_conf_thresh", 0.65)
175
  SystemLimits.L4_OB_WALL_RATIO = active_dna.ob_settings.get("wall_ratio_limit", 0.4)
176
 
 
181
  SystemLimits.LEGACY_V2_PANIC_THRESH = gs.get('legacy_v2', 0.95)
182
  SystemLimits.LEGACY_V3_HARD_THRESH = gs.get('legacy_v3', 0.95)
183
 
 
 
 
184
  def update_market_regime(self, new_regime: str):
185
  if new_regime in self.strategies:
186
  self.current_market_regime = new_regime
 
191
  dna = self.strategies.get(self.current_market_regime)
192
  if not dna: return "System Initializing..."
193
 
 
194
  thresh_ratio = dna.filters.get('l1_min_score', 0)
 
195
 
196
+ # عرض الحالة مع الأوزان الجديدة
197
  return (f"Regime: {self.current_market_regime} | "
198
+ f"L1 Thresh: {thresh_ratio:.0%} | "
199
+ f"Titan: {dna.model_weights.get('titan'):.2f} | "
200
+ f"Struct: {dna.model_weights.get('structure'):.2f}")
201
 
202
  async def _save_state_to_r2(self):
203
  if not self.r2: return