Spaces:
Running
Running
File size: 22,239 Bytes
490e45e 6f41fff f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad 490e45e f3ca3ad |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
import asyncio
import json
import time
import traceback
from datetime import datetime, timedelta
from helpers import safe_float_conversion, _apply_patience_logic
class TradeManager:
def __init__(self, r2_service, learning_engine=None, data_manager=None):
self.r2_service = r2_service
self.learning_engine = learning_engine
self.data_manager = data_manager
self.monitoring_tasks = {}
self.is_running = False
self.monitoring_errors = {}
self.max_consecutive_errors = 5
async def open_trade(self, symbol, decision, current_price):
try:
portfolio_state = await self.r2_service.get_portfolio_state_async()
available_capital = portfolio_state.get("current_capital_usd", 0)
if available_capital < 1:
print(f"❌ رأس المال غير كافي لفتح صفقة لـ {symbol}: {available_capital}")
return None
expected_target_minutes = decision.get('expected_target_minutes', 15)
expected_target_minutes = max(5, min(expected_target_minutes, 45))
expected_target_time = (datetime.now() + timedelta(minutes=expected_target_minutes)).isoformat()
strategy = decision.get('strategy')
if not strategy or strategy == 'unknown':
strategy = 'GENERIC'
trades = await self.r2_service.get_open_trades_async()
new_trade = {
"id": str(int(datetime.now().timestamp())),
"symbol": symbol,
"entry_price": current_price,
"entry_timestamp": datetime.now().isoformat(),
"decision_data": decision,
"status": "OPEN",
"stop_loss": decision.get("stop_loss"),
"take_profit": decision.get("take_profit"),
"trade_type": decision.get("trade_type"),
"position_size_usd": available_capital,
"expected_target_minutes": expected_target_minutes,
"expected_target_time": expected_target_time,
"is_monitored": True,
"strategy": strategy,
"monitoring_started": False
}
trades.append(new_trade)
await self.r2_service.save_open_trades_async(trades)
portfolio_state["invested_capital_usd"] = available_capital
portfolio_state["current_capital_usd"] = 0.0
portfolio_state["total_trades"] = portfolio_state.get("total_trades", 0) + 1
await self.r2_service.save_portfolio_state_async(portfolio_state)
await self.r2_service.save_system_logs_async({
"new_trade_opened": True,
"symbol": symbol,
"position_size": available_capital,
"expected_minutes": expected_target_minutes,
"trade_type": decision.get("trade_type", "LONG"),
"strategy": strategy
})
print(f"✅ تم فتح صفقة جديدة لـ {symbol} باستراتيجية {strategy}")
return new_trade
except Exception as e:
print(f"❌ فشل فتح صفقة لـ {symbol}: {e}")
await self.r2_service.save_system_logs_async({
"trade_open_failed": True,
"symbol": symbol,
"error": str(e)
})
raise
async def close_trade(self, trade_to_close, close_price, reason="إغلاق بالنظام"):
try:
symbol = trade_to_close.get('symbol')
trade_to_close['status'] = 'CLOSED'
trade_to_close['close_price'] = close_price
trade_to_close['close_timestamp'] = datetime.now().isoformat()
trade_to_close['is_monitored'] = False
entry_price = trade_to_close['entry_price']
position_size = trade_to_close['position_size_usd']
trade_type = trade_to_close.get('trade_type', 'LONG')
strategy = trade_to_close.get('strategy', 'unknown')
pnl = 0.0
pnl_percent = 0.0
if entry_price and entry_price > 0 and close_price and close_price > 0:
try:
if trade_type == 'LONG':
pnl_percent = ((close_price - entry_price) / entry_price) * 100
pnl = position_size * (pnl_percent / 100)
elif trade_type == 'SHORT':
pnl_percent = ((entry_price - close_price) / entry_price) * 100
pnl = position_size * (pnl_percent / 100)
except (TypeError, ZeroDivisionError) as calc_error:
pnl = 0.0
pnl_percent = 0.0
trade_to_close['pnl_usd'] = pnl
trade_to_close['pnl_percent'] = pnl_percent
await self._archive_closed_trade(trade_to_close)
await self._update_trade_summary(trade_to_close)
portfolio_state = await self.r2_service.get_portfolio_state_async()
current_capital = portfolio_state.get("current_capital_usd", 0)
invested_capital = portfolio_state.get("invested_capital_usd", 0)
new_capital = current_capital + position_size + pnl
portfolio_state["current_capital_usd"] = new_capital
portfolio_state["invested_capital_usd"] = 0.0
if pnl > 0:
portfolio_state["winning_trades"] = portfolio_state.get("winning_trades", 0) + 1
portfolio_state["total_profit_usd"] = portfolio_state.get("total_profit_usd", 0.0) + pnl
elif pnl < 0:
portfolio_state["total_loss_usd"] = portfolio_state.get("total_loss_usd", 0.0) + abs(pnl)
await self.r2_service.save_portfolio_state_async(portfolio_state)
open_trades = await self.r2_service.get_open_trades_async()
trades_to_keep = [t for t in open_trades if t.get('id') != trade_to_close.get('id')]
await self.r2_service.save_open_trades_async(trades_to_keep)
# إزالة من المهام النشطة
if symbol in self.monitoring_tasks:
del self.monitoring_tasks[symbol]
if symbol in self.monitoring_errors:
del self.monitoring_errors[symbol]
await self.r2_service.save_system_logs_async({
"trade_closed": True,
"symbol": symbol,
"entry_price": entry_price,
"close_price": close_price,
"pnl_usd": pnl,
"pnl_percent": pnl_percent,
"new_capital": new_capital,
"strategy": strategy,
"position_size": position_size,
"trade_type": trade_type,
"reason": reason
})
if self.learning_engine and self.learning_engine.initialized:
await self.learning_engine.analyze_trade_outcome(trade_to_close, reason)
print(f"✅ تم إغلاق صفقة {symbol} - السبب: {reason} - الربح: {pnl_percent:+.2f}%")
return True
except Exception as e:
print(f"❌ فشل إغلاق صفقة {trade_to_close.get('symbol')}: {e}")
await self.r2_service.save_system_logs_async({
"trade_close_failed": True,
"symbol": trade_to_close.get('symbol'),
"error": str(e)
})
raise
async def update_trade(self, trade_to_update, re_analysis_decision):
try:
symbol = trade_to_update.get('symbol')
if re_analysis_decision.get('new_stop_loss'):
trade_to_update['stop_loss'] = re_analysis_decision['new_stop_loss']
if re_analysis_decision.get('new_take_profit'):
trade_to_update['take_profit'] = re_analysis_decision['new_take_profit']
new_expected_minutes = re_analysis_decision.get('new_expected_minutes')
if new_expected_minutes:
new_expected_minutes = max(5, min(new_expected_minutes, 45))
trade_to_update['expected_target_minutes'] = new_expected_minutes
trade_to_update['expected_target_time'] = (datetime.now() + timedelta(minutes=new_expected_minutes)).isoformat()
original_strategy = trade_to_update.get('strategy')
if not original_strategy or original_strategy == 'unknown':
original_strategy = re_analysis_decision.get('strategy', 'GENERIC')
trade_to_update['strategy'] = original_strategy
trade_to_update['decision_data'] = re_analysis_decision
trade_to_update['is_monitored'] = True
open_trades = await self.r2_service.get_open_trades_async()
for i, trade in enumerate(open_trades):
if trade.get('id') == trade_to_update.get('id'):
open_trades[i] = trade_to_update
break
await self.r2_service.save_open_trades_async(open_trades)
await self.r2_service.save_system_logs_async({
"trade_updated": True,
"symbol": symbol,
"new_expected_minutes": new_expected_minutes,
"action": "UPDATE_TRADE",
"strategy": original_strategy
})
print(f"✅ تم تحديث صفقة {symbol}")
return True
except Exception as e:
print(f"❌ فشل تحديث صفقة {trade_to_update.get('symbol')}: {e}")
raise
async def immediate_close_trade(self, symbol, close_price, reason="المراقبة الفورية"):
try:
open_trades = await self.r2_service.get_open_trades_async()
trade_to_close = None
for trade in open_trades:
if trade['symbol'] == symbol and trade['status'] == 'OPEN':
trade_to_close = trade
break
if not trade_to_close:
print(f"⚠️ لم يتم العثور على صفقة مفتوحة لـ {symbol}")
return False
await self.close_trade(trade_to_close, close_price, reason)
return True
except Exception as e:
print(f"❌ فشل الإغلاق الفوري لـ {symbol}: {e}")
return False
async def start_trade_monitoring(self):
self.is_running = True
print("🔍 بدء مراقبة الصفقات...")
while self.is_running:
try:
open_trades = await self.r2_service.get_open_trades_async()
current_time = time.time()
for trade in open_trades:
symbol = trade['symbol']
# تخطي الصفقات التي تجاوزت حد الأخطاء
if self.monitoring_errors.get(symbol, 0) >= self.max_consecutive_errors:
if symbol in self.monitoring_tasks:
del self.monitoring_tasks[symbol]
continue
# بدء المراقبة إذا لم تكن نشطة
if symbol not in self.monitoring_tasks:
task = asyncio.create_task(self._monitor_single_trade(trade))
self.monitoring_tasks[symbol] = {
'task': task,
'start_time': current_time,
'trade': trade
}
trade['monitoring_started'] = True
# تنظيف المهام المنتهية
current_symbols = {trade['symbol'] for trade in open_trades}
for symbol in list(self.monitoring_tasks.keys()):
if symbol not in current_symbols:
task_info = self.monitoring_tasks[symbol]
if not task_info['task'].done():
task_info['task'].cancel()
del self.monitoring_tasks[symbol]
if symbol in self.monitoring_errors:
del self.monitoring_errors[symbol]
await asyncio.sleep(10)
except Exception as error:
print(f"❌ خطأ في مراقبة الصفقات: {error}")
await asyncio.sleep(30)
async def _monitor_single_trade(self, trade):
symbol = trade['symbol']
max_monitoring_time = 3600 # أقصى وقت مراقبة: ساعة واحدة
print(f"🔍 بدء مراقبة الصفقة: {symbol}")
while (symbol in self.monitoring_tasks and
self.is_running and
self.monitoring_errors.get(symbol, 0) < self.max_consecutive_errors):
try:
start_time = time.time()
if not self.data_manager:
print(f"⚠️ DataManager غير متوفر لـ {symbol}")
await asyncio.sleep(15)
continue
# الحصول على السعر الحالي مع مهلة زمنية
try:
current_price = await asyncio.wait_for(
self.data_manager.get_latest_price_async(symbol),
timeout=10
)
except asyncio.TimeoutError:
print(f"⏰ مهلة انتظار السعر لـ {symbol}")
self._increment_monitoring_error(symbol)
await asyncio.sleep(15)
continue
if not current_price:
print(f"⚠️ لم يتم الحصول على سعر لـ {symbol}")
self._increment_monitoring_error(symbol)
await asyncio.sleep(15)
continue
entry_price = trade['entry_price']
stop_loss = trade.get('stop_loss')
take_profit = trade.get('take_profit')
should_close, close_reason = False, ""
# التحقق من شروط الإغلاق
if stop_loss and current_price <= stop_loss:
should_close, close_reason = True, f"وصول وقف الخسارة: {current_price} <= {stop_loss}"
elif take_profit and current_price >= take_profit:
should_close, close_reason = True, f"وصول جني الأرباح: {current_price} >= {take_profit}"
# تحديث وقف الخسارة الديناميكي
if not should_close and current_price > entry_price:
dynamic_stop = current_price * 0.98
if dynamic_stop > (stop_loss or 0):
trade['stop_loss'] = dynamic_stop
# إغلاق الصفقة إذا لزم الأمر
if should_close:
if self.r2_service.acquire_lock():
try:
await self.immediate_close_trade(symbol, current_price, close_reason)
except Exception as close_error:
print(f"❌ فشل الإغلاق التلقائي لـ {symbol}: {close_error}")
finally:
self.r2_service.release_lock()
break
# إعادة تعيين عداد الأخطاء عند النجاح
if symbol in self.monitoring_errors:
self.monitoring_errors[symbol] = 0
# التحقق من وقت المراقبة الطويل
monitoring_duration = time.time() - start_time
if monitoring_duration > max_monitoring_time:
print(f"🕒 انتهى وقت مراقبة الصفقة {symbol}")
break
await asyncio.sleep(15)
except Exception as error:
error_count = self._increment_monitoring_error(symbol)
print(f"❌ خطأ في مراقبة {symbol} (الخطأ #{error_count}): {error}")
if error_count >= self.max_consecutive_errors:
print(f"🚨 إيقاف مراقبة {symbol} بسبب الأخطاء المتتالية")
await self.r2_service.save_system_logs_async({
"monitoring_stopped": True,
"symbol": symbol,
"error_count": error_count,
"error": str(error)
})
break
await asyncio.sleep(30)
print(f"🛑 توقيف مراقبة الصفقة: {symbol}")
def _increment_monitoring_error(self, symbol):
if symbol not in self.monitoring_errors:
self.monitoring_errors[symbol] = 0
self.monitoring_errors[symbol] += 1
return self.monitoring_errors[symbol]
def stop_monitoring(self):
self.is_running = False
print("🛑 إيقاف جميع مهام المراقبة...")
for symbol, task_info in self.monitoring_tasks.items():
if not task_info['task'].done():
task_info['task'].cancel()
print(f"✅ تم إلغاء مهمة مراقبة {symbol}")
self.monitoring_tasks.clear()
self.monitoring_errors.clear()
async def _archive_closed_trade(self, closed_trade):
try:
key = "closed_trades_history.json"
try:
response = self.r2_service.s3_client.get_object(Bucket="trading", Key=key)
history = json.loads(response['Body'].read())
except Exception:
history = []
history.append(closed_trade)
# حفظ آخر 1000 صفقة فقط
if len(history) > 1000:
history = history[-1000:]
data_json = json.dumps(history, indent=2).encode('utf-8')
self.r2_service.s3_client.put_object(
Bucket="trading", Key=key, Body=data_json, ContentType="application/json"
)
except Exception as e:
print(f"❌ فشل أرشفة الصفقة: {e}")
async def _update_trade_summary(self, closed_trade):
try:
key = "trade_summary.json"
try:
response = self.r2_service.s3_client.get_object(Bucket="trading", Key=key)
summary = json.loads(response['Body'].read())
except Exception:
summary = {
"total_trades": 0, "winning_trades": 0, "losing_trades": 0,
"total_profit_usd": 0.0, "total_loss_usd": 0.0, "win_percentage": 0.0,
"avg_profit_per_trade": 0.0, "avg_loss_per_trade": 0.0,
"largest_win": 0.0, "largest_loss": 0.0,
"last_updated": datetime.now().isoformat()
}
pnl = closed_trade.get('pnl_usd', 0.0)
summary['total_trades'] += 1
if pnl >= 0:
summary['winning_trades'] += 1
summary['total_profit_usd'] += pnl
if pnl > summary.get('largest_win', 0):
summary['largest_win'] = pnl
else:
summary['losing_trades'] += 1
summary['total_loss_usd'] += abs(pnl)
if abs(pnl) > summary.get('largest_loss', 0):
summary['largest_loss'] = abs(pnl)
if summary['total_trades'] > 0:
summary['win_percentage'] = (summary['winning_trades'] / summary['total_trades']) * 100
if summary['winning_trades'] > 0:
summary['avg_profit_per_trade'] = summary['total_profit_usd'] / summary['winning_trades']
if summary['losing_trades'] > 0:
summary['avg_loss_per_trade'] = summary['total_loss_usd'] / summary['losing_trades']
summary['last_updated'] = datetime.now().isoformat()
data_json = json.dumps(summary, indent=2).encode('utf-8')
self.r2_service.s3_client.put_object(
Bucket="trading", Key=key, Body=data_json, ContentType="application/json"
)
except Exception as e:
print(f"❌ فشل تحديث ملخص التداول: {e}")
async def get_open_trades(self):
try:
return await self.r2_service.get_open_trades_async()
except Exception as e:
print(f"❌ فشل جلب الصفقات المفتوحة: {e}")
return []
async def get_trade_by_symbol(self, symbol):
try:
open_trades = await self.get_open_trades()
for trade in open_trades:
if trade['symbol'] == symbol and trade['status'] == 'OPEN':
return trade
return None
except Exception as e:
print(f"❌ فشل البحث عن صفقة {symbol}: {e}")
return None
def get_monitoring_status(self):
return {
'is_running': self.is_running,
'active_tasks': len(self.monitoring_tasks),
'monitoring_errors': dict(self.monitoring_errors),
'max_consecutive_errors': self.max_consecutive_errors
} |