Spaces:
Paused
Paused
Update trade_manager.py
Browse files- trade_manager.py +46 -19
trade_manager.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# ============================================================
|
| 2 |
-
# 🛡️ trade_manager.py (
|
| 3 |
# ============================================================
|
| 4 |
|
| 5 |
import asyncio
|
|
@@ -9,10 +9,11 @@ import traceback
|
|
| 9 |
from datetime import datetime
|
| 10 |
from typing import List, Dict, Any
|
| 11 |
|
| 12 |
-
# استيراد
|
| 13 |
from smart_portfolio import SmartPortfolio
|
| 14 |
-
# ✅ استيراد الحدود المركزية لقراءة الإعدادات الحية (للحراس)
|
| 15 |
from ml_engine.processor import SystemLimits
|
|
|
|
|
|
|
| 16 |
|
| 17 |
class TradeManager:
|
| 18 |
def __init__(self, r2_service, data_manager, processor):
|
|
@@ -23,12 +24,15 @@ class TradeManager:
|
|
| 23 |
# ✅ سيتم حقنه من الخارج لربط حلقة التعلم
|
| 24 |
self.learning_hub = None
|
| 25 |
|
|
|
|
| 26 |
self.smart_portfolio = SmartPortfolio(r2_service, data_manager)
|
|
|
|
|
|
|
| 27 |
self.open_positions = {}
|
| 28 |
self.watchlist = {}
|
| 29 |
self.sentry_tasks = {}
|
| 30 |
self.running = True
|
| 31 |
-
self.latest_guardian_log = "🛡️ Guardian &
|
| 32 |
self.FEE_RATE = 0.001
|
| 33 |
self.ORACLE_CHECK_INTERVAL = 900
|
| 34 |
|
|
@@ -41,7 +45,7 @@ class TradeManager:
|
|
| 41 |
}
|
| 42 |
|
| 43 |
self.execution_lock = asyncio.Lock()
|
| 44 |
-
print(f"🛡️ [TradeManager
|
| 45 |
|
| 46 |
async def initialize_sentry_exchanges(self):
|
| 47 |
"""تهيئة المحفظة واستعادة الحالة"""
|
|
@@ -140,10 +144,37 @@ class TradeManager:
|
|
| 140 |
await self._execute_entry_from_signal(best_signal['symbol'], best_signal)
|
| 141 |
|
| 142 |
async def _execute_entry_from_signal(self, symbol, signal_data):
|
| 143 |
-
"""تنفيذ الدخول الفعلي مع إدارة المحفظة"""
|
| 144 |
try:
|
| 145 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
is_approved, plan = await self.smart_portfolio.request_entry_approval(signal_data, len(self.open_positions))
|
|
|
|
| 147 |
if not is_approved:
|
| 148 |
print(f"⛔ [Portfolio Rejection] {symbol}: {plan.get('reason')}")
|
| 149 |
return
|
|
@@ -161,11 +192,13 @@ class TradeManager:
|
|
| 161 |
|
| 162 |
# حفظ تفاصيل القرار كاملة من أجل التعلم
|
| 163 |
decision_snapshot = {
|
| 164 |
-
'components': signal_data.get('components', {}),
|
| 165 |
'oracle_conf': signal_data.get('confidence', 0),
|
|
|
|
|
|
|
| 166 |
'system_confidence': system_conf,
|
| 167 |
'market_mood': market_mood,
|
| 168 |
-
'regime_at_entry': getattr(SystemLimits, 'CURRENT_REGIME', 'UNKNOWN')
|
| 169 |
}
|
| 170 |
|
| 171 |
new_trade = {
|
|
@@ -179,7 +212,7 @@ class TradeManager:
|
|
| 179 |
'sl_price': float(signal_data.get('sl_price', current_price * 0.95)),
|
| 180 |
'last_update': datetime.now().isoformat(),
|
| 181 |
'last_oracle_check': datetime.now().isoformat(),
|
| 182 |
-
'strategy': '
|
| 183 |
'initial_oracle_strength': float(signal_data.get('strength', 0.5)),
|
| 184 |
'initial_oracle_class': signal_data.get('target_class', 'TP2'),
|
| 185 |
'oracle_tp_map': signal_data.get('tp_map', {}),
|
|
@@ -187,7 +220,7 @@ class TradeManager:
|
|
| 187 |
'entry_fee_usd': entry_fee_usd,
|
| 188 |
'l1_score': float(signal_data.get('enhanced_final_score', 0.0)),
|
| 189 |
'target_class_int': 3,
|
| 190 |
-
'decision_data': decision_snapshot,
|
| 191 |
'highest_price': current_price
|
| 192 |
}
|
| 193 |
|
|
@@ -209,7 +242,7 @@ class TradeManager:
|
|
| 209 |
if symbol in self.sentry_tasks: self.sentry_tasks[symbol].cancel()
|
| 210 |
self.sentry_tasks[symbol] = asyncio.create_task(self._guardian_loop(symbol))
|
| 211 |
|
| 212 |
-
print(f"✅ [ENTRY] {symbol} @ {current_price} | Size: ${approved_size_usd:.2f} | TP: {approved_tp} ({target_label}) |
|
| 213 |
|
| 214 |
except Exception as e:
|
| 215 |
print(f"❌ [Entry Error] {symbol}: {e}")
|
|
@@ -360,8 +393,6 @@ class TradeManager:
|
|
| 360 |
curr = await self.data_manager.get_latest_price_async(symbol)
|
| 361 |
if curr == 0: return
|
| 362 |
|
| 363 |
-
# إذا بعنا، والسعر هبط -> خروج جيد (وفرنا خسارة أو حفظنا ربح)
|
| 364 |
-
# إذا بعنا، والسعر صعد -> خروج سيء (فوتنا ربح)
|
| 365 |
change_pct = (curr - exit_price) / exit_price
|
| 366 |
usd_impact = change_pct * position_size_usd
|
| 367 |
is_good_exit = change_pct < 0
|
|
@@ -374,8 +405,6 @@ class TradeManager:
|
|
| 374 |
|
| 375 |
record = {"symbol": symbol, "exit_price": exit_price, "price_15m": curr, "usd_impact": usd_impact, "verdict": "SUCCESS" if is_good_exit else "MISS"}
|
| 376 |
await self.r2.append_deep_steward_audit(record)
|
| 377 |
-
|
| 378 |
-
# (يمكن إضافة هذا السجل للتعلم أيضاً، لكننا اعتمدنا على register_trade_outcome الفوري)
|
| 379 |
except Exception: pass
|
| 380 |
|
| 381 |
async def _execute_exit(self, symbol, price, reason, ai_scores=None):
|
|
@@ -425,10 +454,9 @@ class TradeManager:
|
|
| 425 |
self._launch_post_exit_analysis(symbol, exit_price, trade.get('exit_time'), entry_capital, ai_scores, trade)
|
| 426 |
|
| 427 |
# ==========================================================
|
| 428 |
-
# 🧠 THE TACTICAL LEARNING LINK
|
| 429 |
# ==========================================================
|
| 430 |
if self.learning_hub:
|
| 431 |
-
# نرسل الصفقة للمركز التعليمي ليقوم بمكافأة/عقاب النماذج
|
| 432 |
print(f"🎓 [Learning] Reporting trade outcome to AdaptiveHub...")
|
| 433 |
asyncio.create_task(self.learning_hub.register_trade_outcome(trade))
|
| 434 |
# ==========================================================
|
|
@@ -438,7 +466,6 @@ class TradeManager:
|
|
| 438 |
|
| 439 |
except Exception as e:
|
| 440 |
print(f"❌ [Exit Error] {e}"); traceback.print_exc()
|
| 441 |
-
# استعادة الصفقة في حالة الخطأ
|
| 442 |
if symbol not in self.open_positions: self.open_positions[symbol] = trade
|
| 443 |
|
| 444 |
async def force_exit_by_manager(self, symbol, reason):
|
|
|
|
| 1 |
# ============================================================
|
| 2 |
+
# 🛡️ trade_manager.py (V37.0 - GEM-Architect: Governance Integrated)
|
| 3 |
# ============================================================
|
| 4 |
|
| 5 |
import asyncio
|
|
|
|
| 9 |
from datetime import datetime
|
| 10 |
from typing import List, Dict, Any
|
| 11 |
|
| 12 |
+
# استيراد المكونات الأساسية
|
| 13 |
from smart_portfolio import SmartPortfolio
|
|
|
|
| 14 |
from ml_engine.processor import SystemLimits
|
| 15 |
+
# ✅ استيراد محرك الحوكمة الجديد (مجلس الشيوخ)
|
| 16 |
+
from governance_engine import GovernanceEngine
|
| 17 |
|
| 18 |
class TradeManager:
|
| 19 |
def __init__(self, r2_service, data_manager, processor):
|
|
|
|
| 24 |
# ✅ سيتم حقنه من الخارج لربط حلقة التعلم
|
| 25 |
self.learning_hub = None
|
| 26 |
|
| 27 |
+
# تهيئة المحفظة والحوكمة
|
| 28 |
self.smart_portfolio = SmartPortfolio(r2_service, data_manager)
|
| 29 |
+
self.governance = GovernanceEngine() # 🏛️ تفعيل مجلس الحوكمة
|
| 30 |
+
|
| 31 |
self.open_positions = {}
|
| 32 |
self.watchlist = {}
|
| 33 |
self.sentry_tasks = {}
|
| 34 |
self.running = True
|
| 35 |
+
self.latest_guardian_log = "🛡️ Guardian & Governance Systems Online."
|
| 36 |
self.FEE_RATE = 0.001
|
| 37 |
self.ORACLE_CHECK_INTERVAL = 900
|
| 38 |
|
|
|
|
| 45 |
}
|
| 46 |
|
| 47 |
self.execution_lock = asyncio.Lock()
|
| 48 |
+
print(f"🛡️ [TradeManager V37.0] Full System Online (Governance Layer Active).")
|
| 49 |
|
| 50 |
async def initialize_sentry_exchanges(self):
|
| 51 |
"""تهيئة المحفظة واستعادة الحالة"""
|
|
|
|
| 144 |
await self._execute_entry_from_signal(best_signal['symbol'], best_signal)
|
| 145 |
|
| 146 |
async def _execute_entry_from_signal(self, symbol, signal_data):
|
| 147 |
+
"""تنفيذ الدخول الفعلي مع فحص الحوكمة وإدارة المحفظة"""
|
| 148 |
try:
|
| 149 |
+
# 🏛️ الخطوة 1: استشارة مجلس الحوكمة (Governance Layer)
|
| 150 |
+
# نحتاج إلى تجميع البيانات المطلوبة للحوكمة (خاصة فريم 15 دقيقة)
|
| 151 |
+
print(f" 🏛️ [Governance] Convening Senate for {symbol}...")
|
| 152 |
+
|
| 153 |
+
t15_task = self.data_manager.get_latest_ohlcv(symbol, '15m', 200)
|
| 154 |
+
t1h_task = self.data_manager.get_latest_ohlcv(symbol, '1h', 200)
|
| 155 |
+
ob_task = self.data_manager.get_order_book_snapshot(symbol)
|
| 156 |
+
|
| 157 |
+
t15, t1h, ob = await asyncio.gather(t15_task, t1h_task, ob_task)
|
| 158 |
+
|
| 159 |
+
ohlcv_dict = {'15m': t15, '1h': t1h}
|
| 160 |
+
|
| 161 |
+
# تقييم الحوكمة
|
| 162 |
+
gov_decision = await self.governance.evaluate_trade(symbol, ohlcv_dict, ob)
|
| 163 |
+
|
| 164 |
+
if gov_decision['grade'] == 'REJECT':
|
| 165 |
+
print(f"⛔ [Governance VETO] {symbol} Rejected by Senate. Grade: REJECT | Score: {gov_decision['governance_score']:.1f}")
|
| 166 |
+
return # إيقاف التنفيذ فوراً
|
| 167 |
+
|
| 168 |
+
print(f" ✅ [Governance PASS] Grade: {gov_decision['grade']} | Score: {gov_decision['governance_score']:.1f}")
|
| 169 |
+
|
| 170 |
+
# دمج نتائج الحوكمة في بيانات الإشارة لتراها المحفظة
|
| 171 |
+
signal_data['governance_grade'] = gov_decision['grade']
|
| 172 |
+
signal_data['governance_score'] = gov_decision['governance_score']
|
| 173 |
+
signal_data['governance_details'] = gov_decision['components']
|
| 174 |
+
|
| 175 |
+
# 💰 الخطوة 2: طلب الموافقة من المحفظة الذكية (تستخدم الـ Grade لتحديد الحجم)
|
| 176 |
is_approved, plan = await self.smart_portfolio.request_entry_approval(signal_data, len(self.open_positions))
|
| 177 |
+
|
| 178 |
if not is_approved:
|
| 179 |
print(f"⛔ [Portfolio Rejection] {symbol}: {plan.get('reason')}")
|
| 180 |
return
|
|
|
|
| 192 |
|
| 193 |
# حفظ تفاصيل القرار كاملة من أجل التعلم
|
| 194 |
decision_snapshot = {
|
| 195 |
+
'components': signal_data.get('components', {}),
|
| 196 |
'oracle_conf': signal_data.get('confidence', 0),
|
| 197 |
+
'governance_grade': gov_decision['grade'], # تسجيل الجودة
|
| 198 |
+
'governance_score': gov_decision['governance_score'],
|
| 199 |
'system_confidence': system_conf,
|
| 200 |
'market_mood': market_mood,
|
| 201 |
+
'regime_at_entry': getattr(SystemLimits, 'CURRENT_REGIME', 'UNKNOWN')
|
| 202 |
}
|
| 203 |
|
| 204 |
new_trade = {
|
|
|
|
| 212 |
'sl_price': float(signal_data.get('sl_price', current_price * 0.95)),
|
| 213 |
'last_update': datetime.now().isoformat(),
|
| 214 |
'last_oracle_check': datetime.now().isoformat(),
|
| 215 |
+
'strategy': 'OracleV4_Governance_Hydra',
|
| 216 |
'initial_oracle_strength': float(signal_data.get('strength', 0.5)),
|
| 217 |
'initial_oracle_class': signal_data.get('target_class', 'TP2'),
|
| 218 |
'oracle_tp_map': signal_data.get('tp_map', {}),
|
|
|
|
| 220 |
'entry_fee_usd': entry_fee_usd,
|
| 221 |
'l1_score': float(signal_data.get('enhanced_final_score', 0.0)),
|
| 222 |
'target_class_int': 3,
|
| 223 |
+
'decision_data': decision_snapshot,
|
| 224 |
'highest_price': current_price
|
| 225 |
}
|
| 226 |
|
|
|
|
| 242 |
if symbol in self.sentry_tasks: self.sentry_tasks[symbol].cancel()
|
| 243 |
self.sentry_tasks[symbol] = asyncio.create_task(self._guardian_loop(symbol))
|
| 244 |
|
| 245 |
+
print(f"✅ [ENTRY] {symbol} @ {current_price} | Grade: {gov_decision['grade']} | Size: ${approved_size_usd:.2f} | TP: {approved_tp} ({target_label}) | Mood: {market_mood}")
|
| 246 |
|
| 247 |
except Exception as e:
|
| 248 |
print(f"❌ [Entry Error] {symbol}: {e}")
|
|
|
|
| 393 |
curr = await self.data_manager.get_latest_price_async(symbol)
|
| 394 |
if curr == 0: return
|
| 395 |
|
|
|
|
|
|
|
| 396 |
change_pct = (curr - exit_price) / exit_price
|
| 397 |
usd_impact = change_pct * position_size_usd
|
| 398 |
is_good_exit = change_pct < 0
|
|
|
|
| 405 |
|
| 406 |
record = {"symbol": symbol, "exit_price": exit_price, "price_15m": curr, "usd_impact": usd_impact, "verdict": "SUCCESS" if is_good_exit else "MISS"}
|
| 407 |
await self.r2.append_deep_steward_audit(record)
|
|
|
|
|
|
|
| 408 |
except Exception: pass
|
| 409 |
|
| 410 |
async def _execute_exit(self, symbol, price, reason, ai_scores=None):
|
|
|
|
| 454 |
self._launch_post_exit_analysis(symbol, exit_price, trade.get('exit_time'), entry_capital, ai_scores, trade)
|
| 455 |
|
| 456 |
# ==========================================================
|
| 457 |
+
# 🧠 THE TACTICAL LEARNING LINK
|
| 458 |
# ==========================================================
|
| 459 |
if self.learning_hub:
|
|
|
|
| 460 |
print(f"🎓 [Learning] Reporting trade outcome to AdaptiveHub...")
|
| 461 |
asyncio.create_task(self.learning_hub.register_trade_outcome(trade))
|
| 462 |
# ==========================================================
|
|
|
|
| 466 |
|
| 467 |
except Exception as e:
|
| 468 |
print(f"❌ [Exit Error] {e}"); traceback.print_exc()
|
|
|
|
| 469 |
if symbol not in self.open_positions: self.open_positions[symbol] = trade
|
| 470 |
|
| 471 |
async def force_exit_by_manager(self, symbol, reason):
|