Spaces:
Paused
Paused
Update r2.py
Browse files
r2.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# r2.py (محدث)
|
| 2 |
import os, traceback, json, time
|
| 3 |
from datetime import datetime, timedelta
|
| 4 |
import asyncio
|
|
@@ -11,6 +11,12 @@ R2_SECRET_ACCESS_KEY = os.getenv("R2_SECRET_ACCESS_KEY")
|
|
| 11 |
BUCKET_NAME = "trading"
|
| 12 |
INITIAL_CAPITAL = 10.0
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
class R2Service:
|
| 15 |
def __init__(self):
|
| 16 |
try:
|
|
@@ -317,7 +323,7 @@ class R2Service:
|
|
| 317 |
if updated:
|
| 318 |
await self.save_open_trades_async(open_trades)
|
| 319 |
status = "ENABLED" if is_monitored else "DISABLED"
|
| 320 |
-
print(f"✅ Real-time monitoring {
|
| 321 |
else:
|
| 322 |
print(f"⚠️ Trade {symbol} not found for monitoring status update")
|
| 323 |
return updated
|
|
@@ -373,5 +379,117 @@ class R2Service:
|
|
| 373 |
except Exception as e:
|
| 374 |
print(f"❌ فشل حفظ سجل تدقيق التحليل في R2: {e}")
|
| 375 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
|
| 377 |
print("✅ Enhanced R2 Service Loaded - Comprehensive Logging System with Candidates Support")
|
|
|
|
| 1 |
+
# r2.py (محدث V10.2 - Whale Learning Storage)
|
| 2 |
import os, traceback, json, time
|
| 3 |
from datetime import datetime, timedelta
|
| 4 |
import asyncio
|
|
|
|
| 11 |
BUCKET_NAME = "trading"
|
| 12 |
INITIAL_CAPITAL = 10.0
|
| 13 |
|
| 14 |
+
# 🔴 --- (جديد V10.2) أسماء ملفات التعلم --- 🔴
|
| 15 |
+
WHALE_LEARNING_PENDING_KEY = "learning_whale_pending_records.json"
|
| 16 |
+
WHALE_LEARNING_COMPLETED_KEY = "learning_whale_completed_records.json"
|
| 17 |
+
WHALE_LEARNING_CONFIG_KEY = "learning_whale_optimal_config.json"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
class R2Service:
|
| 21 |
def __init__(self):
|
| 22 |
try:
|
|
|
|
| 323 |
if updated:
|
| 324 |
await self.save_open_trades_async(open_trades)
|
| 325 |
status = "ENABLED" if is_monitored else "DISABLED"
|
| 326 |
+
print(f"✅ Real-time monitoring {STATUS} for {symbol}")
|
| 327 |
else:
|
| 328 |
print(f"⚠️ Trade {symbol} not found for monitoring status update")
|
| 329 |
return updated
|
|
|
|
| 379 |
except Exception as e:
|
| 380 |
print(f"❌ فشل حفظ سجل تدقيق التحليل في R2: {e}")
|
| 381 |
|
| 382 |
+
# 🔴 --- START OF CHANGE (V10.2 - Whale Learning Storage) --- 🔴
|
| 383 |
+
|
| 384 |
+
async def _load_json_file_from_r2(self, key: str, default: Any = []) -> Any:
|
| 385 |
+
"""دالة مساعدة لتحميل ملف JSON بأمان."""
|
| 386 |
+
try:
|
| 387 |
+
response = self.s3_client.get_object(Bucket=self.BUCKET_NAME, Key=key)
|
| 388 |
+
return json.loads(response['Body'].read())
|
| 389 |
+
except ClientError as e:
|
| 390 |
+
if e.response['Error']['Code'] == 'NoSuchKey':
|
| 391 |
+
print(f"ℹ️ [R2Service] لم يتم العثور على ملف '{key}'. سيتم استخدام القيمة الافتراضية.")
|
| 392 |
+
return default
|
| 393 |
+
else:
|
| 394 |
+
print(f"❌ [R2Service] خطأ ClientError أثناء تحميل '{key}': {e}")
|
| 395 |
+
raise
|
| 396 |
+
except Exception as e:
|
| 397 |
+
print(f"❌ [R2Service] خطأ عام أثناء تحميل '{key}': {e}")
|
| 398 |
+
return default
|
| 399 |
+
|
| 400 |
+
async def _save_json_file_to_r2(self, key: str, data: Any):
|
| 401 |
+
"""دالة مساعدة لحفظ ملف JSON بأمان."""
|
| 402 |
+
try:
|
| 403 |
+
data_json = json.dumps(data, indent=2, ensure_ascii=False).encode('utf-8')
|
| 404 |
+
self.s3_client.put_object(
|
| 405 |
+
Bucket=self.BUCKET_NAME, Key=key, Body=data_json, ContentType="application/json"
|
| 406 |
+
)
|
| 407 |
+
except Exception as e:
|
| 408 |
+
print(f"❌ [R2Service] فشل حفظ الملف '{key}' إلى R2: {e}")
|
| 409 |
+
traceback.print_exc()
|
| 410 |
+
|
| 411 |
+
async def save_whale_learning_record_async(self, record: Dict[str, Any]):
|
| 412 |
+
"""
|
| 413 |
+
(جديد V10.2)
|
| 414 |
+
يحفظ سجلاً "معلقاً" جديداً في ملف PENDING.
|
| 415 |
+
"""
|
| 416 |
+
try:
|
| 417 |
+
pending_records = await self._load_json_file_from_r2(WHALE_LEARNING_PENDING_KEY, default=[])
|
| 418 |
+
pending_records.append(record)
|
| 419 |
+
await self._save_json_file_to_r2(WHALE_LEARNING_PENDING_KEY, pending_records)
|
| 420 |
+
print(f"✅ [R2Service] تم حفظ سجل تعلم الحيتان (PENDING) لـ {record['symbol']}.")
|
| 421 |
+
except Exception as e:
|
| 422 |
+
print(f"❌ [R2Service] فشل في save_whale_learning_record_async: {e}")
|
| 423 |
+
|
| 424 |
+
async def get_pending_whale_learning_records_async(self) -> List[Dict[str, Any]]:
|
| 425 |
+
"""
|
| 426 |
+
(جديد V10.2)
|
| 427 |
+
يجلب جميع السجلات "المعلقة" من ملف PENDING.
|
| 428 |
+
"""
|
| 429 |
+
try:
|
| 430 |
+
return await self._load_json_file_from_r2(WHALE_LEARNING_PENDING_KEY, default=[])
|
| 431 |
+
except Exception as e:
|
| 432 |
+
print(f"❌ [R2Service] فشل في get_pending_whale_learning_records_async: {e}")
|
| 433 |
+
return []
|
| 434 |
+
|
| 435 |
+
async def update_completed_whale_learning_record_async(self, completed_record: Dict[str, Any]):
|
| 436 |
+
"""
|
| 437 |
+
(جديد V10.2)
|
| 438 |
+
1. يحفظ السجل "المكتمل" في ملف COMPLETED.
|
| 439 |
+
2. يزيل السجل من ملف PENDING.
|
| 440 |
+
"""
|
| 441 |
+
try:
|
| 442 |
+
record_id = completed_record.get("record_id")
|
| 443 |
+
if not record_id:
|
| 444 |
+
print("❌ [R2Service] لا يمكن تحديث سجل مكتمل بدون record_id.")
|
| 445 |
+
return
|
| 446 |
+
|
| 447 |
+
# 1. الحفظ في ملف المكتمل (يحتفظ بآخر 5000 سجل مكتمل)
|
| 448 |
+
completed_records = await self._load_json_file_from_r2(WHALE_LEARNING_COMPLETED_KEY, default=[])
|
| 449 |
+
completed_records.append(completed_record)
|
| 450 |
+
if len(completed_records) > 5000:
|
| 451 |
+
completed_records = completed_records[-5000:]
|
| 452 |
+
await self._save_json_file_to_r2(WHALE_LEARNING_COMPLETED_KEY, completed_records)
|
| 453 |
+
|
| 454 |
+
# 2. الإزالة من ملف المعلق
|
| 455 |
+
pending_records = await self._load_json_file_from_r2(WHALE_LEARNING_PENDING_KEY, default=[])
|
| 456 |
+
updated_pending_records = [
|
| 457 |
+
rec for rec in pending_records if rec.get("record_id") != record_id
|
| 458 |
+
]
|
| 459 |
+
await self._save_json_file_to_r2(WHALE_LEARNING_PENDING_KEY, updated_pending_records)
|
| 460 |
+
|
| 461 |
+
print(f"✅ [R2Service] تم نقل سجل تعلم الحيتان (COMPLETED) لـ {completed_record['symbol']} (ID: {record_id}).")
|
| 462 |
+
|
| 463 |
+
except Exception as e:
|
| 464 |
+
print(f"❌ [R2Service] فشل في update_completed_whale_learning_record_async: {e}")
|
| 465 |
+
|
| 466 |
+
async def get_all_completed_whale_records_async(self) -> List[Dict[str, Any]]:
|
| 467 |
+
"""
|
| 468 |
+
(جديد V10.2)
|
| 469 |
+
يجلب *جميع* السجلات المكتملة (لتحليل الارتباط).
|
| 470 |
+
"""
|
| 471 |
+
try:
|
| 472 |
+
return await self._load_json_file_from_r2(WHALE_LEARNING_COMPLETED_KEY, default=[])
|
| 473 |
+
except Exception as e:
|
| 474 |
+
print(f"❌ [R2Service] فشل في get_all_completed_whale_records_async: {e}")
|
| 475 |
+
return []
|
| 476 |
+
|
| 477 |
+
async def save_whale_learning_config_async(self, config: Dict[str, Any]):
|
| 478 |
+
"""
|
| 479 |
+
(جديد V10.2)
|
| 480 |
+
يحفظ ملف الإعدادات (الأوزان) الذي نتج عن التعلم.
|
| 481 |
+
"""
|
| 482 |
+
await self._save_json_file_to_r2(WHALE_LEARNING_CONFIG_KEY, config)
|
| 483 |
+
print(f"✅ [R2Service] تم حفظ إعدادات تعلم الحيتان المثلى.")
|
| 484 |
+
|
| 485 |
+
async def load_whale_learning_config_async(self) -> Dict[str, Any]:
|
| 486 |
+
"""
|
| 487 |
+
(جديد V10.2)
|
| 488 |
+
يجلب ملف الإعدادات (الأوزان) الذي نتج عن التعلم.
|
| 489 |
+
"""
|
| 490 |
+
return await self._load_json_file_from_r2(WHALE_LEARNING_CONFIG_KEY, default={})
|
| 491 |
+
|
| 492 |
+
# 🔴 --- END OF CHANGE --- 🔴
|
| 493 |
+
|
| 494 |
|
| 495 |
print("✅ Enhanced R2 Service Loaded - Comprehensive Logging System with Candidates Support")
|