Spaces:
Paused
Paused
Update backtest_engine.py
Browse files- backtest_engine.py +52 -100
backtest_engine.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# ============================================================
|
| 2 |
-
# 🧪 backtest_engine.py (V86.
|
| 3 |
# ============================================================
|
| 4 |
|
| 5 |
import asyncio
|
|
@@ -10,8 +10,6 @@ import logging
|
|
| 10 |
import itertools
|
| 11 |
import os
|
| 12 |
import gc
|
| 13 |
-
import sys
|
| 14 |
-
import traceback
|
| 15 |
import concurrent.futures
|
| 16 |
from datetime import datetime, timezone
|
| 17 |
from typing import Dict, Any, List
|
|
@@ -28,52 +26,37 @@ logging.getLogger('ml_engine').setLevel(logging.WARNING)
|
|
| 28 |
CACHE_DIR = "backtest_real_scores"
|
| 29 |
|
| 30 |
# ==============================================================================
|
| 31 |
-
# 🚜 ISOLATED WORKER
|
| 32 |
# ==============================================================================
|
| 33 |
def run_parallel_chunk(chunk_payload):
|
| 34 |
"""
|
| 35 |
-
عامل مستقل مع
|
| 36 |
"""
|
| 37 |
symbol, start_ms, end_ms, chunk_id = chunk_payload
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
-
wait_time = chunk_id * 1.5
|
| 42 |
-
if chunk_id > 0:
|
| 43 |
-
time.sleep(wait_time)
|
| 44 |
|
| 45 |
-
print(f" ⚡ [Core {chunk_id}]
|
| 46 |
|
| 47 |
try:
|
| 48 |
-
#
|
| 49 |
-
# نمرر None لتجنب الاتصالات الثقيلة غير الضرورية، لكن DataManager يحتاج لتهيئة
|
| 50 |
local_dm = DataManager(None, None, None)
|
| 51 |
-
|
| 52 |
-
# حيلة: لا نستدعي initialize الكاملة لـ DM إذا كانت تتصل بالإنترنت لجلب الأسواق
|
| 53 |
-
# فقط نهيئ http_client إذا لزم الأمر يدوياً داخل المهمة
|
| 54 |
-
|
| 55 |
-
# تهيئة المعالج
|
| 56 |
local_proc = MLProcessor(local_dm)
|
| 57 |
|
| 58 |
-
# تشغيل حلقة الأحداث الخاصة بهذه العملية
|
| 59 |
loop = asyncio.new_event_loop()
|
| 60 |
asyncio.set_event_loop(loop)
|
| 61 |
|
| 62 |
-
# ت
|
| 63 |
-
# ملاحظة: MLProcessor قد يستغرق وقتاً لتحميل النماذج
|
| 64 |
loop.run_until_complete(local_proc.initialize())
|
| 65 |
-
|
| 66 |
-
if not local_dm.http_client:
|
| 67 |
-
import httpx
|
| 68 |
-
local_dm.http_client = httpx.AsyncClient(timeout=30.0)
|
| 69 |
|
| 70 |
-
# إنشاء نسخة محلية من الباكتستر
|
| 71 |
local_tester = HeavyDutyBacktester(local_dm, local_proc)
|
| 72 |
|
| 73 |
dt_start = datetime.fromtimestamp(start_ms/1000, tz=timezone.utc).strftime('%Y-%m-%d')
|
| 74 |
-
print(f" 📥 [Core {chunk_id}]
|
| 75 |
|
| 76 |
-
# فترة
|
| 77 |
warmup_ms = 2000 * 60 * 1000
|
| 78 |
actual_fetch_start = start_ms - warmup_ms
|
| 79 |
|
|
@@ -88,16 +71,17 @@ def run_parallel_chunk(chunk_payload):
|
|
| 88 |
)
|
| 89 |
)
|
| 90 |
|
| 91 |
-
# تنظيف
|
| 92 |
loop.run_until_complete(local_dm.close())
|
| 93 |
loop.close()
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
print(f" ✅ [Core {chunk_id}]
|
| 96 |
return (chunk_id, success)
|
| 97 |
|
| 98 |
except Exception as e:
|
| 99 |
-
print(f" ❌ [Core {chunk_id}]
|
| 100 |
-
traceback.print_exc() # طباعة تفاصيل الخطأ
|
| 101 |
return (chunk_id, False)
|
| 102 |
|
| 103 |
# ==============================================================================
|
|
@@ -108,16 +92,12 @@ class HeavyDutyBacktester:
|
|
| 108 |
self.dm = data_manager
|
| 109 |
self.proc = processor
|
| 110 |
self.GRID_DENSITY = 10
|
| 111 |
-
|
| 112 |
self.INITIAL_CAPITAL = 10.0
|
| 113 |
self.TRADING_FEES = 0.001
|
| 114 |
self.MAX_SLOTS = 4
|
| 115 |
-
|
| 116 |
self.TARGET_COINS = ['SOL/USDT']
|
| 117 |
-
|
| 118 |
self.force_start_date = None
|
| 119 |
self.force_end_date = None
|
| 120 |
-
|
| 121 |
if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR)
|
| 122 |
|
| 123 |
def set_date_range(self, start_str, end_str):
|
|
@@ -129,7 +109,7 @@ class HeavyDutyBacktester:
|
|
| 129 |
return df[['timestamp', 'open', 'high', 'low', 'close', 'volume']].values.tolist()
|
| 130 |
|
| 131 |
# ==============================================================
|
| 132 |
-
# 🧱 Core Logic: Single Coin Processor (With
|
| 133 |
# ==============================================================
|
| 134 |
async def _process_single_coin_task(self, sym, start_time_ms, end_time_ms, chunk_suffix="", analysis_start_ms=None, worker_id=0):
|
| 135 |
safe_sym = sym.replace('/', '_')
|
|
@@ -147,24 +127,15 @@ class HeavyDutyBacktester:
|
|
| 147 |
df_1m = None
|
| 148 |
frames = {}
|
| 149 |
|
| 150 |
-
# 1. تنزيل البيانات
|
| 151 |
try:
|
| 152 |
current_since = start_time_ms
|
| 153 |
-
req_count = 0
|
| 154 |
|
| 155 |
while current_since < end_time_ms:
|
| 156 |
try:
|
| 157 |
-
# إضافة مهلة وتكرار في حال الفشل
|
| 158 |
batch = await self.dm.exchange.fetch_ohlcv(sym, '1m', since=current_since, limit=1000)
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
# طباعة تقدم كل 5 طلبات لنعرف أن العملية حية
|
| 162 |
-
if req_count % 5 == 0:
|
| 163 |
-
print(f" ⏳ [Core {worker_id}] Fetched batch {req_count}...", flush=True)
|
| 164 |
-
|
| 165 |
-
except Exception as net_err:
|
| 166 |
-
print(f" ⚠️ [Core {worker_id}] Network hiccup: {net_err}. Retrying in 5s...", flush=True)
|
| 167 |
-
await asyncio.sleep(5)
|
| 168 |
continue
|
| 169 |
|
| 170 |
if not batch: break
|
|
@@ -174,21 +145,17 @@ class HeavyDutyBacktester:
|
|
| 174 |
|
| 175 |
all_candles_1m.extend(batch)
|
| 176 |
current_since = last_ts + 1
|
| 177 |
-
|
| 178 |
-
# تخفيف الضغط قليلاً على الـ API
|
| 179 |
-
await asyncio.sleep(0.1)
|
| 180 |
-
|
| 181 |
if current_since >= end_time_ms: break
|
| 182 |
|
| 183 |
all_candles_1m = [c for c in all_candles_1m if c[0] <= end_time_ms]
|
| 184 |
|
| 185 |
if not all_candles_1m:
|
| 186 |
-
print(f" ⚠️ [Core {worker_id}] No
|
| 187 |
return False
|
| 188 |
|
| 189 |
-
print(f" ⚙️ [Core {worker_id}]
|
| 190 |
|
| 191 |
-
# معالجة البيانات (Pandas)
|
| 192 |
df_1m = pd.DataFrame(all_candles_1m, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
|
| 193 |
cols = ['open', 'high', 'low', 'close', 'volume']
|
| 194 |
df_1m[cols] = df_1m[cols].astype('float32')
|
|
@@ -197,9 +164,8 @@ class HeavyDutyBacktester:
|
|
| 197 |
df_1m = df_1m.sort_index()
|
| 198 |
|
| 199 |
agg_dict = {'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum'}
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
frames['1m'] = df_1m_ready
|
| 203 |
|
| 204 |
for tf_str, tf_code in [('5m', '5T'), ('15m', '15T'), ('1h', '1h'), ('4h', '4h'), ('1d', '1D')]:
|
| 205 |
resampled = df_1m.resample(tf_code).agg(agg_dict).dropna()
|
|
@@ -211,34 +177,30 @@ class HeavyDutyBacktester:
|
|
| 211 |
analysis_start_dt = pd.to_datetime(analysis_start_ms, unit='ms')
|
| 212 |
valid_indices = frames['5m'].loc[analysis_start_dt:].index
|
| 213 |
|
| 214 |
-
# حلقة الذكاء الاصطناعي
|
| 215 |
total_steps = len(valid_indices)
|
| 216 |
step_count = 0
|
| 217 |
|
|
|
|
| 218 |
for t_idx in valid_indices:
|
| 219 |
if t_idx.timestamp() * 1000 > end_time_ms: break
|
| 220 |
step_count += 1
|
| 221 |
|
| 222 |
-
# طباعة تقدم
|
| 223 |
-
if step_count % max(1, (total_steps
|
| 224 |
-
|
|
|
|
| 225 |
|
| 226 |
current_timestamp = int(t_idx.timestamp() * 1000)
|
| 227 |
ohlcv_data = {}
|
| 228 |
try:
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
ohlcv_data['
|
| 237 |
-
ohlcv_data['5m'] = self.df_to_list(current_slice_5m.tail(200))
|
| 238 |
-
ohlcv_data['15m'] = self.df_to_list(current_slice_15m.tail(200))
|
| 239 |
-
ohlcv_data['1h'] = self.df_to_list(current_slice_1h.tail(200))
|
| 240 |
-
ohlcv_data['4h'] = self.df_to_list(current_slice_4h.tail(100))
|
| 241 |
-
ohlcv_data['1d'] = self.df_to_list(current_slice_1d.tail(50))
|
| 242 |
except: continue
|
| 243 |
|
| 244 |
if len(ohlcv_data['1h']) < 60: continue
|
|
@@ -250,13 +212,7 @@ class HeavyDutyBacktester:
|
|
| 250 |
'ohlcv_15m': ohlcv_data['15m'][-60:],
|
| 251 |
'change_24h': 0.0
|
| 252 |
}
|
| 253 |
-
|
| 254 |
-
if len(ohlcv_data['1h']) >= 24:
|
| 255 |
-
p_now = ohlcv_data['1h'][-1][4]
|
| 256 |
-
p_old = ohlcv_data['1h'][-24][4]
|
| 257 |
-
logic_packet['change_24h'] = ((p_now - p_old) / p_old) * 100
|
| 258 |
-
except: pass
|
| 259 |
-
|
| 260 |
logic_result = self.dm._apply_logic_tree(logic_packet)
|
| 261 |
signal_type = logic_result.get('type', 'NONE')
|
| 262 |
l1_score = logic_result.get('score', 0.0)
|
|
@@ -281,13 +237,14 @@ class HeavyDutyBacktester:
|
|
| 281 |
dt = time.time() - t0
|
| 282 |
if ai_results:
|
| 283 |
pd.DataFrame(ai_results).to_pickle(scores_file)
|
| 284 |
-
print(f" 💾 [Core {worker_id}] Saved {len(ai_results)} signals. (
|
|
|
|
|
|
|
| 285 |
|
| 286 |
return True
|
| 287 |
|
| 288 |
except Exception as e:
|
| 289 |
-
print(f" ❌ [Core {worker_id}]
|
| 290 |
-
traceback.print_exc()
|
| 291 |
return False
|
| 292 |
|
| 293 |
finally:
|
|
@@ -297,7 +254,7 @@ class HeavyDutyBacktester:
|
|
| 297 |
gc.collect()
|
| 298 |
|
| 299 |
# ==============================================================
|
| 300 |
-
# PHASE 1: Main Loop
|
| 301 |
# ==============================================================
|
| 302 |
async def generate_truth_data(self):
|
| 303 |
if self.force_start_date and self.force_end_date:
|
|
@@ -306,13 +263,13 @@ class HeavyDutyBacktester:
|
|
| 306 |
start_time_ms = int(dt_start.timestamp() * 1000)
|
| 307 |
end_time_ms = int(dt_end.timestamp() * 1000)
|
| 308 |
print(f"\n🚜 [Phase 1] Processing Era: {self.force_start_date} -> {self.force_end_date}")
|
| 309 |
-
print(f" 🚀 Turbo Mode:
|
| 310 |
else:
|
| 311 |
return
|
| 312 |
|
| 313 |
-
|
| 314 |
-
#
|
| 315 |
-
workers_count =
|
| 316 |
|
| 317 |
total_duration = end_time_ms - start_time_ms
|
| 318 |
chunk_size = total_duration // workers_count
|
|
@@ -352,8 +309,7 @@ class HeavyDutyBacktester:
|
|
| 352 |
df_part = pd.read_pickle(part_file)
|
| 353 |
if not df_part.empty: all_dfs.append(df_part)
|
| 354 |
os.remove(part_file)
|
| 355 |
-
except
|
| 356 |
-
print(f" ⚠️ Merge Error (Part {chunk_id}): {e}")
|
| 357 |
|
| 358 |
if all_dfs:
|
| 359 |
final_df = pd.concat(all_dfs).drop_duplicates(subset=['timestamp']).sort_values('timestamp')
|
|
@@ -361,11 +317,10 @@ class HeavyDutyBacktester:
|
|
| 361 |
print(f" 💾 [{sym}] FINAL SAVE: {len(final_df)} signals.")
|
| 362 |
else:
|
| 363 |
print(f" ⚠️ [{sym}] No signals generated.")
|
| 364 |
-
|
| 365 |
gc.collect()
|
| 366 |
|
| 367 |
# ==============================================================
|
| 368 |
-
# PHASE 2: Portfolio Digital Twin Engine (Unchanged
|
| 369 |
# ==============================================================
|
| 370 |
@staticmethod
|
| 371 |
def _worker_optimize(combinations_batch, scores_files, initial_capital, fees_pct, max_slots):
|
|
@@ -388,7 +343,6 @@ class HeavyDutyBacktester:
|
|
| 388 |
for ts, group in grouped_by_time:
|
| 389 |
active_symbols = list(wallet["positions"].keys())
|
| 390 |
current_prices = {row['symbol']: row['close'] for _, row in group.iterrows()}
|
| 391 |
-
# Exits
|
| 392 |
for sym in active_symbols:
|
| 393 |
if sym in current_prices:
|
| 394 |
curr_p = current_prices[sym]
|
|
@@ -403,7 +357,7 @@ class HeavyDutyBacktester:
|
|
| 403 |
wallet["balance"] += net_pnl
|
| 404 |
del wallet["positions"][sym]
|
| 405 |
wallet["trades_history"].append({'pnl': net_pnl})
|
| 406 |
-
|
| 407 |
current_total_equity = wallet["balance"] + wallet["allocated"]
|
| 408 |
if current_total_equity > peak_balance: peak_balance = current_total_equity
|
| 409 |
dd = (peak_balance - current_total_equity) / peak_balance
|
|
@@ -442,7 +396,6 @@ class HeavyDutyBacktester:
|
|
| 442 |
win_count = len([p for p in pnls if p > 0]); loss_count = len([p for p in pnls if p <= 0])
|
| 443 |
win_rate = (win_count / len(trades)) * 100
|
| 444 |
max_single_win = max(pnls) if pnls else 0.0; max_single_loss = min(pnls) if pnls else 0.0
|
| 445 |
-
|
| 446 |
current_win_streak = 0; max_win_streak = 0
|
| 447 |
current_loss_streak = 0; max_loss_streak = 0
|
| 448 |
for p in pnls:
|
|
@@ -452,7 +405,6 @@ class HeavyDutyBacktester:
|
|
| 452 |
else:
|
| 453 |
current_loss_streak += 1; current_win_streak = 0
|
| 454 |
if current_loss_streak > max_loss_streak: max_loss_streak = current_loss_streak
|
| 455 |
-
|
| 456 |
results.append({
|
| 457 |
'config': config, 'final_balance': wallet["balance"] + wallet["allocated"],
|
| 458 |
'net_profit': net_profit, 'total_trades': len(trades),
|
|
@@ -520,7 +472,7 @@ class HeavyDutyBacktester:
|
|
| 520 |
return best['config'], best
|
| 521 |
|
| 522 |
async def run_strategic_optimization_task():
|
| 523 |
-
print("\n🧪 [STRATEGIC BACKTEST] Time Lord Initiated (
|
| 524 |
r2 = R2Service()
|
| 525 |
dm = DataManager(None, None, r2)
|
| 526 |
proc = MLProcessor(dm)
|
|
|
|
| 1 |
# ============================================================
|
| 2 |
+
# 🧪 backtest_engine.py (V86.3 - GEM-Architect: Stable Parallel)
|
| 3 |
# ============================================================
|
| 4 |
|
| 5 |
import asyncio
|
|
|
|
| 10 |
import itertools
|
| 11 |
import os
|
| 12 |
import gc
|
|
|
|
|
|
|
| 13 |
import concurrent.futures
|
| 14 |
from datetime import datetime, timezone
|
| 15 |
from typing import Dict, Any, List
|
|
|
|
| 26 |
CACHE_DIR = "backtest_real_scores"
|
| 27 |
|
| 28 |
# ==============================================================================
|
| 29 |
+
# 🚜 ISOLATED WORKER (Stable & Clean)
|
| 30 |
# ==============================================================================
|
| 31 |
def run_parallel_chunk(chunk_payload):
|
| 32 |
"""
|
| 33 |
+
عامل مستقل بمعايير ثبات عالية.
|
| 34 |
"""
|
| 35 |
symbol, start_ms, end_ms, chunk_id = chunk_payload
|
| 36 |
|
| 37 |
+
# تأخير بسيط جداً عند الإقلاع لتخفيف صدمة المعالج
|
| 38 |
+
time.sleep(chunk_id * 1.0)
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
print(f" ⚡ [Core {chunk_id}] Initializing ML Engine...", flush=True)
|
| 41 |
|
| 42 |
try:
|
| 43 |
+
# تهيئة بيئة نظيفة
|
|
|
|
| 44 |
local_dm = DataManager(None, None, None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
local_proc = MLProcessor(local_dm)
|
| 46 |
|
|
|
|
| 47 |
loop = asyncio.new_event_loop()
|
| 48 |
asyncio.set_event_loop(loop)
|
| 49 |
|
| 50 |
+
# تحميل النماذج (هنا يكمن الثقل)
|
|
|
|
| 51 |
loop.run_until_complete(local_proc.initialize())
|
| 52 |
+
loop.run_until_complete(local_dm.initialize())
|
|
|
|
|
|
|
|
|
|
| 53 |
|
|
|
|
| 54 |
local_tester = HeavyDutyBacktester(local_dm, local_proc)
|
| 55 |
|
| 56 |
dt_start = datetime.fromtimestamp(start_ms/1000, tz=timezone.utc).strftime('%Y-%m-%d')
|
| 57 |
+
print(f" 📥 [Core {chunk_id}] Fetching Data from {dt_start}...", flush=True)
|
| 58 |
|
| 59 |
+
# إضافة فترة تحمية للمؤشرات (2000 دقيقة)
|
| 60 |
warmup_ms = 2000 * 60 * 1000
|
| 61 |
actual_fetch_start = start_ms - warmup_ms
|
| 62 |
|
|
|
|
| 71 |
)
|
| 72 |
)
|
| 73 |
|
| 74 |
+
# تنظيف الذاكرة فوراً
|
| 75 |
loop.run_until_complete(local_dm.close())
|
| 76 |
loop.close()
|
| 77 |
+
del local_dm, local_proc, local_tester
|
| 78 |
+
gc.collect()
|
| 79 |
|
| 80 |
+
print(f" ✅ [Core {chunk_id}] Completed.", flush=True)
|
| 81 |
return (chunk_id, success)
|
| 82 |
|
| 83 |
except Exception as e:
|
| 84 |
+
print(f" ❌ [Core {chunk_id}] CRASH: {e}", flush=True)
|
|
|
|
| 85 |
return (chunk_id, False)
|
| 86 |
|
| 87 |
# ==============================================================================
|
|
|
|
| 92 |
self.dm = data_manager
|
| 93 |
self.proc = processor
|
| 94 |
self.GRID_DENSITY = 10
|
|
|
|
| 95 |
self.INITIAL_CAPITAL = 10.0
|
| 96 |
self.TRADING_FEES = 0.001
|
| 97 |
self.MAX_SLOTS = 4
|
|
|
|
| 98 |
self.TARGET_COINS = ['SOL/USDT']
|
|
|
|
| 99 |
self.force_start_date = None
|
| 100 |
self.force_end_date = None
|
|
|
|
| 101 |
if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR)
|
| 102 |
|
| 103 |
def set_date_range(self, start_str, end_str):
|
|
|
|
| 109 |
return df[['timestamp', 'open', 'high', 'low', 'close', 'volume']].values.tolist()
|
| 110 |
|
| 111 |
# ==============================================================
|
| 112 |
+
# 🧱 Core Logic: Single Coin Processor (With % Progress)
|
| 113 |
# ==============================================================
|
| 114 |
async def _process_single_coin_task(self, sym, start_time_ms, end_time_ms, chunk_suffix="", analysis_start_ms=None, worker_id=0):
|
| 115 |
safe_sym = sym.replace('/', '_')
|
|
|
|
| 127 |
df_1m = None
|
| 128 |
frames = {}
|
| 129 |
|
| 130 |
+
# 1. تنزيل البيانات
|
| 131 |
try:
|
| 132 |
current_since = start_time_ms
|
|
|
|
| 133 |
|
| 134 |
while current_since < end_time_ms:
|
| 135 |
try:
|
|
|
|
| 136 |
batch = await self.dm.exchange.fetch_ohlcv(sym, '1m', since=current_since, limit=1000)
|
| 137 |
+
except Exception:
|
| 138 |
+
await asyncio.sleep(2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
continue
|
| 140 |
|
| 141 |
if not batch: break
|
|
|
|
| 145 |
|
| 146 |
all_candles_1m.extend(batch)
|
| 147 |
current_since = last_ts + 1
|
| 148 |
+
await asyncio.sleep(0.05)
|
|
|
|
|
|
|
|
|
|
| 149 |
if current_since >= end_time_ms: break
|
| 150 |
|
| 151 |
all_candles_1m = [c for c in all_candles_1m if c[0] <= end_time_ms]
|
| 152 |
|
| 153 |
if not all_candles_1m:
|
| 154 |
+
print(f" ⚠️ [Core {worker_id}] No data found.", flush=True)
|
| 155 |
return False
|
| 156 |
|
| 157 |
+
# print(f" ⚙️ [Core {worker_id}] Parsing {len(all_candles_1m)} candles...", flush=True)
|
| 158 |
|
|
|
|
| 159 |
df_1m = pd.DataFrame(all_candles_1m, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
|
| 160 |
cols = ['open', 'high', 'low', 'close', 'volume']
|
| 161 |
df_1m[cols] = df_1m[cols].astype('float32')
|
|
|
|
| 164 |
df_1m = df_1m.sort_index()
|
| 165 |
|
| 166 |
agg_dict = {'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum'}
|
| 167 |
+
frames['1m'] = df_1m.copy()
|
| 168 |
+
frames['1m']['timestamp'] = frames['1m'].index.astype(np.int64) // 10**6
|
|
|
|
| 169 |
|
| 170 |
for tf_str, tf_code in [('5m', '5T'), ('15m', '15T'), ('1h', '1h'), ('4h', '4h'), ('1d', '1D')]:
|
| 171 |
resampled = df_1m.resample(tf_code).agg(agg_dict).dropna()
|
|
|
|
| 177 |
analysis_start_dt = pd.to_datetime(analysis_start_ms, unit='ms')
|
| 178 |
valid_indices = frames['5m'].loc[analysis_start_dt:].index
|
| 179 |
|
|
|
|
| 180 |
total_steps = len(valid_indices)
|
| 181 |
step_count = 0
|
| 182 |
|
| 183 |
+
# حلقة المعالجة
|
| 184 |
for t_idx in valid_indices:
|
| 185 |
if t_idx.timestamp() * 1000 > end_time_ms: break
|
| 186 |
step_count += 1
|
| 187 |
|
| 188 |
+
# طباعة نسبة التقدم كل 10%
|
| 189 |
+
if total_steps > 0 and step_count % max(1, int(total_steps * 0.1)) == 0:
|
| 190 |
+
pct = int((step_count / total_steps) * 100)
|
| 191 |
+
print(f" 🧠 [Core {worker_id}] Progress: {pct}%", flush=True)
|
| 192 |
|
| 193 |
current_timestamp = int(t_idx.timestamp() * 1000)
|
| 194 |
ohlcv_data = {}
|
| 195 |
try:
|
| 196 |
+
# استخراج البيانات باستخدام loc (أسرع وأدق)
|
| 197 |
+
cutoff = t_idx
|
| 198 |
+
ohlcv_data['1m'] = self.df_to_list(frames['1m'].loc[:cutoff].tail(500))
|
| 199 |
+
ohlcv_data['5m'] = self.df_to_list(frames['5m'].loc[:cutoff].tail(200))
|
| 200 |
+
ohlcv_data['15m'] = self.df_to_list(frames['15m'].loc[:cutoff].tail(200))
|
| 201 |
+
ohlcv_data['1h'] = self.df_to_list(frames['1h'].loc[:cutoff].tail(200))
|
| 202 |
+
ohlcv_data['4h'] = self.df_to_list(frames['4h'].loc[:cutoff].tail(100))
|
| 203 |
+
ohlcv_data['1d'] = self.df_to_list(frames['1d'].loc[:cutoff].tail(50))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
except: continue
|
| 205 |
|
| 206 |
if len(ohlcv_data['1h']) < 60: continue
|
|
|
|
| 212 |
'ohlcv_15m': ohlcv_data['15m'][-60:],
|
| 213 |
'change_24h': 0.0
|
| 214 |
}
|
| 215 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
logic_result = self.dm._apply_logic_tree(logic_packet)
|
| 217 |
signal_type = logic_result.get('type', 'NONE')
|
| 218 |
l1_score = logic_result.get('score', 0.0)
|
|
|
|
| 237 |
dt = time.time() - t0
|
| 238 |
if ai_results:
|
| 239 |
pd.DataFrame(ai_results).to_pickle(scores_file)
|
| 240 |
+
print(f" 💾 [Core {worker_id}] Saved {len(ai_results)} signals. ({dt:.1f}s)", flush=True)
|
| 241 |
+
else:
|
| 242 |
+
print(f" ⚠️ [Core {worker_id}] No signals found.", flush=True)
|
| 243 |
|
| 244 |
return True
|
| 245 |
|
| 246 |
except Exception as e:
|
| 247 |
+
print(f" ❌ [Core {worker_id}] ERR: {e}", flush=True)
|
|
|
|
| 248 |
return False
|
| 249 |
|
| 250 |
finally:
|
|
|
|
| 254 |
gc.collect()
|
| 255 |
|
| 256 |
# ==============================================================
|
| 257 |
+
# PHASE 1: Main Loop (Restricted Concurrency)
|
| 258 |
# ==============================================================
|
| 259 |
async def generate_truth_data(self):
|
| 260 |
if self.force_start_date and self.force_end_date:
|
|
|
|
| 263 |
start_time_ms = int(dt_start.timestamp() * 1000)
|
| 264 |
end_time_ms = int(dt_end.timestamp() * 1000)
|
| 265 |
print(f"\n🚜 [Phase 1] Processing Era: {self.force_start_date} -> {self.force_end_date}")
|
| 266 |
+
print(f" 🚀 Turbo Mode: Safe Parallel Execution (Max 4 Cores)...")
|
| 267 |
else:
|
| 268 |
return
|
| 269 |
|
| 270 |
+
# ⚠️ تقييد عدد العمال لتجنب تجميد الجهاز بسبب نماذج الذكاء الاصطناعي
|
| 271 |
+
# 4 عمال هو حد آمن لمعظم الأجهزة
|
| 272 |
+
workers_count = 4
|
| 273 |
|
| 274 |
total_duration = end_time_ms - start_time_ms
|
| 275 |
chunk_size = total_duration // workers_count
|
|
|
|
| 309 |
df_part = pd.read_pickle(part_file)
|
| 310 |
if not df_part.empty: all_dfs.append(df_part)
|
| 311 |
os.remove(part_file)
|
| 312 |
+
except: pass
|
|
|
|
| 313 |
|
| 314 |
if all_dfs:
|
| 315 |
final_df = pd.concat(all_dfs).drop_duplicates(subset=['timestamp']).sort_values('timestamp')
|
|
|
|
| 317 |
print(f" 💾 [{sym}] FINAL SAVE: {len(final_df)} signals.")
|
| 318 |
else:
|
| 319 |
print(f" ⚠️ [{sym}] No signals generated.")
|
|
|
|
| 320 |
gc.collect()
|
| 321 |
|
| 322 |
# ==============================================================
|
| 323 |
+
# PHASE 2: Portfolio Digital Twin Engine (Unchanged)
|
| 324 |
# ==============================================================
|
| 325 |
@staticmethod
|
| 326 |
def _worker_optimize(combinations_batch, scores_files, initial_capital, fees_pct, max_slots):
|
|
|
|
| 343 |
for ts, group in grouped_by_time:
|
| 344 |
active_symbols = list(wallet["positions"].keys())
|
| 345 |
current_prices = {row['symbol']: row['close'] for _, row in group.iterrows()}
|
|
|
|
| 346 |
for sym in active_symbols:
|
| 347 |
if sym in current_prices:
|
| 348 |
curr_p = current_prices[sym]
|
|
|
|
| 357 |
wallet["balance"] += net_pnl
|
| 358 |
del wallet["positions"][sym]
|
| 359 |
wallet["trades_history"].append({'pnl': net_pnl})
|
| 360 |
+
|
| 361 |
current_total_equity = wallet["balance"] + wallet["allocated"]
|
| 362 |
if current_total_equity > peak_balance: peak_balance = current_total_equity
|
| 363 |
dd = (peak_balance - current_total_equity) / peak_balance
|
|
|
|
| 396 |
win_count = len([p for p in pnls if p > 0]); loss_count = len([p for p in pnls if p <= 0])
|
| 397 |
win_rate = (win_count / len(trades)) * 100
|
| 398 |
max_single_win = max(pnls) if pnls else 0.0; max_single_loss = min(pnls) if pnls else 0.0
|
|
|
|
| 399 |
current_win_streak = 0; max_win_streak = 0
|
| 400 |
current_loss_streak = 0; max_loss_streak = 0
|
| 401 |
for p in pnls:
|
|
|
|
| 405 |
else:
|
| 406 |
current_loss_streak += 1; current_win_streak = 0
|
| 407 |
if current_loss_streak > max_loss_streak: max_loss_streak = current_loss_streak
|
|
|
|
| 408 |
results.append({
|
| 409 |
'config': config, 'final_balance': wallet["balance"] + wallet["allocated"],
|
| 410 |
'net_profit': net_profit, 'total_trades': len(trades),
|
|
|
|
| 472 |
return best['config'], best
|
| 473 |
|
| 474 |
async def run_strategic_optimization_task():
|
| 475 |
+
print("\n🧪 [STRATEGIC BACKTEST] Time Lord Initiated (Stable Parallel)...")
|
| 476 |
r2 = R2Service()
|
| 477 |
dm = DataManager(None, None, r2)
|
| 478 |
proc = MLProcessor(dm)
|