Spaces:
Paused
Paused
Update trade_manager.py
Browse files- trade_manager.py +29 -95
trade_manager.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# trade_manager.py (V23.
|
| 2 |
|
| 3 |
import asyncio
|
| 4 |
import uuid
|
|
@@ -9,17 +9,9 @@ from typing import List, Dict, Any
|
|
| 9 |
|
| 10 |
class TradeManager:
|
| 11 |
def __init__(self, r2_service, data_manager, processor):
|
| 12 |
-
"""
|
| 13 |
-
مدير الصفقات: المسؤول التنفيذي.
|
| 14 |
-
ينسق بين البيانات (Data)، العقل (Processor)، ومركز التعلم (Learning Hub).
|
| 15 |
-
"""
|
| 16 |
self.r2 = r2_service
|
| 17 |
self.data_manager = data_manager
|
| 18 |
-
|
| 19 |
-
# 🧠 The Central Brain (Titan, Oracle, Sniper, Guardian)
|
| 20 |
self.processor = processor
|
| 21 |
-
|
| 22 |
-
# 🎓 Learning Hub (سيتم حقنه من app.py)
|
| 23 |
self.learning_hub = None
|
| 24 |
|
| 25 |
self.open_positions = {}
|
|
@@ -27,7 +19,6 @@ class TradeManager:
|
|
| 27 |
self.sentry_tasks = {}
|
| 28 |
self.running = True
|
| 29 |
|
| 30 |
-
# [ 🧠 IQ Stats ] إحصائيات الذكاء الاصطناعي للواجهة
|
| 31 |
self.ai_stats = {
|
| 32 |
"hybrid": {"total": 0, "good": 0, "saved": 0.0, "missed": 0.0},
|
| 33 |
"v2": {"total": 0, "good": 0, "saved": 0.0, "missed": 0.0},
|
|
@@ -35,8 +26,7 @@ class TradeManager:
|
|
| 35 |
}
|
| 36 |
|
| 37 |
self.execution_lock = asyncio.Lock()
|
| 38 |
-
|
| 39 |
-
print(f"🛡️ [TradeManager V23.8] Initialized (Sniper 60/40 & Learning Ready).")
|
| 40 |
|
| 41 |
async def initialize_sentry_exchanges(self):
|
| 42 |
print("🛡️ [TradeManager] Syncing state with R2...")
|
|
@@ -52,20 +42,13 @@ class TradeManager:
|
|
| 52 |
self.open_positions = {}
|
| 53 |
|
| 54 |
# ==============================================================================
|
| 55 |
-
# 🎯 L4 Sniper Logic
|
| 56 |
# ==============================================================================
|
| 57 |
async def select_and_execute_best_signal(self, oracle_approved_signals: List[Dict[str, Any]]):
|
| 58 |
-
"""
|
| 59 |
-
مرحلة الفرز النهائي (القناص):
|
| 60 |
-
- تجلب شموع الدقيقة + دفتر الطلبات.
|
| 61 |
-
- ترسلها للمعالج ليطبق معادلة (0.6*ML + 0.4*OB).
|
| 62 |
-
- تختار الأفضل وتنفذه.
|
| 63 |
-
"""
|
| 64 |
if len(self.open_positions) > 0:
|
| 65 |
print(f"⛔ [TradeManager] Scan aborted. Max positions reached.")
|
| 66 |
return
|
| 67 |
|
| 68 |
-
# التأكد من جاهزية المعالج
|
| 69 |
if not self.processor.initialized:
|
| 70 |
await self.processor.initialize()
|
| 71 |
|
|
@@ -77,69 +60,57 @@ class TradeManager:
|
|
| 77 |
if symbol in self.open_positions or symbol in self.watchlist:
|
| 78 |
continue
|
| 79 |
|
| 80 |
-
#
|
| 81 |
ohlcv_task = self.data_manager.get_latest_ohlcv(symbol, '1m', 600)
|
| 82 |
ob_task = self.data_manager.get_order_book_snapshot(symbol)
|
| 83 |
-
|
| 84 |
ohlcv_1m, order_book = await asyncio.gather(ohlcv_task, ob_task)
|
| 85 |
|
| 86 |
-
# التحقق من سلامة البيانات
|
| 87 |
if not ohlcv_1m or len(ohlcv_1m) < 500:
|
| 88 |
-
print(f" -> [L4 Skip] {symbol} (Not enough
|
| 89 |
continue
|
| 90 |
|
| 91 |
-
#
|
| 92 |
-
if not order_book:
|
| 93 |
-
print(f" ⚠️ [L4 Warn] {symbol} (Empty Order Book). Proceeding with ML only...")
|
| 94 |
-
|
| 95 |
-
# ⚡ استشارة القناص (Processor -> SniperEngine) ⚡
|
| 96 |
sniper_result = await self.processor.check_sniper_entry(ohlcv_1m, order_book)
|
| 97 |
|
| 98 |
-
# استخراج بيانات التقرير
|
| 99 |
reason_str = sniper_result.get('reason', 'N/A')
|
| 100 |
-
confidence = sniper_result.get('confidence_prob', 0.0)
|
| 101 |
|
| 102 |
if sniper_result['signal'] == 'BUY':
|
| 103 |
print(f" -> 🟢 [L4 PASS] {symbol} | Score: {confidence:.2f} | {reason_str}")
|
| 104 |
-
|
| 105 |
signal['l2_sniper_result'] = sniper_result
|
| 106 |
signal['sniper_confidence'] = confidence
|
| 107 |
sniper_candidates.append(signal)
|
| 108 |
else:
|
| 109 |
-
# طباعة سبب الرفض (سيوضح ما إذا كان السبب هو النموذج أو الدفتر)
|
| 110 |
print(f" -> 🔴 [L4 REJECT] {symbol} | {reason_str}")
|
| 111 |
|
| 112 |
if not sniper_candidates:
|
| 113 |
-
print(" -> [L4 Result] No candidates passed the Sniper
|
| 114 |
return
|
| 115 |
|
| 116 |
-
#
|
| 117 |
-
sniper_candidates.sort(
|
| 118 |
-
|
|
|
|
|
|
|
| 119 |
|
| 120 |
-
|
|
|
|
| 121 |
|
| 122 |
-
# التنفيذ الفعلي
|
| 123 |
async with self.execution_lock:
|
| 124 |
if len(self.open_positions) == 0 and best_signal['symbol'] not in self.open_positions:
|
| 125 |
await self._execute_entry_from_signal(best_signal['symbol'], best_signal)
|
| 126 |
|
| 127 |
# ==============================================================================
|
| 128 |
-
# 🎯 Entry Execution
|
| 129 |
# ==============================================================================
|
| 130 |
async def _execute_entry_from_signal(self, symbol, signal_data):
|
| 131 |
try:
|
| 132 |
trade_id = str(uuid.uuid4())
|
| 133 |
current_price = float(signal_data.get('current_price', 0.0))
|
| 134 |
-
|
| 135 |
-
# حماية: إذا السعر 0، اطلبه مرة أخرى
|
| 136 |
if current_price <= 0.0:
|
| 137 |
current_price = await self.data_manager.get_latest_price_async(symbol)
|
| 138 |
|
| 139 |
-
# بيانات القناص (للتخزين)
|
| 140 |
l2_result = signal_data.get('l2_sniper_result', {})
|
| 141 |
-
|
| 142 |
-
# الأهداف (من Oracle أو حساب تلقائي)
|
| 143 |
tp_price = float(signal_data.get('tp_price') or 0.0)
|
| 144 |
sl_price = float(signal_data.get('sl_price') or 0.0)
|
| 145 |
|
|
@@ -148,7 +119,6 @@ class TradeManager:
|
|
| 148 |
tp_price = current_price + (atr_mock * 2.0)
|
| 149 |
sl_price = current_price - (atr_mock * 1.0)
|
| 150 |
|
| 151 |
-
# بناء كائن الصفقة
|
| 152 |
new_trade = {
|
| 153 |
'id': trade_id,
|
| 154 |
'symbol': symbol,
|
|
@@ -158,12 +128,13 @@ class TradeManager:
|
|
| 158 |
'tp_price': tp_price,
|
| 159 |
'sl_price': sl_price,
|
| 160 |
'last_update': datetime.now().isoformat(),
|
| 161 |
-
|
| 162 |
-
# تخزين البيانات الوصفية للتعلم لاحقاً
|
| 163 |
'strategy': 'Hybrid_Titan_V1',
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
| 165 |
'l2_sniper_confidence': float(l2_result.get('confidence_prob', 0.0)),
|
| 166 |
-
'decision_data': {
|
| 167 |
'components': signal_data.get('components', {}),
|
| 168 |
'sniper_analysis': l2_result,
|
| 169 |
'oracle_tp': tp_price,
|
|
@@ -171,18 +142,15 @@ class TradeManager:
|
|
| 171 |
}
|
| 172 |
}
|
| 173 |
|
| 174 |
-
# الحفظ والتحديث
|
| 175 |
self.open_positions[symbol] = new_trade
|
| 176 |
if self.watchlist: self.watchlist.clear()
|
| 177 |
|
| 178 |
-
# R2 Update
|
| 179 |
portfolio = await self.r2.get_portfolio_state_async()
|
| 180 |
if portfolio.get('first_trade_timestamp') is None:
|
| 181 |
portfolio['first_trade_timestamp'] = new_trade['entry_time']
|
| 182 |
await self.r2.save_portfolio_state_async(portfolio)
|
| 183 |
await self.r2.save_open_trades_async(list(self.open_positions.values()))
|
| 184 |
|
| 185 |
-
# تشغيل الحارس
|
| 186 |
if symbol in self.sentry_tasks: self.sentry_tasks[symbol].cancel()
|
| 187 |
self.sentry_tasks[symbol] = asyncio.create_task(self._guardian_loop(symbol))
|
| 188 |
|
|
@@ -193,7 +161,7 @@ class TradeManager:
|
|
| 193 |
traceback.print_exc()
|
| 194 |
|
| 195 |
# ==============================================================================
|
| 196 |
-
# 🛡️ Hybrid Sentry
|
| 197 |
# ==============================================================================
|
| 198 |
async def _guardian_loop(self, symbol: str):
|
| 199 |
print(f"🛡️ [Sentry] Guarding {symbol}...")
|
|
@@ -201,15 +169,13 @@ class TradeManager:
|
|
| 201 |
|
| 202 |
while self.running and symbol in self.open_positions:
|
| 203 |
try:
|
| 204 |
-
await asyncio.sleep(2)
|
| 205 |
-
|
| 206 |
trade = self.open_positions.get(symbol)
|
| 207 |
if not trade: break
|
| 208 |
|
| 209 |
current_price = await self.data_manager.get_latest_price_async(symbol)
|
| 210 |
if current_price == 0.0: continue
|
| 211 |
|
| 212 |
-
# 1. الفحص الصارم للأهداف (Hard Limits) - الأولوية القصوى
|
| 213 |
if current_price >= trade['tp_price']:
|
| 214 |
async with self.execution_lock:
|
| 215 |
await self._execute_exit(symbol, current_price, "TP_HIT_HARD")
|
|
@@ -219,19 +185,14 @@ class TradeManager:
|
|
| 219 |
await self._execute_exit(symbol, current_price, "SL_HIT_HARD")
|
| 220 |
break
|
| 221 |
|
| 222 |
-
# 2. فحص الذكاء الاصطناعي (كل 60 ثانية)
|
| 223 |
if time.time() - last_ai_check_time > 60:
|
| 224 |
-
# جلب بيانات متعددة الأطر للحارس
|
| 225 |
t1 = self.data_manager.get_latest_ohlcv(symbol, '1m', 300)
|
| 226 |
t5 = self.data_manager.get_latest_ohlcv(symbol, '5m', 200)
|
| 227 |
t15 = self.data_manager.get_latest_ohlcv(symbol, '15m', 100)
|
| 228 |
-
|
| 229 |
d1, d5, d15 = await asyncio.gather(t1, t5, t15)
|
| 230 |
|
| 231 |
if d1 and d5 and d15 and len(d1) >= 200:
|
| 232 |
-
# استشارة المعالج (الذي يستشير الحارس)
|
| 233 |
decision = self.processor.consult_guardian(d1, d5, d15, trade['entry_price'])
|
| 234 |
-
|
| 235 |
action = decision.get('action', 'HOLD')
|
| 236 |
scores = decision.get('scores', {})
|
| 237 |
|
|
@@ -240,21 +201,17 @@ class TradeManager:
|
|
| 240 |
async with self.execution_lock:
|
| 241 |
await self._execute_exit(symbol, current_price, f"AI_{action}", ai_scores=scores)
|
| 242 |
break
|
| 243 |
-
|
| 244 |
last_ai_check_time = time.time()
|
| 245 |
self.open_positions[symbol]['last_update'] = datetime.now().isoformat()
|
| 246 |
-
|
| 247 |
-
except asyncio.CancelledError:
|
| 248 |
-
break
|
| 249 |
except Exception as e:
|
| 250 |
print(f"❌ [Sentry Error] {symbol}: {e}")
|
| 251 |
await asyncio.sleep(5)
|
| 252 |
|
| 253 |
# ==============================================================================
|
| 254 |
-
# 👻 Ghost Monitor & Learning
|
| 255 |
# ==============================================================================
|
| 256 |
def _launch_post_exit_analysis(self, symbol, exit_price, exit_time, position_size_usd, ai_scores=None, trade_obj=None):
|
| 257 |
-
# تشغيل مهمة الخلفية للتعلم
|
| 258 |
asyncio.create_task(self._analyze_after_exit_task(symbol, exit_price, exit_time, position_size_usd, ai_scores, trade_obj))
|
| 259 |
|
| 260 |
def _update_specific_stat(self, key, is_good, usd_impact):
|
|
@@ -267,52 +224,35 @@ class TradeManager:
|
|
| 267 |
self.ai_stats[key]["missed"] += abs(usd_impact)
|
| 268 |
|
| 269 |
async def _analyze_after_exit_task(self, symbol, exit_price, exit_time, position_size_usd, ai_scores, trade_obj):
|
| 270 |
-
|
| 271 |
-
تحليل ما بعد الخروج:
|
| 272 |
-
1. يراقب السعر بعد 15 دقيقة (Ghost Monitor).
|
| 273 |
-
2. يرسل الصفقة لمركز التعلم (Learning Hub).
|
| 274 |
-
"""
|
| 275 |
-
await asyncio.sleep(900) # انتظار 15 دقيقة
|
| 276 |
try:
|
| 277 |
curr = await self.data_manager.get_latest_price_async(symbol)
|
| 278 |
if curr == 0: return
|
| 279 |
|
| 280 |
-
# هل كان الخروج جيداً؟
|
| 281 |
-
# إذا بعنا والسعر نزل -> جيد (وفرنا خسارة)
|
| 282 |
-
# إذا بعنا والسعر صعد -> سيء (فوتنا ربح)
|
| 283 |
change_pct = (curr - exit_price) / exit_price
|
| 284 |
usd_impact = change_pct * position_size_usd
|
| 285 |
is_good_exit = change_pct < 0
|
| 286 |
|
| 287 |
-
# تحديث إحصائيات الواجهة
|
| 288 |
self._update_specific_stat("hybrid", is_good_exit, usd_impact)
|
| 289 |
if ai_scores:
|
| 290 |
if ai_scores.get('v2', 0) >= 0.60: self._update_specific_stat("v2", is_good_exit, usd_impact)
|
| 291 |
if ai_scores.get('v3', 0) >= 0.75: self._update_specific_stat("v3", is_good_exit, usd_impact)
|
| 292 |
|
| 293 |
-
|
| 294 |
-
record = {
|
| 295 |
-
"symbol": symbol, "exit_price": exit_price, "price_15m": curr,
|
| 296 |
-
"usd_impact": usd_impact, "verdict": "SUCCESS" if is_good_exit else "MISS"
|
| 297 |
-
}
|
| 298 |
await self.r2.append_deep_steward_audit(record)
|
| 299 |
|
| 300 |
-
# 🎓 إرسال البيانات لمركز التعلم (The Self-Evolving Step) 🎓
|
| 301 |
if self.learning_hub and trade_obj:
|
| 302 |
-
# نحدث كائن الصفقة بالنتيجة النهائية
|
| 303 |
trade_obj['pnl_percent'] = trade_obj.get('profit_pct', 0.0)
|
| 304 |
-
# نرسلها للمدير التعليمي ليوزعها (أوزان + تدريب)
|
| 305 |
await self.learning_hub.analyze_trade_and_learn(trade_obj, trade_obj.get('exit_reason', 'UNKNOWN'))
|
| 306 |
|
| 307 |
except Exception as e:
|
| 308 |
print(f"⚠️ [Ghost/Learning Error] {e}")
|
| 309 |
|
| 310 |
# ==============================================================================
|
| 311 |
-
# 🔴 Exit Logic
|
| 312 |
# ==============================================================================
|
| 313 |
async def _execute_exit(self, symbol, price, reason, ai_scores=None):
|
| 314 |
if symbol not in self.open_positions: return
|
| 315 |
-
|
| 316 |
try:
|
| 317 |
trade = self.open_positions.pop(symbol)
|
| 318 |
entry = float(trade['entry_price'])
|
|
@@ -321,7 +261,6 @@ class TradeManager:
|
|
| 321 |
|
| 322 |
trade.update({'status': 'CLOSED', 'exit_price': exit_p, 'exit_reason': reason, 'profit_pct': profit_pct*100})
|
| 323 |
|
| 324 |
-
# المحاسبة
|
| 325 |
portfolio = await self.r2.get_portfolio_state_async()
|
| 326 |
curr_cap = float(portfolio.get('current_capital_usd', 100.0))
|
| 327 |
pnl_usd = curr_cap * profit_pct
|
|
@@ -338,14 +277,12 @@ class TradeManager:
|
|
| 338 |
portfolio['total_loss_usd'] = portfolio.get('total_loss_usd', 0) + abs(pnl_usd)
|
| 339 |
trade['result'] = 'LOSS'
|
| 340 |
|
| 341 |
-
# الحفظ
|
| 342 |
await self.r2.save_portfolio_state_async(portfolio)
|
| 343 |
await self.r2.save_open_trades_async(list(self.open_positions.values()))
|
| 344 |
await self.r2.append_to_closed_trades_history(trade)
|
| 345 |
|
| 346 |
print(f"✅ [EXIT] {symbol} | PnL: {trade['profit_pct']:.2f}% | Cap: ${new_cap:.2f}")
|
| 347 |
|
| 348 |
-
# إطلاق التحليل اللاحق (Learning & Ghost)
|
| 349 |
self._launch_post_exit_analysis(symbol, exit_p, trade.get('exit_time'), curr_cap, ai_scores, trade)
|
| 350 |
|
| 351 |
if symbol in self.sentry_tasks:
|
|
@@ -354,21 +291,18 @@ class TradeManager:
|
|
| 354 |
|
| 355 |
except Exception as e:
|
| 356 |
print(f"❌ [Exit Error] {e}")
|
| 357 |
-
self.open_positions[symbol] = trade
|
| 358 |
|
| 359 |
async def force_exit_by_manager(self, symbol, reason):
|
| 360 |
-
"""الخروج اليدوي القسري"""
|
| 361 |
p = await self.data_manager.get_latest_price_async(symbol)
|
| 362 |
async with self.execution_lock:
|
| 363 |
await self._execute_exit(symbol, p, reason)
|
| 364 |
|
| 365 |
async def start_sentry_loops(self):
|
| 366 |
-
"""إعادة تشغيل المراقبة للصفقات الموجودة عند بدء النظام"""
|
| 367 |
for symbol in list(self.open_positions.keys()):
|
| 368 |
if symbol not in self.sentry_tasks or self.sentry_tasks[symbol].done():
|
| 369 |
self.sentry_tasks[symbol] = asyncio.create_task(self._guardian_loop(symbol))
|
| 370 |
|
| 371 |
async def stop_sentry_loops(self):
|
| 372 |
-
"""إيقاف جميع الحراس عند الإغلاق"""
|
| 373 |
self.running = False
|
| 374 |
for task in self.sentry_tasks.values(): task.cancel()
|
|
|
|
| 1 |
+
# trade_manager.py (V23.9 - GEM-Architect: KeyError Fix)
|
| 2 |
|
| 3 |
import asyncio
|
| 4 |
import uuid
|
|
|
|
| 9 |
|
| 10 |
class TradeManager:
|
| 11 |
def __init__(self, r2_service, data_manager, processor):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
self.r2 = r2_service
|
| 13 |
self.data_manager = data_manager
|
|
|
|
|
|
|
| 14 |
self.processor = processor
|
|
|
|
|
|
|
| 15 |
self.learning_hub = None
|
| 16 |
|
| 17 |
self.open_positions = {}
|
|
|
|
| 19 |
self.sentry_tasks = {}
|
| 20 |
self.running = True
|
| 21 |
|
|
|
|
| 22 |
self.ai_stats = {
|
| 23 |
"hybrid": {"total": 0, "good": 0, "saved": 0.0, "missed": 0.0},
|
| 24 |
"v2": {"total": 0, "good": 0, "saved": 0.0, "missed": 0.0},
|
|
|
|
| 26 |
}
|
| 27 |
|
| 28 |
self.execution_lock = asyncio.Lock()
|
| 29 |
+
print(f"🛡️ [TradeManager V23.9] Initialized (KeyError Fixed).")
|
|
|
|
| 30 |
|
| 31 |
async def initialize_sentry_exchanges(self):
|
| 32 |
print("🛡️ [TradeManager] Syncing state with R2...")
|
|
|
|
| 42 |
self.open_positions = {}
|
| 43 |
|
| 44 |
# ==============================================================================
|
| 45 |
+
# 🎯 L4 Sniper Logic
|
| 46 |
# ==============================================================================
|
| 47 |
async def select_and_execute_best_signal(self, oracle_approved_signals: List[Dict[str, Any]]):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
if len(self.open_positions) > 0:
|
| 49 |
print(f"⛔ [TradeManager] Scan aborted. Max positions reached.")
|
| 50 |
return
|
| 51 |
|
|
|
|
| 52 |
if not self.processor.initialized:
|
| 53 |
await self.processor.initialize()
|
| 54 |
|
|
|
|
| 60 |
if symbol in self.open_positions or symbol in self.watchlist:
|
| 61 |
continue
|
| 62 |
|
| 63 |
+
# جلب البيانات (Parallel Fetch)
|
| 64 |
ohlcv_task = self.data_manager.get_latest_ohlcv(symbol, '1m', 600)
|
| 65 |
ob_task = self.data_manager.get_order_book_snapshot(symbol)
|
|
|
|
| 66 |
ohlcv_1m, order_book = await asyncio.gather(ohlcv_task, ob_task)
|
| 67 |
|
|
|
|
| 68 |
if not ohlcv_1m or len(ohlcv_1m) < 500:
|
| 69 |
+
print(f" -> [L4 Skip] {symbol} (Not enough data).")
|
| 70 |
continue
|
| 71 |
|
| 72 |
+
# استشارة القناص
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
sniper_result = await self.processor.check_sniper_entry(ohlcv_1m, order_book)
|
| 74 |
|
|
|
|
| 75 |
reason_str = sniper_result.get('reason', 'N/A')
|
| 76 |
+
confidence = sniper_result.get('confidence_prob', 0.0)
|
| 77 |
|
| 78 |
if sniper_result['signal'] == 'BUY':
|
| 79 |
print(f" -> 🟢 [L4 PASS] {symbol} | Score: {confidence:.2f} | {reason_str}")
|
|
|
|
| 80 |
signal['l2_sniper_result'] = sniper_result
|
| 81 |
signal['sniper_confidence'] = confidence
|
| 82 |
sniper_candidates.append(signal)
|
| 83 |
else:
|
|
|
|
| 84 |
print(f" -> 🔴 [L4 REJECT] {symbol} | {reason_str}")
|
| 85 |
|
| 86 |
if not sniper_candidates:
|
| 87 |
+
print(" -> [L4 Result] No candidates passed the Sniper check.")
|
| 88 |
return
|
| 89 |
|
| 90 |
+
# ✅ [FIXED HERE] استخدام الاسم الصحيح 'enhanced_final_score' واستخدام .get للحماية
|
| 91 |
+
sniper_candidates.sort(
|
| 92 |
+
key=lambda x: (x.get('sniper_confidence', 0), x.get('enhanced_final_score', 0)),
|
| 93 |
+
reverse=True
|
| 94 |
+
)
|
| 95 |
|
| 96 |
+
best_signal = sniper_candidates[0]
|
| 97 |
+
print(f" 🔥 [L4 WINNER] {best_signal['symbol']} selected.")
|
| 98 |
|
|
|
|
| 99 |
async with self.execution_lock:
|
| 100 |
if len(self.open_positions) == 0 and best_signal['symbol'] not in self.open_positions:
|
| 101 |
await self._execute_entry_from_signal(best_signal['symbol'], best_signal)
|
| 102 |
|
| 103 |
# ==============================================================================
|
| 104 |
+
# 🎯 Entry Execution
|
| 105 |
# ==============================================================================
|
| 106 |
async def _execute_entry_from_signal(self, symbol, signal_data):
|
| 107 |
try:
|
| 108 |
trade_id = str(uuid.uuid4())
|
| 109 |
current_price = float(signal_data.get('current_price', 0.0))
|
|
|
|
|
|
|
| 110 |
if current_price <= 0.0:
|
| 111 |
current_price = await self.data_manager.get_latest_price_async(symbol)
|
| 112 |
|
|
|
|
| 113 |
l2_result = signal_data.get('l2_sniper_result', {})
|
|
|
|
|
|
|
| 114 |
tp_price = float(signal_data.get('tp_price') or 0.0)
|
| 115 |
sl_price = float(signal_data.get('sl_price') or 0.0)
|
| 116 |
|
|
|
|
| 119 |
tp_price = current_price + (atr_mock * 2.0)
|
| 120 |
sl_price = current_price - (atr_mock * 1.0)
|
| 121 |
|
|
|
|
| 122 |
new_trade = {
|
| 123 |
'id': trade_id,
|
| 124 |
'symbol': symbol,
|
|
|
|
| 128 |
'tp_price': tp_price,
|
| 129 |
'sl_price': sl_price,
|
| 130 |
'last_update': datetime.now().isoformat(),
|
|
|
|
|
|
|
| 131 |
'strategy': 'Hybrid_Titan_V1',
|
| 132 |
+
|
| 133 |
+
# ✅ [FIXED HERE] استخدام الاسم الصحيح للحفظ في السجل
|
| 134 |
+
'l1_score': float(signal_data.get('enhanced_final_score', 0.0)),
|
| 135 |
+
|
| 136 |
'l2_sniper_confidence': float(l2_result.get('confidence_prob', 0.0)),
|
| 137 |
+
'decision_data': {
|
| 138 |
'components': signal_data.get('components', {}),
|
| 139 |
'sniper_analysis': l2_result,
|
| 140 |
'oracle_tp': tp_price,
|
|
|
|
| 142 |
}
|
| 143 |
}
|
| 144 |
|
|
|
|
| 145 |
self.open_positions[symbol] = new_trade
|
| 146 |
if self.watchlist: self.watchlist.clear()
|
| 147 |
|
|
|
|
| 148 |
portfolio = await self.r2.get_portfolio_state_async()
|
| 149 |
if portfolio.get('first_trade_timestamp') is None:
|
| 150 |
portfolio['first_trade_timestamp'] = new_trade['entry_time']
|
| 151 |
await self.r2.save_portfolio_state_async(portfolio)
|
| 152 |
await self.r2.save_open_trades_async(list(self.open_positions.values()))
|
| 153 |
|
|
|
|
| 154 |
if symbol in self.sentry_tasks: self.sentry_tasks[symbol].cancel()
|
| 155 |
self.sentry_tasks[symbol] = asyncio.create_task(self._guardian_loop(symbol))
|
| 156 |
|
|
|
|
| 161 |
traceback.print_exc()
|
| 162 |
|
| 163 |
# ==============================================================================
|
| 164 |
+
# 🛡️ Hybrid Sentry
|
| 165 |
# ==============================================================================
|
| 166 |
async def _guardian_loop(self, symbol: str):
|
| 167 |
print(f"🛡️ [Sentry] Guarding {symbol}...")
|
|
|
|
| 169 |
|
| 170 |
while self.running and symbol in self.open_positions:
|
| 171 |
try:
|
| 172 |
+
await asyncio.sleep(2)
|
|
|
|
| 173 |
trade = self.open_positions.get(symbol)
|
| 174 |
if not trade: break
|
| 175 |
|
| 176 |
current_price = await self.data_manager.get_latest_price_async(symbol)
|
| 177 |
if current_price == 0.0: continue
|
| 178 |
|
|
|
|
| 179 |
if current_price >= trade['tp_price']:
|
| 180 |
async with self.execution_lock:
|
| 181 |
await self._execute_exit(symbol, current_price, "TP_HIT_HARD")
|
|
|
|
| 185 |
await self._execute_exit(symbol, current_price, "SL_HIT_HARD")
|
| 186 |
break
|
| 187 |
|
|
|
|
| 188 |
if time.time() - last_ai_check_time > 60:
|
|
|
|
| 189 |
t1 = self.data_manager.get_latest_ohlcv(symbol, '1m', 300)
|
| 190 |
t5 = self.data_manager.get_latest_ohlcv(symbol, '5m', 200)
|
| 191 |
t15 = self.data_manager.get_latest_ohlcv(symbol, '15m', 100)
|
|
|
|
| 192 |
d1, d5, d15 = await asyncio.gather(t1, t5, t15)
|
| 193 |
|
| 194 |
if d1 and d5 and d15 and len(d1) >= 200:
|
|
|
|
| 195 |
decision = self.processor.consult_guardian(d1, d5, d15, trade['entry_price'])
|
|
|
|
| 196 |
action = decision.get('action', 'HOLD')
|
| 197 |
scores = decision.get('scores', {})
|
| 198 |
|
|
|
|
| 201 |
async with self.execution_lock:
|
| 202 |
await self._execute_exit(symbol, current_price, f"AI_{action}", ai_scores=scores)
|
| 203 |
break
|
|
|
|
| 204 |
last_ai_check_time = time.time()
|
| 205 |
self.open_positions[symbol]['last_update'] = datetime.now().isoformat()
|
| 206 |
+
except asyncio.CancelledError: break
|
|
|
|
|
|
|
| 207 |
except Exception as e:
|
| 208 |
print(f"❌ [Sentry Error] {symbol}: {e}")
|
| 209 |
await asyncio.sleep(5)
|
| 210 |
|
| 211 |
# ==============================================================================
|
| 212 |
+
# 👻 Ghost Monitor & Learning
|
| 213 |
# ==============================================================================
|
| 214 |
def _launch_post_exit_analysis(self, symbol, exit_price, exit_time, position_size_usd, ai_scores=None, trade_obj=None):
|
|
|
|
| 215 |
asyncio.create_task(self._analyze_after_exit_task(symbol, exit_price, exit_time, position_size_usd, ai_scores, trade_obj))
|
| 216 |
|
| 217 |
def _update_specific_stat(self, key, is_good, usd_impact):
|
|
|
|
| 224 |
self.ai_stats[key]["missed"] += abs(usd_impact)
|
| 225 |
|
| 226 |
async def _analyze_after_exit_task(self, symbol, exit_price, exit_time, position_size_usd, ai_scores, trade_obj):
|
| 227 |
+
await asyncio.sleep(900)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
try:
|
| 229 |
curr = await self.data_manager.get_latest_price_async(symbol)
|
| 230 |
if curr == 0: return
|
| 231 |
|
|
|
|
|
|
|
|
|
|
| 232 |
change_pct = (curr - exit_price) / exit_price
|
| 233 |
usd_impact = change_pct * position_size_usd
|
| 234 |
is_good_exit = change_pct < 0
|
| 235 |
|
|
|
|
| 236 |
self._update_specific_stat("hybrid", is_good_exit, usd_impact)
|
| 237 |
if ai_scores:
|
| 238 |
if ai_scores.get('v2', 0) >= 0.60: self._update_specific_stat("v2", is_good_exit, usd_impact)
|
| 239 |
if ai_scores.get('v3', 0) >= 0.75: self._update_specific_stat("v3", is_good_exit, usd_impact)
|
| 240 |
|
| 241 |
+
record = {"symbol": symbol, "exit_price": exit_price, "price_15m": curr, "usd_impact": usd_impact, "verdict": "SUCCESS" if is_good_exit else "MISS"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
await self.r2.append_deep_steward_audit(record)
|
| 243 |
|
|
|
|
| 244 |
if self.learning_hub and trade_obj:
|
|
|
|
| 245 |
trade_obj['pnl_percent'] = trade_obj.get('profit_pct', 0.0)
|
|
|
|
| 246 |
await self.learning_hub.analyze_trade_and_learn(trade_obj, trade_obj.get('exit_reason', 'UNKNOWN'))
|
| 247 |
|
| 248 |
except Exception as e:
|
| 249 |
print(f"⚠️ [Ghost/Learning Error] {e}")
|
| 250 |
|
| 251 |
# ==============================================================================
|
| 252 |
+
# 🔴 Exit Logic
|
| 253 |
# ==============================================================================
|
| 254 |
async def _execute_exit(self, symbol, price, reason, ai_scores=None):
|
| 255 |
if symbol not in self.open_positions: return
|
|
|
|
| 256 |
try:
|
| 257 |
trade = self.open_positions.pop(symbol)
|
| 258 |
entry = float(trade['entry_price'])
|
|
|
|
| 261 |
|
| 262 |
trade.update({'status': 'CLOSED', 'exit_price': exit_p, 'exit_reason': reason, 'profit_pct': profit_pct*100})
|
| 263 |
|
|
|
|
| 264 |
portfolio = await self.r2.get_portfolio_state_async()
|
| 265 |
curr_cap = float(portfolio.get('current_capital_usd', 100.0))
|
| 266 |
pnl_usd = curr_cap * profit_pct
|
|
|
|
| 277 |
portfolio['total_loss_usd'] = portfolio.get('total_loss_usd', 0) + abs(pnl_usd)
|
| 278 |
trade['result'] = 'LOSS'
|
| 279 |
|
|
|
|
| 280 |
await self.r2.save_portfolio_state_async(portfolio)
|
| 281 |
await self.r2.save_open_trades_async(list(self.open_positions.values()))
|
| 282 |
await self.r2.append_to_closed_trades_history(trade)
|
| 283 |
|
| 284 |
print(f"✅ [EXIT] {symbol} | PnL: {trade['profit_pct']:.2f}% | Cap: ${new_cap:.2f}")
|
| 285 |
|
|
|
|
| 286 |
self._launch_post_exit_analysis(symbol, exit_p, trade.get('exit_time'), curr_cap, ai_scores, trade)
|
| 287 |
|
| 288 |
if symbol in self.sentry_tasks:
|
|
|
|
| 291 |
|
| 292 |
except Exception as e:
|
| 293 |
print(f"❌ [Exit Error] {e}")
|
| 294 |
+
self.open_positions[symbol] = trade
|
| 295 |
|
| 296 |
async def force_exit_by_manager(self, symbol, reason):
|
|
|
|
| 297 |
p = await self.data_manager.get_latest_price_async(symbol)
|
| 298 |
async with self.execution_lock:
|
| 299 |
await self._execute_exit(symbol, p, reason)
|
| 300 |
|
| 301 |
async def start_sentry_loops(self):
|
|
|
|
| 302 |
for symbol in list(self.open_positions.keys()):
|
| 303 |
if symbol not in self.sentry_tasks or self.sentry_tasks[symbol].done():
|
| 304 |
self.sentry_tasks[symbol] = asyncio.create_task(self._guardian_loop(symbol))
|
| 305 |
|
| 306 |
async def stop_sentry_loops(self):
|
|
|
|
| 307 |
self.running = False
|
| 308 |
for task in self.sentry_tasks.values(): task.cancel()
|