Riy777 commited on
Commit
20dcc06
·
verified ·
1 Parent(s): 9133da3

Update learning_hub/adaptive_hub.py

Browse files
Files changed (1) hide show
  1. learning_hub/adaptive_hub.py +17 -136
learning_hub/adaptive_hub.py CHANGED
@@ -1,26 +1,22 @@
1
  # ==============================================================================
2
  # 🧠 learning_hub/adaptive_hub.py
3
- # (V53.0 - GEM-Architect: Structure-Aware Core)
4
  # ==============================================================================
5
 
6
  import json
7
  import asyncio
8
  import traceback
9
- from datetime import datetime
10
- from collections import deque
11
- from typing import Dict, Any, List, Optional
12
 
13
- # استيراد الحدود المركزية
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):
@@ -36,168 +32,54 @@ class StrategyDNA:
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:
51
  data_bytes = await self.r2.get_file_async(self.dna_file_key)
52
  if data_bytes:
53
  saved_data = json.loads(data_bytes)
54
  self._load_from_dict(saved_data)
55
- print("✅ [AdaptiveHub] DNA Loaded Successfully.")
56
  else:
57
- print("⚠️ [AdaptiveHub] No DNA found. Creating Default Genomes.")
58
  self._create_default_dna()
59
  else:
60
  self._create_default_dna()
61
-
62
  self._inject_current_parameters()
63
-
64
- except Exception as e:
65
- print(f"❌ [AdaptiveHub] Init Failed: {e}")
66
- traceback.print_exc()
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
106
- )
107
 
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"],
122
- ob_settings=val["ob_settings"],
123
- filters=val["filters"],
124
- guard_settings=val.get("guard_settings", {})
125
- )
126
- self.strategies[key].stats = val.get("stats", {"wins":0, "losses":0})
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
134
-
135
- if self.current_market_regime in self.strategies:
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
-
177
- gs = active_dna.guard_settings
178
- if gs:
179
- SystemLimits.HYDRA_CRASH_THRESH = gs.get('hydra_crash', 0.60)
180
- SystemLimits.HYDRA_GIVEBACK_THRESH = gs.get('hydra_giveback', 0.70)
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
187
- print(f"🔄 [AdaptiveHub] Regime Switched to: {new_regime}")
188
- self._inject_current_parameters()
189
-
190
- def get_status(self):
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
@@ -207,5 +89,4 @@ class AdaptiveHub:
207
  "strategies": {k: v.to_dict() for k, v in self.strategies.items()}
208
  }
209
  await self.r2.upload_json_async(data, self.dna_file_key)
210
- except Exception as e:
211
- print(f"❌ [AdaptiveHub] Save Failed: {e}")
 
1
  # ==============================================================================
2
  # 🧠 learning_hub/adaptive_hub.py
3
+ # (V54.0 - GEM-Architect: Time Lord Support)
4
  # ==============================================================================
5
 
6
  import json
7
  import asyncio
8
  import traceback
9
+ from typing import Dict, Any, List
 
 
10
 
 
11
  from ml_engine.processor import SystemLimits
12
 
13
  class StrategyDNA:
14
  def __init__(self, name, model_weights, ob_settings, filters, guard_settings=None):
15
  self.name = name
16
+ self.model_weights = model_weights
17
+ self.ob_settings = ob_settings
18
+ self.filters = filters
19
+ self.guard_settings = guard_settings if guard_settings else {}
 
20
  self.stats = {"wins": 0, "losses": 0, "win_rate": 0.0}
21
 
22
  def to_dict(self):
 
32
  class AdaptiveHub:
33
  def __init__(self, r2_service=None):
34
  self.r2 = r2_service
 
35
  self.dna_file_key = "learning/strategic_dna_v5_struct.json"
36
  self.current_market_regime = "RANGE"
37
  self.strategies: Dict[str, StrategyDNA] = {}
38
+ print("🧠 [AdaptiveHub V54.0] Time Lord Core Initialized.")
 
 
39
 
40
  async def initialize(self):
 
41
  try:
42
  if self.r2:
43
  data_bytes = await self.r2.get_file_async(self.dna_file_key)
44
  if data_bytes:
45
  saved_data = json.loads(data_bytes)
46
  self._load_from_dict(saved_data)
 
47
  else:
 
48
  self._create_default_dna()
49
  else:
50
  self._create_default_dna()
 
51
  self._inject_current_parameters()
52
+ except Exception:
 
 
 
53
  self._create_default_dna()
54
 
55
  def _create_default_dna(self):
56
+ default_guards = {"hydra_crash": 0.85, "hydra_giveback": 0.70, "legacy_v2": 0.95, "legacy_v3": 0.95}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ self.strategies["BULL"] = StrategyDNA("BULL", {"titan": 0.50, "structure": 0.30, "sniper": 0.20}, {"wall_ratio_limit": 0.60, "imbalance_thresh": 0.5}, {"l1_min_score": 0.55, "l3_conf_thresh": 0.60}, default_guards)
59
+ self.strategies["BEAR"] = StrategyDNA("BEAR", {"titan": 0.30, "structure": 0.40, "sniper": 0.30}, {"wall_ratio_limit": 0.30, "imbalance_thresh": 0.7}, {"l1_min_score": 0.75, "l3_conf_thresh": 0.75}, default_guards)
60
+ self.strategies["RANGE"] = StrategyDNA("RANGE", {"titan": 0.40, "structure": 0.40, "sniper": 0.20}, {"wall_ratio_limit": 0.40, "imbalance_thresh": 0.6}, {"l1_min_score": 0.65, "l3_conf_thresh": 0.65}, default_guards)
61
+ self.strategies["DEAD"] = StrategyDNA("DEAD", {"titan": 0.25, "structure": 0.25, "sniper": 0.25}, {"wall_ratio_limit": 0.20, "imbalance_thresh": 0.8}, {"l1_min_score": 0.85, "l3_conf_thresh": 0.80}, default_guards)
 
 
 
 
62
 
63
  def _load_from_dict(self, data):
64
  for key, val in data.get("strategies", {}).items():
65
+ self.strategies[key] = StrategyDNA(val["name"], val["model_weights"], val["ob_settings"], val["filters"], val.get("guard_settings", {}))
 
 
 
 
 
 
 
 
66
  self.current_market_regime = data.get("current_regime", "RANGE")
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  def _inject_current_parameters(self):
69
+ if self.current_market_regime not in self.strategies: return
 
 
 
 
 
 
 
70
  active_dna = self.strategies[self.current_market_regime]
71
 
 
 
 
72
  mw = active_dna.model_weights
73
  total_w = sum(mw.values()) if sum(mw.values()) > 0 else 1.0
74
 
75
  SystemLimits.L2_WEIGHT_TITAN = mw.get("titan", 0.4) / total_w
 
 
 
76
  SystemLimits.L2_WEIGHT_PATTERNS = mw.get("structure", 0.3) / total_w
77
 
78
+ raw_score_limit = (active_dna.filters.get("l1_min_score", 0.65) * 100.0) - 20.0
 
 
79
  SystemLimits.L1_MIN_AFFINITY_SCORE = raw_score_limit
 
 
80
  SystemLimits.CURRENT_REGIME = self.current_market_regime
81
  SystemLimits.L3_CONFIDENCE_THRESHOLD = active_dna.filters.get("l3_conf_thresh", 0.65)
82
  SystemLimits.L4_OB_WALL_RATIO = active_dna.ob_settings.get("wall_ratio_limit", 0.4)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  async def _save_state_to_r2(self):
85
  if not self.r2: return
 
89
  "strategies": {k: v.to_dict() for k, v in self.strategies.items()}
90
  }
91
  await self.r2.upload_json_async(data, self.dna_file_key)
92
+ except Exception: pass