Riy777 commited on
Commit
a408586
·
verified ·
1 Parent(s): fc2dff6

Update r2.py

Browse files
Files changed (1) hide show
  1. r2.py +45 -16
r2.py CHANGED
@@ -1,4 +1,11 @@
1
- # r2.py (V14.0 - GEM-Architect: Full Support for Training & Models)
 
 
 
 
 
 
 
2
  import os
3
  import traceback
4
  import json
@@ -27,6 +34,9 @@ WHALE_LEARNING_COMPLETED_KEY = "learning_whale_completed_records.json"
27
  WHALE_LEARNING_CONFIG_KEY = "learning_whale_optimal_config.json"
28
 
29
  PORTFOLIO_STATE_KEY = "portfolio_state.json"
 
 
 
30
  OPEN_TRADES_KEY = "open_trades.json"
31
  CLOSED_TRADES_KEY = "closed_trades_history.json"
32
 
@@ -58,16 +68,18 @@ class R2Service:
58
  raise RuntimeError(f"Failed to initialize S3 client: {e}")
59
 
60
  # ==============================================================================
61
- # 🔴 [هام جداً] دالة التصفير الشامل
62
  # ==============================================================================
63
  async def reset_all_stats_async(self):
64
  """تصفير المحفظة والسجلات التاريخية والعودة لنقطة الصفر"""
65
  try:
66
  print("🔄 [R2 Reset] بدء عملية التصفير...")
67
 
 
68
  initial_state = {
69
  "current_capital_usd": INITIAL_CAPITAL,
70
- "invested_capital_usd": 0.0,
 
71
  "initial_capital_usd": INITIAL_CAPITAL,
72
  "total_trades": 0,
73
  "winning_trades": 0,
@@ -75,10 +87,27 @@ class R2Service:
75
  "total_profit_usd": 0.0,
76
  "total_loss_usd": 0.0,
77
  "win_rate": 0.0,
 
 
78
  "last_update": datetime.now().isoformat()
79
  }
 
 
80
  await self.save_portfolio_state_async(initial_state)
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  empty_list_json = json.dumps([], indent=2).encode('utf-8')
83
  self.s3_client.put_object(
84
  Bucket=BUCKET_NAME, Key=CLOSED_TRADES_KEY, Body=empty_list_json, ContentType="application/json"
@@ -89,7 +118,7 @@ class R2Service:
89
  Bucket=BUCKET_NAME, Key=SYSTEM_LOGS_KEY, Body=empty_logs_json, ContentType="application/json"
90
  )
91
 
92
- print("✅ [R2 Reset] تم تصفير جميع البيانات والمحفظة بنجاح.")
93
  return True
94
 
95
  except Exception as e:
@@ -98,13 +127,12 @@ class R2Service:
98
  return False
99
 
100
  # ==============================================================================
101
- # 🆕 دوال دعم التدريب (Training Support) - [NEW for V13 Learning Hub]
102
  # ==============================================================================
103
  async def upload_json_async(self, data: Any, key: str):
104
  """رفع أي بيانات JSON إلى مسار محدد"""
105
  try:
106
  json_bytes = json.dumps(data, indent=2, ensure_ascii=False).encode('utf-8')
107
- # تشغيل الرفع في Thread منفصل لمنع تجميد الحلقة
108
  await asyncio.to_thread(
109
  self.s3_client.put_object,
110
  Bucket=self.BUCKET_NAME,
@@ -126,7 +154,6 @@ class R2Service:
126
  )
127
  return response['Body'].read()
128
  except ClientError as e:
129
- # إذا الملف غير موجود، نرجع None بدلاً من رفع استثناء
130
  if e.response['Error']['Code'] == 'NoSuchKey':
131
  return None
132
  raise
@@ -191,11 +218,9 @@ class R2Service:
191
  # 📝 السجلات والتعلم
192
  # ==============================================================================
193
  async def save_system_logs_async(self, log_data):
194
- # (يمكن تحسينها باستخدام append بدلاً من قراءة الكل، لكن سنبقيها بسيطة الآن)
195
- pass # تم تعطيلها لتخفيف الحمل، الاعتماد على Console Logs + Audit
196
 
197
  async def append_deep_steward_audit(self, audit_record: Dict[str, Any]):
198
- """حفظ تحليل ما بعد الخروج"""
199
  try:
200
  file_key = "DeepSteward_Audit_Log.json"
201
  data_bytes = await self.get_file_async(file_key)
@@ -210,25 +235,30 @@ class R2Service:
210
  print(f"❌ [R2 Error] فشل حفظ التدقيق: {e}")
211
 
212
  # ==============================================================================
213
- # 💰 إدارة المحفظة (Accounting)
214
  # ==============================================================================
215
  async def get_portfolio_state_async(self):
216
  try:
217
  data_bytes = await self.get_file_async(PORTFOLIO_STATE_KEY)
218
  if data_bytes:
219
  state = json.loads(data_bytes)
220
- # تصحيح البيانات القديمة
221
  if 'losing_trades' not in state: state['losing_trades'] = 0
222
  if 'initial_capital_usd' not in state: state['initial_capital_usd'] = INITIAL_CAPITAL
 
 
223
  return state
224
 
225
- # تهيئة افتراضية
226
  initial_state = {
227
  "current_capital_usd": INITIAL_CAPITAL,
228
- "invested_capital_usd": 0.0,
 
229
  "initial_capital_usd": INITIAL_CAPITAL,
230
  "total_trades": 0, "winning_trades": 0, "losing_trades": 0,
231
  "total_profit_usd": 0.0, "total_loss_usd": 0.0, "win_rate": 0.0,
 
 
232
  "last_update": datetime.now().isoformat()
233
  }
234
  await self.save_portfolio_state_async(initial_state)
@@ -292,7 +322,6 @@ class R2Service:
292
  rec_id = completed_record.get("record_id")
293
  if not rec_id: return
294
 
295
- # نقل من Pending -> Completed
296
  comp_data = await self.get_file_async(WHALE_LEARNING_COMPLETED_KEY)
297
  completed = json.loads(comp_data) if comp_data else []
298
  completed.append(completed_record)
@@ -316,4 +345,4 @@ class R2Service:
316
  data = await self.get_file_async(WHALE_LEARNING_CONFIG_KEY)
317
  return json.loads(data) if data else {}
318
 
319
- print("✅ [R2 V14.0] Full Service Loaded (Training & Models Support).")
 
1
+ # ==============================================================================
2
+ # ☁️ r2.py (V14.1 - GEM-Architect: Portfolio-Ready Storage)
3
+ # ==============================================================================
4
+ # التحديثات:
5
+ # 1. دعم الحقول الجديدة (allocated_capital, daily_net_pnl) في الهيكل الافتراضي.
6
+ # 2. تصفير شامل يشمل ملف حالة المحفظة الذكية (smart_portfolio_state.json).
7
+ # ==============================================================================
8
+
9
  import os
10
  import traceback
11
  import json
 
34
  WHALE_LEARNING_CONFIG_KEY = "learning_whale_optimal_config.json"
35
 
36
  PORTFOLIO_STATE_KEY = "portfolio_state.json"
37
+ # ✅ المفتاح الجديد لحالة المحفظة الذكية
38
+ SMART_PORTFOLIO_STATE_KEY = "smart_portfolio_state.json"
39
+
40
  OPEN_TRADES_KEY = "open_trades.json"
41
  CLOSED_TRADES_KEY = "closed_trades_history.json"
42
 
 
68
  raise RuntimeError(f"Failed to initialize S3 client: {e}")
69
 
70
  # ==============================================================================
71
+ # 🔴 [هام جداً] دالة التصفير الشامل (Updated for Smart Portfolio)
72
  # ==============================================================================
73
  async def reset_all_stats_async(self):
74
  """تصفير المحفظة والسجلات التاريخية والعودة لنقطة الصفر"""
75
  try:
76
  print("🔄 [R2 Reset] بدء عملية التصفير...")
77
 
78
+ # 1. إعداد الحالة الأولية المتوافقة مع SmartPortfolio V1.2
79
  initial_state = {
80
  "current_capital_usd": INITIAL_CAPITAL,
81
+ "invested_capital_usd": 0.0, # حقل قديم (للتوافق)
82
+ "allocated_capital_usd": 0.0, # ✅ حقل جديد (للمحفظة الذكية)
83
  "initial_capital_usd": INITIAL_CAPITAL,
84
  "total_trades": 0,
85
  "winning_trades": 0,
 
87
  "total_profit_usd": 0.0,
88
  "total_loss_usd": 0.0,
89
  "win_rate": 0.0,
90
+ "daily_net_pnl": 0.0, # ✅ حقل جديد
91
+ "is_trading_halted": False, # ✅ حقل جديد
92
  "last_update": datetime.now().isoformat()
93
  }
94
+
95
+ # حفظ الحالة في الملف الرئيسي
96
  await self.save_portfolio_state_async(initial_state)
97
 
98
+ # ✅ تصفير ملف المحفظة الذكية الخاص أيضاً
99
+ smart_state = {
100
+ "current_capital": INITIAL_CAPITAL,
101
+ "allocated_capital_usd": 0.0,
102
+ "session_start_balance": INITIAL_CAPITAL,
103
+ "daily_net_pnl": 0.0,
104
+ "is_trading_halted": False,
105
+ "halt_reason": None,
106
+ "last_session_reset": datetime.now().isoformat()
107
+ }
108
+ await self.upload_json_async(smart_state, SMART_PORTFOLIO_STATE_KEY)
109
+
110
+ # تصفير السجلات الأخرى
111
  empty_list_json = json.dumps([], indent=2).encode('utf-8')
112
  self.s3_client.put_object(
113
  Bucket=BUCKET_NAME, Key=CLOSED_TRADES_KEY, Body=empty_list_json, ContentType="application/json"
 
118
  Bucket=BUCKET_NAME, Key=SYSTEM_LOGS_KEY, Body=empty_logs_json, ContentType="application/json"
119
  )
120
 
121
+ print("✅ [R2 Reset] تم تصفير جميع البيانات والمحفظة (بما في ذلك SmartPortfolio) بنجاح.")
122
  return True
123
 
124
  except Exception as e:
 
127
  return False
128
 
129
  # ==============================================================================
130
+ # 🆕 دوال دعم التدريب (Training Support)
131
  # ==============================================================================
132
  async def upload_json_async(self, data: Any, key: str):
133
  """رفع أي بيانات JSON إلى مسار محدد"""
134
  try:
135
  json_bytes = json.dumps(data, indent=2, ensure_ascii=False).encode('utf-8')
 
136
  await asyncio.to_thread(
137
  self.s3_client.put_object,
138
  Bucket=self.BUCKET_NAME,
 
154
  )
155
  return response['Body'].read()
156
  except ClientError as e:
 
157
  if e.response['Error']['Code'] == 'NoSuchKey':
158
  return None
159
  raise
 
218
  # 📝 السجلات والتعلم
219
  # ==============================================================================
220
  async def save_system_logs_async(self, log_data):
221
+ pass
 
222
 
223
  async def append_deep_steward_audit(self, audit_record: Dict[str, Any]):
 
224
  try:
225
  file_key = "DeepSteward_Audit_Log.json"
226
  data_bytes = await self.get_file_async(file_key)
 
235
  print(f"❌ [R2 Error] فشل حفظ التدقيق: {e}")
236
 
237
  # ==============================================================================
238
+ # 💰 إدارة المحفظة (Accounting - Updated)
239
  # ==============================================================================
240
  async def get_portfolio_state_async(self):
241
  try:
242
  data_bytes = await self.get_file_async(PORTFOLIO_STATE_KEY)
243
  if data_bytes:
244
  state = json.loads(data_bytes)
245
+ # تصحيح وتحديث البيانات القديمة لتشمل حقول SmartPortfolio
246
  if 'losing_trades' not in state: state['losing_trades'] = 0
247
  if 'initial_capital_usd' not in state: state['initial_capital_usd'] = INITIAL_CAPITAL
248
+ if 'allocated_capital_usd' not in state: state['allocated_capital_usd'] = 0.0
249
+ if 'daily_net_pnl' not in state: state['daily_net_pnl'] = 0.0
250
  return state
251
 
252
+ # تهيئة افتراضية متكاملة
253
  initial_state = {
254
  "current_capital_usd": INITIAL_CAPITAL,
255
+ "allocated_capital_usd": 0.0, # ✅ جديد
256
+ "invested_capital_usd": 0.0, # Legacy support
257
  "initial_capital_usd": INITIAL_CAPITAL,
258
  "total_trades": 0, "winning_trades": 0, "losing_trades": 0,
259
  "total_profit_usd": 0.0, "total_loss_usd": 0.0, "win_rate": 0.0,
260
+ "daily_net_pnl": 0.0, # ✅ جديد
261
+ "is_trading_halted": False,
262
  "last_update": datetime.now().isoformat()
263
  }
264
  await self.save_portfolio_state_async(initial_state)
 
322
  rec_id = completed_record.get("record_id")
323
  if not rec_id: return
324
 
 
325
  comp_data = await self.get_file_async(WHALE_LEARNING_COMPLETED_KEY)
326
  completed = json.loads(comp_data) if comp_data else []
327
  completed.append(completed_record)
 
345
  data = await self.get_file_async(WHALE_LEARNING_CONFIG_KEY)
346
  return json.loads(data) if data else {}
347
 
348
+ print("✅ [R2 V14.1] Service Loaded (Smart Portfolio Compatible).")