Riy777 commited on
Commit
2dbc10d
·
verified ·
1 Parent(s): c1f9548

Update trade_manager.py

Browse files
Files changed (1) hide show
  1. trade_manager.py +37 -22
trade_manager.py CHANGED
@@ -1,4 +1,4 @@
1
- # trade_manager.py (V23.0 - GEM-Architect: Processor Integration)
2
 
3
  import asyncio
4
  import uuid
@@ -10,7 +10,7 @@ from typing import List, Dict, Any
10
  class TradeManager:
11
  def __init__(self, r2_service, data_manager, processor):
12
  """
13
- مدير الصفقات: يعتمد كلياً على 'processor' في القرارات الذكية.
14
  """
15
  self.r2 = r2_service
16
  self.data_manager = data_manager
@@ -32,7 +32,7 @@ class TradeManager:
32
 
33
  self.execution_lock = asyncio.Lock()
34
 
35
- print(f"🛡️ [TradeManager V23] Initialized with Central Processor.")
36
 
37
  async def initialize_sentry_exchanges(self):
38
  print("🛡️ [TradeManager] Syncing state with R2...")
@@ -48,14 +48,13 @@ class TradeManager:
48
  self.open_positions = {}
49
 
50
  # ==============================================================================
51
- # 🎯 L4 Sniper Logic (Via Processor)
52
  # ==============================================================================
53
  async def select_and_execute_best_signal(self, oracle_approved_signals: List[Dict[str, Any]]):
54
  if len(self.open_positions) > 0:
55
  print(f"⛔ [TradeManager] Scan aborted. Max positions reached.")
56
  return
57
 
58
- # نطلب من المعالج التأكد من أن القناص جاهز
59
  if not self.processor.initialized:
60
  await self.processor.initialize()
61
 
@@ -67,32 +66,48 @@ class TradeManager:
67
  if symbol in self.open_positions or symbol in self.watchlist:
68
  continue
69
 
70
- # جلب البيانات
71
- ohlcv_1m = await self.data_manager.get_latest_ohlcv(symbol, '1m', 600)
 
72
 
73
- # استشارة القناص عبر المعالج
74
- sniper_result = await self.processor.check_sniper_entry(ohlcv_1m)
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  if sniper_result['signal'] == 'BUY':
77
  confidence = sniper_result['confidence_prob']
78
- threshold = sniper_result.get('threshold', 0.60)
79
- print(f" -> [L4 PASS] {symbol} (Conf: {confidence:.2f}). Added to batch.")
 
 
 
80
 
81
  signal['l2_sniper_result'] = sniper_result
82
  signal['sniper_confidence'] = confidence
83
  sniper_candidates.append(signal)
84
  else:
85
- print(f" -> [L4 REJECT] {symbol} (Conf: {sniper_result.get('confidence_prob',0):.2f})")
86
 
87
  if not sniper_candidates:
88
- print(" -> [L4 Result] No candidates passed the Sniper check.")
89
  return
90
 
91
- # ترتيب النتائج
92
  sniper_candidates.sort(key=lambda x: (x['sniper_confidence'], x['final_total_score']), reverse=True)
93
  best_signal = sniper_candidates[0]
94
 
95
- print(f" 🔥 [L4 WINNER] {best_signal['symbol']} (Sniper: {best_signal['sniper_confidence']:.2f})")
96
 
97
  # التنفيذ
98
  async with self.execution_lock:
@@ -111,12 +126,12 @@ class TradeManager:
111
 
112
  l2_result = signal_data.get('l2_sniper_result', {})
113
 
114
- # الأهدا�� (من Oracle أو حساب تلقائي)
115
  tp_price = float(signal_data.get('tp_price') or 0.0)
116
  sl_price = float(signal_data.get('sl_price') or 0.0)
117
 
 
118
  if tp_price <= 0 or sl_price <= 0:
119
- # Fallback simple calculation
120
  atr_mock = current_price * 0.02
121
  tp_price = current_price + (atr_mock * 2.0)
122
  sl_price = current_price - (atr_mock * 1.0)
@@ -166,7 +181,7 @@ class TradeManager:
166
 
167
  while self.running and symbol in self.open_positions:
168
  try:
169
- await asyncio.sleep(2) # Fast tick
170
 
171
  trade = self.open_positions.get(symbol)
172
  if not trade: break
@@ -174,7 +189,7 @@ class TradeManager:
174
  current_price = await self.data_manager.get_latest_price_async(symbol)
175
  if current_price == 0.0: continue
176
 
177
- # 1. Hard Limits
178
  if current_price >= trade['tp_price']:
179
  async with self.execution_lock:
180
  await self._execute_exit(symbol, current_price, "TP_HIT_HARD")
@@ -184,7 +199,7 @@ class TradeManager:
184
  await self._execute_exit(symbol, current_price, "SL_HIT_HARD")
185
  break
186
 
187
- # 2. AI Check (Processor Consultation) every 60s
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)
@@ -193,7 +208,7 @@ class TradeManager:
193
  d1, d5, d15 = await asyncio.gather(t1, t5, t15)
194
 
195
  if d1 and d5 and d15 and len(d1) >= 200:
196
- # ⚡ استشارة المعالج هنا
197
  decision = self.processor.consult_guardian(d1, d5, d15, trade['entry_price'])
198
 
199
  action = decision.get('action', 'HOLD')
@@ -299,7 +314,7 @@ class TradeManager:
299
 
300
  except Exception as e:
301
  print(f"❌ [Exit Error] {e}")
302
- self.open_positions[symbol] = trade # استعادة في حال الخطأ
303
 
304
  async def force_exit_by_manager(self, symbol, reason):
305
  p = await self.data_manager.get_latest_price_async(symbol)
 
1
+ # trade_manager.py (V23.2 - GEM-Architect: Sniper with Order Book)
2
 
3
  import asyncio
4
  import uuid
 
10
  class TradeManager:
11
  def __init__(self, r2_service, data_manager, processor):
12
  """
13
+ مدير الصفقات: ينفذ الأوامر بناءً على إشارات المعالج المركزي.
14
  """
15
  self.r2 = r2_service
16
  self.data_manager = data_manager
 
32
 
33
  self.execution_lock = asyncio.Lock()
34
 
35
+ print(f"🛡️ [TradeManager V23.2] Initialized (L4 OB Enabled).")
36
 
37
  async def initialize_sentry_exchanges(self):
38
  print("🛡️ [TradeManager] Syncing state with R2...")
 
48
  self.open_positions = {}
49
 
50
  # ==============================================================================
51
+ # 🎯 L4 Sniper Logic (Fusion: ML + Order Book)
52
  # ==============================================================================
53
  async def select_and_execute_best_signal(self, oracle_approved_signals: List[Dict[str, Any]]):
54
  if len(self.open_positions) > 0:
55
  print(f"⛔ [TradeManager] Scan aborted. Max positions reached.")
56
  return
57
 
 
58
  if not self.processor.initialized:
59
  await self.processor.initialize()
60
 
 
66
  if symbol in self.open_positions or symbol in self.watchlist:
67
  continue
68
 
69
+ # ⚡ [Parallel Fetch] جلب الشموع + دفتر الطلبات معاً ⚡
70
+ ohlcv_task = self.data_manager.get_latest_ohlcv(symbol, '1m', 600)
71
+ ob_task = self.data_manager.get_order_book_snapshot(symbol)
72
 
73
+ # تنفيذ الطلبين في وقت واحد للسرعة
74
+ ohlcv_1m, order_book = await asyncio.gather(ohlcv_task, ob_task)
75
+
76
+ # التحقق من البيانات
77
+ if not ohlcv_1m or len(ohlcv_1m) < 500:
78
+ print(f" -> [L4 Skip] {symbol} (Not enough candle data).")
79
+ continue
80
+
81
+ if not order_book or 'bids' not in order_book or not order_book['bids']:
82
+ print(f" -> [L4 Skip] {symbol} (Empty Order Book).")
83
+ continue
84
+
85
+ # ⚡ استشارة القناص بالبيانات المدمجة ⚡
86
+ sniper_result = await self.processor.check_sniper_entry(ohlcv_1m, order_book)
87
 
88
  if sniper_result['signal'] == 'BUY':
89
  confidence = sniper_result['confidence_prob']
90
+ # تحليل دفتر الطلبات المرفق
91
+ ob_info = sniper_result.get('ob_data', {})
92
+ ob_reason = ob_info.get('reason', 'N/A')
93
+
94
+ print(f" -> [L4 PASS] {symbol} (Conf: {confidence:.2f} | OB: {ob_reason})")
95
 
96
  signal['l2_sniper_result'] = sniper_result
97
  signal['sniper_confidence'] = confidence
98
  sniper_candidates.append(signal)
99
  else:
100
+ print(f" -> [L4 REJECT] {symbol} ({sniper_result.get('reason')})")
101
 
102
  if not sniper_candidates:
103
+ print(" -> [L4 Result] No candidates passed the Sniper & OrderBook check.")
104
  return
105
 
106
+ # ترتيب النتائج حسب الثقة
107
  sniper_candidates.sort(key=lambda x: (x['sniper_confidence'], x['final_total_score']), reverse=True)
108
  best_signal = sniper_candidates[0]
109
 
110
+ print(f" 🔥 [L4 WINNER] {best_signal['symbol']} selected for execution.")
111
 
112
  # التنفيذ
113
  async with self.execution_lock:
 
126
 
127
  l2_result = signal_data.get('l2_sniper_result', {})
128
 
129
+ # الأهداف (من Oracle)
130
  tp_price = float(signal_data.get('tp_price') or 0.0)
131
  sl_price = float(signal_data.get('sl_price') or 0.0)
132
 
133
+ # حماية ضد القيم الصفرية
134
  if tp_price <= 0 or sl_price <= 0:
 
135
  atr_mock = current_price * 0.02
136
  tp_price = current_price + (atr_mock * 2.0)
137
  sl_price = current_price - (atr_mock * 1.0)
 
181
 
182
  while self.running and symbol in self.open_positions:
183
  try:
184
+ await asyncio.sleep(2) # فحص سريع للأسعار
185
 
186
  trade = self.open_positions.get(symbol)
187
  if not trade: break
 
189
  current_price = await self.data_manager.get_latest_price_async(symbol)
190
  if current_price == 0.0: continue
191
 
192
+ # 1. Hard Limits Check
193
  if current_price >= trade['tp_price']:
194
  async with self.execution_lock:
195
  await self._execute_exit(symbol, current_price, "TP_HIT_HARD")
 
199
  await self._execute_exit(symbol, current_price, "SL_HIT_HARD")
200
  break
201
 
202
+ # 2. AI Check (Every 60s)
203
  if time.time() - last_ai_check_time > 60:
204
  t1 = self.data_manager.get_latest_ohlcv(symbol, '1m', 300)
205
  t5 = self.data_manager.get_latest_ohlcv(symbol, '5m', 200)
 
208
  d1, d5, d15 = await asyncio.gather(t1, t5, t15)
209
 
210
  if d1 and d5 and d15 and len(d1) >= 200:
211
+ # ⚡ استشارة المعالج ⚡
212
  decision = self.processor.consult_guardian(d1, d5, d15, trade['entry_price'])
213
 
214
  action = decision.get('action', 'HOLD')
 
314
 
315
  except Exception as e:
316
  print(f"❌ [Exit Error] {e}")
317
+ self.open_positions[symbol] = trade # استعادة الصفقة في الذاكرة عند الخطأ
318
 
319
  async def force_exit_by_manager(self, symbol, reason):
320
  p = await self.data_manager.get_latest_price_async(symbol)