|
|
|
|
|
|
|
|
import asyncio |
|
|
from typing import Any, Dict |
|
|
|
|
|
|
|
|
from .schemas import * |
|
|
from .policy_engine import PolicyEngine |
|
|
from .memory_store import MemoryStore |
|
|
from .statistical_analyzer import StatisticalAnalyzer |
|
|
from .reflector import Reflector |
|
|
from .curator import Curator |
|
|
|
|
|
class LearningHubManager: |
|
|
def __init__(self, r2_service: Any, llm_service: Any, data_manager: Any): |
|
|
print("🚀 Initializing Learning Hub Manager...") |
|
|
|
|
|
|
|
|
self.r2_service = r2_service |
|
|
self.llm_service = llm_service |
|
|
self.data_manager = data_manager |
|
|
|
|
|
|
|
|
self.policy_engine = PolicyEngine() |
|
|
self.memory_store = MemoryStore( |
|
|
r2_service=self.r2_service, |
|
|
policy_engine=self.policy_engine, |
|
|
llm_service=self.llm_service |
|
|
) |
|
|
self.reflector = Reflector( |
|
|
llm_service=self.llm_service, |
|
|
memory_store=self.memory_store |
|
|
) |
|
|
self.curator = Curator( |
|
|
llm_service=self.llm_service, |
|
|
memory_store=self.memory_store |
|
|
) |
|
|
self.statistical_analyzer = StatisticalAnalyzer( |
|
|
r2_service=self.r2_service, |
|
|
data_manager=self.data_manager |
|
|
) |
|
|
|
|
|
self.initialized = False |
|
|
print("✅ Learning Hub Manager constructed. Ready for initialization.") |
|
|
|
|
|
async def initialize(self): |
|
|
""" |
|
|
تهيئة جميع الأنظمة الفرعية، وخاصة تحميل الإحصائيات والأوزان. |
|
|
""" |
|
|
if self.initialized: |
|
|
return |
|
|
|
|
|
print("🔄 [HubManager] Initializing all sub-modules...") |
|
|
await self.statistical_analyzer.initialize() |
|
|
self.initialized = True |
|
|
print("✅ [HubManager] All sub-modules initialized. Learning Hub is LIVE.") |
|
|
|
|
|
async def analyze_trade_and_learn(self, trade_object: Dict[str, Any], close_reason: str): |
|
|
""" |
|
|
هذه هي الدالة الرئيسية التي يستدعيها TradeManager. |
|
|
إنها تشغل كلاً من نظام التعلم السريع (Reflector) والبطيء (StatsAnalyzer). |
|
|
""" |
|
|
if not self.initialized: |
|
|
print("⚠️ [HubManager] Learning Hub not initialized. Skipping learning.") |
|
|
return |
|
|
|
|
|
print(f"🧠 [HubManager] Learning from trade {trade_object.get('symbol')}...") |
|
|
|
|
|
try: |
|
|
|
|
|
await self.reflector.analyze_trade_outcome(trade_object, close_reason) |
|
|
except Exception as e: |
|
|
print(f"❌ [HubManager] Reflector (Fast-Learner) failed: {e}") |
|
|
|
|
|
try: |
|
|
|
|
|
await self.statistical_analyzer.update_statistics(trade_object, close_reason) |
|
|
except Exception as e: |
|
|
print(f"❌ [HubManager] StatisticalAnalyzer (Slow-Learner) failed: {e}") |
|
|
|
|
|
print(f"✅ [HubManager] Learning complete for {trade_object.get('symbol')}.") |
|
|
|
|
|
async def get_active_context_for_llm(self, domain: str, query: str) -> str: |
|
|
""" |
|
|
يُستخدم بواسطة LLMService لجلب "الدفتر" (Playbook) / القواعد (Deltas). |
|
|
""" |
|
|
if not self.initialized: |
|
|
return "Learning Hub not initialized." |
|
|
|
|
|
return await self.memory_store.get_active_context(domain, query) |
|
|
|
|
|
async def get_statistical_feedback_for_llm(self, entry_strategy: str) -> str: |
|
|
""" |
|
|
يُستخدم بواسطة LLMService لجلب أفضل ملف خروج (إحصائياً). |
|
|
""" |
|
|
if not self.initialized: |
|
|
return "Learning Hub not initialized." |
|
|
|
|
|
best_profile = await self.statistical_analyzer.get_best_exit_profile(entry_strategy) |
|
|
|
|
|
if best_profile != "unknown": |
|
|
|
|
|
feedback = f"Statistical Feedback: For the '{entry_strategy}' strategy, the '{best_profile}' exit profile has historically performed best." |
|
|
return feedback |
|
|
else: |
|
|
return "No statistical feedback available for this strategy yet." |
|
|
|
|
|
|
|
|
async def get_statistical_news_score(self, raw_vader_score: float) -> float: |
|
|
""" |
|
|
يحول درجة VADER الخام إلى متوسط الربح/الخسارة التاريخي المتوقع. |
|
|
(يُستخدم بواسطة app.py / MLProcessor للترتيب الداخلي) |
|
|
""" |
|
|
if not self.initialized: |
|
|
return 0.0 |
|
|
|
|
|
|
|
|
historical_pnl = await self.statistical_analyzer.get_statistical_vader_pnl(raw_vader_score) |
|
|
|
|
|
|
|
|
return historical_pnl |
|
|
|
|
|
|
|
|
|
|
|
async def get_optimized_weights(self, market_condition: str) -> Dict[str, float]: |
|
|
""" |
|
|
يُستخدم بواسطة MLProcessor/StrategyEngine/Sentry لجلب الأوزان المعدلة إحصائياً. |
|
|
""" |
|
|
if not self.initialized: |
|
|
|
|
|
return await self.statistical_analyzer.get_default_strategy_weights() |
|
|
|
|
|
|
|
|
return await self.statistical_analyzer.get_optimized_weights(market_condition) |
|
|
|
|
|
|
|
|
async def run_distillation_check(self): |
|
|
""" |
|
|
(يتم استدعاؤها دورياً من app.py) |
|
|
للتحقق من جميع المجالات وتشغيل التقطير إذا لزم الأمر. |
|
|
""" |
|
|
if not self.initialized: |
|
|
return |
|
|
|
|
|
print("ℹ️ [HubManager] Running periodic distillation check...") |
|
|
for domain in self.memory_store.domain_files.keys(): |
|
|
await self.curator.check_and_distill_domain(domain) |
|
|
print("✅ [HubManager] Distillation check complete.") |
|
|
|
|
|
|
|
|
async def shutdown(self): |
|
|
""" |
|
|
Saves all persistent data from the statistical analyzer. |
|
|
""" |
|
|
if not self.initialized: |
|
|
return |
|
|
|
|
|
print("🔄 [HubManager] Shutting down... Saving all learning data.") |
|
|
try: |
|
|
await self.statistical_analyzer.save_weights_to_r2() |
|
|
await self.statistical_analyzer.save_performance_history() |
|
|
await self.statistical_analyzer.save_exit_profile_effectiveness() |
|
|
|
|
|
await self.statistical_analyzer.save_vader_effectiveness() |
|
|
|
|
|
print("✅ [HubManager] All statistical (slow-learner) data saved.") |
|
|
except Exception as e: |
|
|
print(f"❌ [HubManager] Failed to save learning data on shutdown: {e}") |
|
|
|
|
|
|
|
|
|