|
|
|
|
|
from .schemas import ReflectorOutput |
|
|
import json |
|
|
|
|
|
class PolicyEngine: |
|
|
def __init__(self): |
|
|
|
|
|
self.auto_accept_threshold: float = 0.80 |
|
|
|
|
|
|
|
|
|
|
|
self.human_review_loss_threshold_percent: float = -3.0 |
|
|
|
|
|
|
|
|
self.admissibility_rules = { |
|
|
"NO_SHORT_TRADES": "النظام لا يدعم صفقات SHORT.", |
|
|
"MAX_LOSS_PER_TRADE": "يجب ألا يتجاوز وقف الخسارة الأولي 10%." |
|
|
} |
|
|
print("✅ Learning Hub Module: Policy Engine loaded") |
|
|
|
|
|
def get_delta_acceptance(self, reflector_output: ReflectorOutput, trade_pnl_percent: float) -> (bool, str): |
|
|
""" |
|
|
يحدد ما إذا كان يجب قبول "الدلتا" المقترحة تلقائياً أم إرسالها للمراجعة. |
|
|
(تنفيذ النقطة 5 و 7) |
|
|
""" |
|
|
|
|
|
|
|
|
if trade_pnl_percent < self.human_review_loss_threshold_percent: |
|
|
reason = f"Human Review Required: Significant loss ({trade_pnl_percent:.2f}%)" |
|
|
print(f"⚠️ [PolicyEngine] {reason}") |
|
|
return False, reason |
|
|
|
|
|
|
|
|
reflector_confidence = reflector_output.confidence |
|
|
|
|
|
|
|
|
|
|
|
delta_score = reflector_confidence |
|
|
|
|
|
if delta_score >= self.auto_accept_threshold: |
|
|
reason = f"Auto-Accepted: High confidence ({delta_score:.2f} >= {self.auto_accept_threshold})" |
|
|
print(f"✅ [PolicyEngine] {reason}") |
|
|
return True, reason |
|
|
else: |
|
|
reason = f"Human Review Required: Low confidence ({delta_score:.2f} < {self.auto_accept_threshold})" |
|
|
print(f"ℹ️ [PolicyEngine] {reason}") |
|
|
return False, reason |
|
|
|
|
|
def check_meta_policy_on_decision(self, decision: dict) -> (bool, str): |
|
|
""" |
|
|
يفحص قرار (قبل التنفيذ) مقابل قواعد السلامة العليا (Meta-Policy). |
|
|
(تنفيذ النقطة 7) |
|
|
""" |
|
|
|
|
|
|
|
|
if decision.get("trade_type") == "SHORT": |
|
|
return False, self.admissibility_rules["NO_SHORT_TRADES"] |
|
|
|
|
|
|
|
|
action = decision.get("action") |
|
|
if action == "BUY": |
|
|
current_price = decision.get("current_price", 1) |
|
|
stop_loss = decision.get("stop_loss", 0) |
|
|
|
|
|
if current_price > 0 and stop_loss > 0: |
|
|
loss_percent = ((current_price - stop_loss) / current_price) * 100 |
|
|
if loss_percent > 10.0: |
|
|
reason = f"Meta-Policy Violation: Stop loss ({loss_percent:.1f}%) exceeds max (10%)" |
|
|
return False, reason |
|
|
|
|
|
|
|
|
return True, "Meta-Policy Passed" |