Riy777 commited on
Commit
d0a22d2
·
verified ·
1 Parent(s): 761ffad

Update backtest_engine.py

Browse files
Files changed (1) hide show
  1. backtest_engine.py +230 -230
backtest_engine.py CHANGED
@@ -1,5 +1,5 @@
1
  # ============================================================
2
- # 🧪 backtest_engine.py (V114.0 - GEM-Architect: Global Inference Velocity)
3
  # ============================================================
4
 
5
  import asyncio
@@ -55,7 +55,7 @@ class HeavyDutyBacktester:
55
  self.force_end_date = None
56
 
57
  if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR)
58
- print(f"🧪 [Backtest V114.0] Global Inference Architecture (Max Speed).")
59
 
60
  def set_date_range(self, start_str, end_str):
61
  self.force_start_date = start_str
@@ -67,25 +67,24 @@ class HeavyDutyBacktester:
67
  async def _fetch_all_data_fast(self, sym, start_ms, end_ms):
68
  print(f" ⚡ [Network] Downloading {sym}...", flush=True)
69
  limit = 1000
70
- # Reduce delay slightly for speed
71
  tasks = []
72
  current = start_ms
73
- duration_per_batch = limit * 60 * 1000
74
  while current < end_ms:
75
  tasks.append(current)
76
  current += duration_per_batch
77
  all_candles = []
78
- sem = asyncio.Semaphore(15) # Increased concurrency
79
 
80
  async def _fetch_batch(timestamp):
81
  async with sem:
82
  for _ in range(3):
83
  try:
84
  return await self.dm.exchange.fetch_ohlcv(sym, '1m', since=timestamp, limit=limit)
85
- except: await asyncio.sleep(0.5)
86
  return []
87
 
88
- chunk_size = 25
89
  for i in range(0, len(tasks), chunk_size):
90
  chunk_tasks = tasks[i:i + chunk_size]
91
  futures = [_fetch_batch(ts) for ts in chunk_tasks]
@@ -94,30 +93,31 @@ class HeavyDutyBacktester:
94
  if res: all_candles.extend(res)
95
 
96
  if not all_candles: return None
97
- # Fast Dedupe
98
- df = pd.DataFrame(all_candles, columns=['timestamp', 'o', 'h', 'l', 'c', 'v'])
99
- df.drop_duplicates('timestamp', inplace=True)
100
- df = df[(df['timestamp'] >= start_ms) & (df['timestamp'] <= end_ms)]
101
- df.sort_values('timestamp', inplace=True)
102
-
103
- print(f" ✅ Downloaded {len(df)} candles.", flush=True)
104
- return df.values.tolist()
 
105
 
106
  # ==============================================================
107
- # 🏎️ VECTORIZED INDICATORS (ALL LAYERS)
108
  # ==============================================================
109
  def _calculate_indicators_vectorized(self, df, timeframe='1m'):
110
- # Optimize types
111
- cols = ['close', 'high', 'low', 'volume', 'open']
112
- for c in cols: df[c] = df[c].astype(np.float32)
 
 
113
 
114
- # Standard
115
  df['rsi'] = ta.rsi(df['close'], length=14)
116
  df['ema20'] = ta.ema(df['close'], length=20)
117
  df['ema50'] = ta.ema(df['close'], length=50)
118
  df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)
119
 
120
- # Hydra
121
  if timeframe == '1m':
122
  sma20 = df['close'].rolling(20).mean()
123
  std20 = df['close'].rolling(20).std()
@@ -125,43 +125,37 @@ class HeavyDutyBacktester:
125
  df['vol_ma50'] = df['volume'].rolling(50).mean()
126
  df['rel_vol'] = df['volume'] / (df['vol_ma50'] + 1e-9)
127
 
128
- # Oracle
129
  df['slope'] = ta.slope(df['close'], length=7)
130
  vol_mean = df['volume'].rolling(20).mean()
131
  vol_std = df['volume'].rolling(20).std()
132
  df['vol_z'] = (df['volume'] - vol_mean) / (vol_std + 1e-9)
133
  df['atr_pct'] = df['atr'] / df['close']
134
 
135
- # Sniper (1m)
136
  if timeframe == '1m':
137
  df['ret'] = df['close'].pct_change()
138
  df['dollar_vol'] = df['close'] * df['volume']
139
  df['amihud'] = (df['ret'].abs() / df['dollar_vol'].replace(0, np.nan)).fillna(0)
140
-
141
  dp = df['close'].diff()
142
  roll_cov = dp.rolling(64).cov(dp.shift(1))
143
  df['roll_spread'] = (2 * np.sqrt(np.maximum(0, -roll_cov))).fillna(0)
144
-
145
  sign = np.sign(df['close'].diff()).fillna(0)
146
  df['signed_vol'] = sign * df['volume']
147
  df['ofi'] = df['signed_vol'].rolling(30).sum().fillna(0)
148
-
149
  buy_vol = (sign > 0) * df['volume']
150
  sell_vol = (sign < 0) * df['volume']
151
  imb = (buy_vol.rolling(60).sum() - sell_vol.rolling(60).sum()).abs()
152
  tot = df['volume'].rolling(60).sum()
153
  df['vpin'] = (imb / tot.replace(0, np.nan)).fillna(0)
154
-
155
  vwap = (df['close'] * df['volume']).rolling(20).sum() / df['volume'].rolling(20).sum()
156
  df['vwap_dev'] = (df['close'] - vwap).fillna(0)
157
-
158
  df['rv_gk'] = (np.log(df['high'] / df['low'])**2) / 2 - (2 * np.log(2) - 1) * (np.log(df['close'] / df['open'])**2)
159
-
 
 
160
  r = df['volume'].rolling(500).mean()
161
  s = df['volume'].rolling(500).std()
162
  df['vol_zscore_50'] = ((df['volume'] - r) / s).fillna(0)
163
 
164
- # Legacy
165
  df['log_ret'] = np.log(df['close'] / df['close'].shift(1))
166
  roll_max = df['high'].rolling(50).max()
167
  roll_min = df['low'].rolling(50).min()
@@ -175,19 +169,19 @@ class HeavyDutyBacktester:
175
  df['ema200'] = ta.ema(df['close'], length=200)
176
  df['dist_ema200'] = (df['close'] - df['ema200']) / df['close']
177
 
178
- # Pre-calc Lags for Legacy V2
179
  if timeframe == '1m':
180
  for lag in [1, 2, 3, 5, 10, 20]:
181
- df[f'log_ret_lag_{lag}'] = df['log_ret'].shift(lag)
182
- df[f'rsi_lag_{lag}'] = df['rsi'].shift(lag) / 100.0
183
- df[f'fib_pos_lag_{lag}'] = df['fib_pos'].shift(lag)
184
- df[f'volatility_lag_{lag}'] = df['volatility'].shift(lag)
185
 
186
  df.fillna(0, inplace=True)
187
  return df
188
 
189
  # ==============================================================
190
- # 🧠 CPU PROCESSING (GLOBAL INFERENCE)
191
  # ==============================================================
192
  async def _process_data_in_memory(self, sym, candles, start_ms, end_ms):
193
  safe_sym = sym.replace('/', '_')
@@ -198,7 +192,7 @@ class HeavyDutyBacktester:
198
  print(f" 📂 [{sym}] Data Exists -> Skipping.")
199
  return
200
 
201
- print(f" ⚙️ [CPU] Analyzing {sym} (Global Inference)...", flush=True)
202
  t0 = time.time()
203
 
204
  df_1m = pd.DataFrame(candles, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
@@ -209,11 +203,12 @@ class HeavyDutyBacktester:
209
  frames = {}
210
  agg_dict = {'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum'}
211
 
212
- # 1. Vectorized Calculation (1m)
213
  frames['1m'] = self._calculate_indicators_vectorized(df_1m.copy(), timeframe='1m')
214
  frames['1m']['timestamp'] = frames['1m'].index.floor('1min').astype(np.int64) // 10**6
 
215
 
216
- # 2. Vectorized Calculation (HTF)
217
  numpy_htf = {}
218
  for tf_str, tf_code in [('5m', '5T'), ('15m', '15T'), ('1h', '1h'), ('4h', '4h'), ('1d', '1D')]:
219
  resampled = df_1m.resample(tf_code).agg(agg_dict).dropna()
@@ -222,243 +217,250 @@ class HeavyDutyBacktester:
222
  frames[tf_str] = resampled
223
  numpy_htf[tf_str] = {col: resampled[col].values for col in resampled.columns}
224
 
225
- # 3. GLOBAL MAPPING (Pre-map indices for the whole array)
226
- fast_1m = {col: frames['1m'][col].values for col in frames['1m'].columns}
227
- arr_ts_1m = fast_1m['timestamp']
228
-
229
- # Using searchsorted once for the entire array is extremely fast
230
- map_5m = np.searchsorted(numpy_htf['5m']['timestamp'], arr_ts_1m)
231
- map_15m = np.searchsorted(numpy_htf['15m']['timestamp'], arr_ts_1m)
232
- map_1h = np.searchsorted(numpy_htf['1h']['timestamp'], arr_ts_1m)
233
- map_4h = np.searchsorted(numpy_htf['4h']['timestamp'], arr_ts_1m)
234
 
235
  # Clip
236
- map_5m = np.clip(map_5m, 0, len(numpy_htf['5m']['timestamp']) - 1)
237
- map_15m = np.clip(map_15m, 0, len(numpy_htf['15m']['timestamp']) - 1)
238
- map_1h = np.clip(map_1h, 0, len(numpy_htf['1h']['timestamp']) - 1)
239
- map_4h = np.clip(map_4h, 0, len(numpy_htf['4h']['timestamp']) - 1)
240
-
241
- # 4. LOAD MODELS
242
- legacy_v2 = getattr(self.proc.guardian_legacy, 'model_v2', None)
243
- oracle_model = getattr(self.proc.oracle, 'model_direction', None)
244
- oracle_cols = getattr(self.proc.oracle, 'feature_cols', [])
245
- sniper_models = getattr(self.proc.sniper, 'models', [])
246
- sniper_cols = getattr(self.proc.sniper, 'feature_names', [])
247
 
 
 
 
 
 
248
  hydra_models = getattr(self.proc.guardian_hydra, 'models', {}) if self.proc.guardian_hydra else {}
249
  hydra_cols = getattr(self.proc.guardian_hydra, 'feature_cols', []) if self.proc.guardian_hydra else []
250
-
251
- # ======================================================================
252
- # 🔥 GLOBAL INFERENCE: Run Models on ALL data at once (No Loop) 🔥
253
- # ======================================================================
 
254
 
255
- # A. Global Legacy V2
256
- global_v2_scores = np.zeros(len(arr_ts_1m), dtype=np.float32)
257
  if legacy_v2:
258
- print(" 🚀 Running Global Legacy V2...", flush=True)
259
  try:
260
- # Construct Matrix
261
  l_log = fast_1m['log_ret']
262
  l_rsi = fast_1m['rsi'] / 100.0
263
  l_fib = fast_1m['fib_pos']
264
  l_vol = fast_1m['volatility']
265
 
266
- l5_log = numpy_htf['5m']['log_ret'][map_5m]
267
- l5_rsi = numpy_htf['5m']['rsi'][map_5m] / 100.0
268
- l5_fib = numpy_htf['5m']['fib_pos'][map_5m]
269
- l5_trd = numpy_htf['5m']['trend_slope'][map_5m]
 
270
 
271
- l15_log = numpy_htf['15m']['log_ret'][map_15m]
272
- l15_rsi = numpy_htf['15m']['rsi'][map_15m] / 100.0
273
- l15_fib618 = numpy_htf['15m']['dist_fib618'][map_15m]
274
- l15_trd = numpy_htf['15m']['trend_slope'][map_15m]
275
 
276
- lags = []
 
277
  for lag in [1, 2, 3, 5, 10, 20]:
278
- lags.extend([fast_1m[f'log_ret_lag_{lag}'], fast_1m[f'rsi_lag_{lag}'],
279
- fast_1m[f'fib_pos_lag_{lag}'], fast_1m[f'volatility_lag_{lag}']])
 
 
 
 
 
 
 
 
 
 
280
 
281
- X_V2 = np.column_stack([l_log, l_rsi, l_fib, l_vol, l5_log, l5_rsi, l5_fib, l5_trd,
282
- l15_log, l15_rsi, l15_fib618, l15_trd, *lags])
 
 
283
 
284
- # Predict All
285
- preds = legacy_v2.predict(xgb.DMatrix(X_V2))
286
- global_v2_scores = preds[:, 2] if len(preds.shape) > 1 else preds
287
  except Exception as e: print(f"V2 Error: {e}")
288
 
289
- # B. Global Oracle
290
- global_oracle_scores = np.full(len(arr_ts_1m), 0.5, dtype=np.float32)
291
- if oracle_model and oracle_cols:
292
- print(" 🚀 Running Global Oracle...", flush=True)
293
- try:
294
- # Build Oracle Matrix
295
- # This is tricky because mapping is by column name.
296
- # We assume consistent ordering or build list.
297
- vecs = []
298
- for col in oracle_cols:
299
- if col.startswith('1h_'): vecs.append(numpy_htf['1h'].get(col[3:], np.zeros(len(arr_ts_1m)))[map_1h])
300
- elif col.startswith('15m_'): vecs.append(numpy_htf['15m'].get(col[4:], np.zeros(len(arr_ts_1m)))[map_15m])
301
- elif col.startswith('4h_'): vecs.append(numpy_htf['4h'].get(col[3:], np.zeros(len(arr_ts_1m)))[map_4h])
302
- elif col == 'sim_titan_score': vecs.append(np.full(len(arr_ts_1m), 0.6))
303
- else: vecs.append(np.full(len(arr_ts_1m), 0.5))
304
-
305
- X_ORACLE = np.column_stack(vecs)
306
- preds_o = oracle_model.predict(X_ORACLE)
307
- # Ensure output format
308
- global_oracle_scores = preds_o if isinstance(preds_o, np.ndarray) and len(preds_o.shape)==1 else preds_o[:, 0]
309
- # Adjust short prob if needed logic: here assuming long confidence
310
- except Exception as e: print(f"Oracle Error: {e}")
311
-
312
- # C. Global Sniper
313
- global_sniper_scores = np.full(len(arr_ts_1m), 0.5, dtype=np.float32)
314
- if sniper_models:
315
- print(" 🚀 Running Global Sniper...", flush=True)
316
  try:
317
- vecs_s = []
318
- for col in sniper_cols:
319
- if col in fast_1m: vecs_s.append(fast_1m[col])
320
- elif col == 'L_score': vecs_s.append(fast_1m.get('vol_zscore_50', np.zeros(len(arr_ts_1m))))
321
- else: vecs_s.append(np.zeros(len(arr_ts_1m)))
 
 
 
322
 
323
- X_SNIPER = np.column_stack(vecs_s)
324
- # Average of folds
325
- preds_list = [m.predict(X_SNIPER) for m in sniper_models]
326
- global_sniper_scores = np.mean(preds_list, axis=0)
327
- except Exception as e: print(f"Sniper Error: {e}")
328
-
329
- # --- 5. L1 FILTER (Fast) ---
330
- # Map 1h RSI to 1m resolution for filtering
331
- rsi_1h_mapped = numpy_htf['1h']['rsi'][map_1h]
332
- # Valid: RSI < 70
333
- is_candidate = (rsi_1h_mapped <= 70)
334
-
335
- # We need to find "Start of signal" indices.
336
- # Simple logic: Every index is potentially a signal start if it passes L1.
337
- # To avoid spamming signals every minute, we can debounce or just take them all (HeavyDutyBacktester usually takes all)
338
-
339
- # Limit processing to valid candidates
340
- candidate_indices = np.where(is_candidate)[0]
341
-
342
- # Start date filter
343
- start_ts_val = frames['1m'].index[0] + pd.Timedelta(minutes=500)
344
- start_idx_offset = np.searchsorted(arr_ts_1m, int(start_ts_val.timestamp()*1000))
345
- candidate_indices = candidate_indices[candidate_indices >= start_idx_offset]
346
 
347
- # Limit end index to allow for 4h simulation
348
- max_idx = len(arr_ts_1m) - 245
349
- candidate_indices = candidate_indices[candidate_indices < max_idx]
350
 
351
- print(f" 🎯 Candidates: {len(candidate_indices)}. Simulating Trades...", flush=True)
 
 
 
352
 
353
- # --- 6. SIMULATION LOOP (Lightweight) ---
354
- # Now the loop only needs to:
355
- # 1. Lookup Oracle/Sniper/Titan scores (Instant)
356
- # 2. Calculate Hydra (Dynamic PnL) - Simplified vectorization per trade
357
- # 3. Lookup Legacy (Instant)
358
-
359
  ai_results = []
360
 
361
- # Pre-allocate for Hydra batching inside loop
362
- # We can optimize Hydra further: The static features are already global.
363
- # Only PnL changes per trade entry.
364
-
365
- if hydra_models:
366
- # Prepare Global Static Matrix for Hydra
367
- # [rsi1, rsi5, rsi15, bb, vol, atr, close]
368
- h_static = np.column_stack([
369
- fast_1m['rsi'], numpy_htf['5m']['rsi'][map_5m], numpy_htf['15m']['rsi'][map_15m],
370
- fast_1m['bb_width'], fast_1m['rel_vol'], fast_1m['atr'], fast_1m['close']
371
- ])
372
-
373
- # Iterate candidates
374
- for idx_entry in candidate_indices:
375
-
376
- entry_price = fast_1m['close'][idx_entry]
377
- entry_ts = int(arr_ts_1m[idx_entry])
378
 
379
- # Scores Lookup
380
- s_oracle = global_oracle_scores[idx_entry]
381
- s_sniper = global_sniper_scores[idx_entry]
382
- s_titan = 0.6 # Placeholder
383
 
384
- # Future Window (4h)
385
- idx_exit = idx_entry + 240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
 
387
- # Legacy Risk (Max in window)
388
- # Instant slice max
389
- max_v2 = np.max(global_v2_scores[idx_entry:idx_exit])
390
- # Time of panic?
391
- panic_rel_idx = np.argmax(global_v2_scores[idx_entry:idx_exit])
392
- v2_time = 0
393
- if max_v2 > 0.8: v2_time = int(arr_ts_1m[idx_entry + panic_rel_idx])
394
-
395
- # Hydra Risk (Dynamic)
396
- max_hydra = 0.0; hydra_time = 0
397
- if hydra_models:
398
- # Slice Static
399
- sl_st = h_static[idx_entry:idx_exit] # (240, 7)
400
- sl_close = sl_st[:, 6]
401
- sl_atr = sl_st[:, 5]
 
 
 
 
 
 
 
 
402
 
403
- # Dynamic Calcs (Vectorized for 240 steps)
404
- dist = np.maximum(1.5 * sl_atr, entry_price * 0.015)
405
- pnl = sl_close - entry_price
406
- norm_pnl = pnl / dist
407
- # Cumulative max for Giveback
408
- cum_max = np.maximum.accumulate(sl_close)
409
- max_pnl_r = (np.maximum(cum_max, entry_price) - entry_price) / dist
410
- atr_pct = sl_atr / sl_close
411
- time_vec = np.arange(1, 241)
412
 
413
- # Stack Hydra Matrix (240, 15)
414
- # Map columns manually
415
- # rsi1(0), rsi5(1), rsi15(2), bb(3), vol(4), ema(0), atr_pct, norm, max, dists(0), time, entry(0), oracle, l2(0.7), target(3)
416
 
417
- # Constants
 
 
 
 
 
 
 
 
418
  zeros = np.zeros(240)
419
- const_oracle = np.full(240, s_oracle)
420
- const_l2 = np.full(240, 0.7)
421
- const_tgt = np.full(240, 3.0)
422
 
423
- X_H = np.column_stack([
424
- sl_st[:,0], sl_st[:,1], sl_st[:,2], sl_st[:,3], sl_st[:,4],
425
- zeros, atr_pct, norm_pnl, max_pnl_r,
426
- zeros, zeros, time_vec, zeros,
427
- const_oracle, const_l2, const_tgt
 
 
 
428
  ])
429
 
430
  try:
431
- # Fast Prediction (240 rows is tiny for XGB)
432
- probs = hydra_models['crash'].predict_proba(X_H)[:, 1]
433
- max_hydra = np.max(probs)
434
- if max_hydra > 0.6:
435
- t_idx = np.argmax(probs)
436
- hydra_time = int(arr_ts_1m[idx_entry + t_idx])
437
  except: pass
438
 
439
  ai_results.append({
440
- 'timestamp': entry_ts, 'symbol': sym, 'close': entry_price,
441
- 'real_titan': s_titan,
442
- 'oracle_conf': s_oracle,
443
- 'sniper_score': s_sniper,
444
- 'risk_hydra_crash': max_hydra,
445
- 'time_hydra_crash': hydra_time,
446
- 'risk_legacy_v2': max_v2,
447
- 'time_legacy_panic': v2_time,
448
- 'signal_type': 'BREAKOUT', # Simplified
449
  'l1_score': 50.0
450
  })
451
-
452
  dt = time.time() - t0
453
  if ai_results:
454
  pd.DataFrame(ai_results).to_pickle(scores_file)
455
- print(f" ✅ [{sym}] Completed in {dt:.2f} seconds. ({len(ai_results)} signals)", flush=True)
456
  else:
457
- print(f" ⚠️ [{sym}] No signals. Time: {dt:.2f}s", flush=True)
458
 
459
- del frames, fast_1m, numpy_htf, global_v2_scores, global_oracle_scores, global_sniper_scores
460
  gc.collect()
461
 
 
 
 
462
  async def generate_truth_data(self):
463
  if self.force_start_date and self.force_end_date:
464
  dt_start = datetime.strptime(self.force_start_date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
@@ -498,7 +500,6 @@ class HeavyDutyBacktester:
498
  for ts, group in grouped_by_time:
499
  active = list(wallet["positions"].keys())
500
  current_prices = {row['symbol']: row['close'] for _, row in group.iterrows()}
501
-
502
  for sym in active:
503
  if sym in current_prices:
504
  curr = current_prices[sym]
@@ -523,6 +524,7 @@ class HeavyDutyBacktester:
523
  if row['symbol'] in wallet['positions']: continue
524
  if row['oracle_conf'] < oracle_thresh: continue
525
  if row['sniper_score'] < sniper_thresh: continue
 
526
  size = 10.0
527
  if wallet['balance'] >= size:
528
  wallet['positions'][row['symbol']] = {
@@ -563,11 +565,9 @@ class HeavyDutyBacktester:
563
 
564
  async def run_optimization(self, target_regime="RANGE"):
565
  await self.generate_truth_data()
566
-
567
  oracle_range = [0.5, 0.6, 0.7]
568
  sniper_range = [0.4, 0.5, 0.6]
569
  hydra_range = [0.75, 0.85, 0.95]
570
-
571
  combinations = []
572
  for o, s, h in itertools.product(oracle_range, sniper_range, hydra_range):
573
  combinations.append({
@@ -630,7 +630,7 @@ async def run_strategic_optimization_task():
630
  best_cfg, best_stats = await optimizer.run_optimization(target_regime=target)
631
  if best_cfg:
632
  hub.submit_challenger(target, best_cfg, best_stats)
633
-
634
  await hub._save_state_to_r2()
635
  print("✅ [System] ALL Strategic DNA Updated & Saved.")
636
 
 
1
  # ============================================================
2
+ # 🧪 backtest_engine.py (V113.0 - GEM-Architect: Global Pre-Inference)
3
  # ============================================================
4
 
5
  import asyncio
 
55
  self.force_end_date = None
56
 
57
  if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR)
58
+ print(f"🧪 [Backtest V113.0] Pre-Inference Velocity Mode (Target: 60s).")
59
 
60
  def set_date_range(self, start_str, end_str):
61
  self.force_start_date = start_str
 
67
  async def _fetch_all_data_fast(self, sym, start_ms, end_ms):
68
  print(f" ⚡ [Network] Downloading {sym}...", flush=True)
69
  limit = 1000
70
+ duration_per_batch = limit * 60 * 1000
71
  tasks = []
72
  current = start_ms
 
73
  while current < end_ms:
74
  tasks.append(current)
75
  current += duration_per_batch
76
  all_candles = []
77
+ sem = asyncio.Semaphore(10)
78
 
79
  async def _fetch_batch(timestamp):
80
  async with sem:
81
  for _ in range(3):
82
  try:
83
  return await self.dm.exchange.fetch_ohlcv(sym, '1m', since=timestamp, limit=limit)
84
+ except: await asyncio.sleep(1)
85
  return []
86
 
87
+ chunk_size = 20
88
  for i in range(0, len(tasks), chunk_size):
89
  chunk_tasks = tasks[i:i + chunk_size]
90
  futures = [_fetch_batch(ts) for ts in chunk_tasks]
 
93
  if res: all_candles.extend(res)
94
 
95
  if not all_candles: return None
96
+ filtered = [c for c in all_candles if c[0] >= start_ms and c[0] <= end_ms]
97
+ seen = set(); unique_candles = []
98
+ for c in filtered:
99
+ if c[0] not in seen:
100
+ unique_candles.append(c)
101
+ seen.add(c[0])
102
+ unique_candles.sort(key=lambda x: x[0])
103
+ print(f" ✅ Downloaded {len(unique_candles)} candles.", flush=True)
104
+ return unique_candles
105
 
106
  # ==============================================================
107
+ # 🏎️ VECTORIZED INDICATORS
108
  # ==============================================================
109
  def _calculate_indicators_vectorized(self, df, timeframe='1m'):
110
+ df['close'] = df['close'].astype(float)
111
+ df['high'] = df['high'].astype(float)
112
+ df['low'] = df['low'].astype(float)
113
+ df['volume'] = df['volume'].astype(float)
114
+ df['open'] = df['open'].astype(float)
115
 
 
116
  df['rsi'] = ta.rsi(df['close'], length=14)
117
  df['ema20'] = ta.ema(df['close'], length=20)
118
  df['ema50'] = ta.ema(df['close'], length=50)
119
  df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)
120
 
 
121
  if timeframe == '1m':
122
  sma20 = df['close'].rolling(20).mean()
123
  std20 = df['close'].rolling(20).std()
 
125
  df['vol_ma50'] = df['volume'].rolling(50).mean()
126
  df['rel_vol'] = df['volume'] / (df['vol_ma50'] + 1e-9)
127
 
 
128
  df['slope'] = ta.slope(df['close'], length=7)
129
  vol_mean = df['volume'].rolling(20).mean()
130
  vol_std = df['volume'].rolling(20).std()
131
  df['vol_z'] = (df['volume'] - vol_mean) / (vol_std + 1e-9)
132
  df['atr_pct'] = df['atr'] / df['close']
133
 
 
134
  if timeframe == '1m':
135
  df['ret'] = df['close'].pct_change()
136
  df['dollar_vol'] = df['close'] * df['volume']
137
  df['amihud'] = (df['ret'].abs() / df['dollar_vol'].replace(0, np.nan)).fillna(0)
 
138
  dp = df['close'].diff()
139
  roll_cov = dp.rolling(64).cov(dp.shift(1))
140
  df['roll_spread'] = (2 * np.sqrt(np.maximum(0, -roll_cov))).fillna(0)
 
141
  sign = np.sign(df['close'].diff()).fillna(0)
142
  df['signed_vol'] = sign * df['volume']
143
  df['ofi'] = df['signed_vol'].rolling(30).sum().fillna(0)
 
144
  buy_vol = (sign > 0) * df['volume']
145
  sell_vol = (sign < 0) * df['volume']
146
  imb = (buy_vol.rolling(60).sum() - sell_vol.rolling(60).sum()).abs()
147
  tot = df['volume'].rolling(60).sum()
148
  df['vpin'] = (imb / tot.replace(0, np.nan)).fillna(0)
 
149
  vwap = (df['close'] * df['volume']).rolling(20).sum() / df['volume'].rolling(20).sum()
150
  df['vwap_dev'] = (df['close'] - vwap).fillna(0)
 
151
  df['rv_gk'] = (np.log(df['high'] / df['low'])**2) / 2 - (2 * np.log(2) - 1) * (np.log(df['close'] / df['open'])**2)
152
+ df['return_1m'] = df['ret']
153
+ df['return_5m'] = df['close'].pct_change(5)
154
+ df['return_15m'] = df['close'].pct_change(15)
155
  r = df['volume'].rolling(500).mean()
156
  s = df['volume'].rolling(500).std()
157
  df['vol_zscore_50'] = ((df['volume'] - r) / s).fillna(0)
158
 
 
159
  df['log_ret'] = np.log(df['close'] / df['close'].shift(1))
160
  roll_max = df['high'].rolling(50).max()
161
  roll_min = df['low'].rolling(50).min()
 
169
  df['ema200'] = ta.ema(df['close'], length=200)
170
  df['dist_ema200'] = (df['close'] - df['ema200']) / df['close']
171
 
172
+ # Lags for V2
173
  if timeframe == '1m':
174
  for lag in [1, 2, 3, 5, 10, 20]:
175
+ df[f'log_ret_lag_{lag}'] = df['log_ret'].shift(lag).fillna(0)
176
+ df[f'rsi_lag_{lag}'] = (df['rsi'].shift(lag).fillna(50) / 100.0)
177
+ df[f'fib_pos_lag_{lag}'] = df['fib_pos'].shift(lag).fillna(0.5)
178
+ df[f'volatility_lag_{lag}'] = df['volatility'].shift(lag).fillna(0)
179
 
180
  df.fillna(0, inplace=True)
181
  return df
182
 
183
  # ==============================================================
184
+ # 🧠 CPU PROCESSING (PRE-INFERENCE OPTIMIZED)
185
  # ==============================================================
186
  async def _process_data_in_memory(self, sym, candles, start_ms, end_ms):
187
  safe_sym = sym.replace('/', '_')
 
192
  print(f" 📂 [{sym}] Data Exists -> Skipping.")
193
  return
194
 
195
+ print(f" ⚙️ [CPU] Analyzing {sym} (Global Pre-Inference)...", flush=True)
196
  t0 = time.time()
197
 
198
  df_1m = pd.DataFrame(candles, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
 
203
  frames = {}
204
  agg_dict = {'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum'}
205
 
206
+ # 1. Calc 1m
207
  frames['1m'] = self._calculate_indicators_vectorized(df_1m.copy(), timeframe='1m')
208
  frames['1m']['timestamp'] = frames['1m'].index.floor('1min').astype(np.int64) // 10**6
209
+ fast_1m = {col: frames['1m'][col].values for col in frames['1m'].columns}
210
 
211
+ # 2. Calc HTF
212
  numpy_htf = {}
213
  for tf_str, tf_code in [('5m', '5T'), ('15m', '15T'), ('1h', '1h'), ('4h', '4h'), ('1d', '1D')]:
214
  resampled = df_1m.resample(tf_code).agg(agg_dict).dropna()
 
217
  frames[tf_str] = resampled
218
  numpy_htf[tf_str] = {col: resampled[col].values for col in resampled.columns}
219
 
220
+ # 3. Global Index Maps
221
+ map_1m_to_1h = np.searchsorted(numpy_htf['1h']['timestamp'], fast_1m['timestamp'])
222
+ map_1m_to_5m = np.searchsorted(numpy_htf['5m']['timestamp'], fast_1m['timestamp'])
223
+ map_1m_to_15m = np.searchsorted(numpy_htf['15m']['timestamp'], fast_1m['timestamp'])
 
 
 
 
 
224
 
225
  # Clip
226
+ max_idx_1h = len(numpy_htf['1h']['timestamp']) - 1
227
+ max_idx_5m = len(numpy_htf['5m']['timestamp']) - 1
228
+ max_idx_15m = len(numpy_htf['15m']['timestamp']) - 1
 
 
 
 
 
 
 
 
229
 
230
+ map_1m_to_1h = np.clip(map_1m_to_1h, 0, max_idx_1h)
231
+ map_1m_to_5m = np.clip(map_1m_to_5m, 0, max_idx_5m)
232
+ map_1m_to_15m = np.clip(map_1m_to_15m, 0, max_idx_15m)
233
+
234
+ # 4. Load Models
235
  hydra_models = getattr(self.proc.guardian_hydra, 'models', {}) if self.proc.guardian_hydra else {}
236
  hydra_cols = getattr(self.proc.guardian_hydra, 'feature_cols', []) if self.proc.guardian_hydra else []
237
+ legacy_v2 = getattr(self.proc.guardian_legacy, 'model_v2', None)
238
+
239
+ # 5. 🔥 PRE-CALCULATE LEGACY V2 (GLOBAL) 🔥
240
+ # V2 depends only on structure, not entry price. We can predict for ALL rows at once.
241
+ global_v2_probs = np.zeros(len(fast_1m['close']))
242
 
 
 
243
  if legacy_v2:
244
+ print(f" 🚀 Pre-calculating Legacy V2 for entire history...", flush=True)
245
  try:
246
+ # 1m Feats
247
  l_log = fast_1m['log_ret']
248
  l_rsi = fast_1m['rsi'] / 100.0
249
  l_fib = fast_1m['fib_pos']
250
  l_vol = fast_1m['volatility']
251
 
252
+ # HTF Feats Mapped to 1m
253
+ l5_log = numpy_htf['5m']['log_ret'][map_1m_to_5m]
254
+ l5_rsi = numpy_htf['5m']['rsi'][map_1m_to_5m] / 100.0
255
+ l5_fib = numpy_htf['5m']['fib_pos'][map_1m_to_5m]
256
+ l5_trd = numpy_htf['5m']['trend_slope'][map_1m_to_5m]
257
 
258
+ l15_log = numpy_htf['15m']['log_ret'][map_1m_to_15m]
259
+ l15_rsi = numpy_htf['15m']['rsi'][map_1m_to_15m] / 100.0
260
+ l15_fib618 = numpy_htf['15m']['dist_fib618'][map_1m_to_15m]
261
+ l15_trd = numpy_htf['15m']['trend_slope'][map_1m_to_15m]
262
 
263
+ # Lags
264
+ lag_cols = []
265
  for lag in [1, 2, 3, 5, 10, 20]:
266
+ lag_cols.append(fast_1m[f'log_ret_lag_{lag}'])
267
+ lag_cols.append(fast_1m[f'rsi_lag_{lag}'])
268
+ lag_cols.append(fast_1m[f'fib_pos_lag_{lag}'])
269
+ lag_cols.append(fast_1m[f'volatility_lag_{lag}'])
270
+
271
+ # Huge Matrix
272
+ X_GLOBAL_V2 = np.column_stack([
273
+ l_log, l_rsi, l_fib, l_vol,
274
+ l5_log, l5_rsi, l5_fib, l5_trd,
275
+ l15_log, l15_rsi, l15_fib618, l15_trd,
276
+ *lag_cols
277
+ ])
278
 
279
+ # Predict All in One Go
280
+ dm_glob = xgb.DMatrix(X_GLOBAL_V2)
281
+ preds_glob = legacy_v2.predict(dm_glob)
282
+ global_v2_probs = preds_glob[:, 2] if len(preds_glob.shape) > 1 else preds_glob
283
 
 
 
 
284
  except Exception as e: print(f"V2 Error: {e}")
285
 
286
+ # 6. 🔥 PRE-ASSEMBLE HYDRA STATIC (GLOBAL) 🔥
287
+ # Hydra needs PnL (dynamic), but 90% features are static.
288
+ global_hydra_static = None
289
+ if hydra_models:
290
+ print(f" 🚀 Pre-assembling Hydra features...", flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  try:
292
+ # Map columns that don't depend on PnL
293
+ h_rsi_1m = fast_1m['rsi']
294
+ h_rsi_5m = numpy_htf['5m']['rsi'][map_1m_to_5m]
295
+ h_rsi_15m = numpy_htf['15m']['rsi'][map_1m_to_15m]
296
+ h_bb = fast_1m['bb_width']
297
+ h_vol = fast_1m['rel_vol']
298
+ h_atr = fast_1m['atr']
299
+ h_close = fast_1m['close']
300
 
301
+ # We store these separate to combine inside loop efficiently
302
+ # [rsi1, rsi5, rsi15, bb, vol, atr, close]
303
+ global_hydra_static = np.column_stack([h_rsi_1m, h_rsi_5m, h_rsi_15m, h_bb, h_vol, h_atr, h_close])
304
+ except: pass
305
+
306
+ # 7. Candidate Filtering
307
+ df_1h = frames['1h'].reindex(frames['5m'].index, method='ffill')
308
+ df_5m = frames['5m'].copy()
309
+ is_valid = (df_1h['rsi'] <= 70)
310
+ valid_indices = df_5m[is_valid].index
311
+ start_dt = df_1m.index[0] + pd.Timedelta(minutes=500)
312
+ final_valid_indices = [t for t in valid_indices if t >= start_dt]
 
 
 
 
 
 
 
 
 
 
 
313
 
314
+ total_signals = len(final_valid_indices)
315
+ print(f" 🎯 Candidates: {total_signals}. Running Models...", flush=True)
 
316
 
317
+ oracle_dir_model = getattr(self.proc.oracle, 'model_direction', None)
318
+ oracle_cols = getattr(self.proc.oracle, 'feature_cols', [])
319
+ sniper_models = getattr(self.proc.sniper, 'models', [])
320
+ sniper_cols = getattr(self.proc.sniper, 'feature_names', [])
321
 
 
 
 
 
 
 
322
  ai_results = []
323
 
324
+ # Pre-allocate Hydra time vector (0 to 240)
325
+ time_vec = np.arange(1, 241)
326
+
327
+ # --- MAIN LOOP (Optimized Lookups) ---
328
+ for i, current_time in enumerate(final_valid_indices):
329
+ ts_val = int(current_time.timestamp() * 1000)
330
+ idx_1m = np.searchsorted(fast_1m['timestamp'], ts_val)
 
 
 
 
 
 
 
 
 
 
331
 
332
+ if idx_1m < 500 or idx_1m >= len(fast_1m['close']) - 245: continue
 
 
 
333
 
334
+ idx_1h = map_1m_to_1h[idx_1m]
335
+ idx_15m = map_1m_to_15m[idx_1m]
336
+ idx_4h = np.searchsorted(numpy_htf['4h']['timestamp'], ts_val)
337
+ if idx_4h >= len(numpy_htf['4h']['close']): idx_4h = len(numpy_htf['4h']['close']) - 1
338
+
339
+ # === Oracle (Single Call) ===
340
+ oracle_conf = 0.5
341
+ if oracle_dir_model:
342
+ o_vec = []
343
+ for col in oracle_cols:
344
+ val = 0.0
345
+ if col.startswith('1h_'): val = numpy_htf['1h'].get(col[3:], [0])[idx_1h]
346
+ elif col.startswith('15m_'): val = numpy_htf['15m'].get(col[4:], [0])[idx_15m]
347
+ elif col.startswith('4h_'): val = numpy_htf['4h'].get(col[3:], [0])[idx_4h]
348
+ elif col == 'sim_titan_score': val = 0.6
349
+ elif col == 'sim_mc_score': val = 0.5
350
+ elif col == 'sim_pattern_score': val = 0.5
351
+ o_vec.append(val)
352
+ try:
353
+ o_pred = oracle_dir_model.predict(np.array(o_vec).reshape(1, -1))[0]
354
+ oracle_conf = float(o_pred[0]) if isinstance(o_pred, (list, np.ndarray)) else float(o_pred)
355
+ if oracle_conf < 0.5: oracle_conf = 1 - oracle_conf
356
+ except: pass
357
+
358
+ # === Sniper (Single Call) ===
359
+ sniper_score = 0.5
360
+ if sniper_models:
361
+ s_vec = []
362
+ for col in sniper_cols:
363
+ if col in fast_1m: s_vec.append(fast_1m[col][idx_1m])
364
+ elif col == 'L_score': s_vec.append(fast_1m.get('vol_zscore_50', [0])[idx_1m])
365
+ else: s_vec.append(0.0)
366
+ try:
367
+ s_preds = [m.predict(np.array(s_vec).reshape(1, -1))[0] for m in sniper_models]
368
+ sniper_score = np.mean(s_preds)
369
+ except: pass
370
+
371
+ # === RISK SIMULATION (ULTRA FAST) ===
372
+ start_idx = idx_1m + 1
373
+ end_idx = start_idx + 240
374
 
375
+ # 1. LEGACY V2 (Instant Lookup)
376
+ max_legacy_v2 = 0.0; legacy_panic_time = 0
377
+ if legacy_v2:
378
+ # Just slice the pre-calculated array!
379
+ probs_slice = global_v2_probs[start_idx:end_idx]
380
+ max_legacy_v2 = np.max(probs_slice)
381
+ panic_indices = np.where(probs_slice > 0.8)[0]
382
+ if len(panic_indices) > 0:
383
+ legacy_panic_time = int(fast_1m['timestamp'][start_idx + panic_indices[0]])
384
+
385
+ # 2. HYDRA (Semi-Vectorized)
386
+ max_hydra_crash = 0.0; hydra_crash_time = 0
387
+ if hydra_models and global_hydra_static is not None:
388
+ # Slice Static Feats
389
+ sl_static = global_hydra_static[start_idx:end_idx] # [rsi1, rsi5, rsi15, bb, vol, atr, close]
390
+
391
+ entry_price = fast_1m['close'][idx_1m]
392
+ sl_close = sl_static[:, 6]
393
+ sl_atr = sl_static[:, 5]
394
+
395
+ # Calc Dynamic Feats
396
+ sl_dist = 1.5 * sl_atr
397
+ sl_dist = np.where(sl_dist > 0, sl_dist, entry_price * 0.015)
398
 
399
+ sl_pnl = sl_close - entry_price
400
+ sl_norm_pnl = sl_pnl / sl_dist
 
 
 
 
 
 
 
401
 
402
+ sl_cum_max = np.maximum.accumulate(sl_close)
403
+ sl_cum_max = np.maximum(sl_cum_max, entry_price)
404
+ sl_max_pnl_r = (sl_cum_max - entry_price) / sl_dist
405
 
406
+ sl_atr_pct = sl_atr / sl_close
407
+
408
+ # Map to Hydra Cols Order (Hardcoded for max speed)
409
+ # Cols: rsi_1m, rsi_5m, rsi_15m, bb_width, rel_vol, dist_ema20_1h, atr_pct, norm_pnl_r, max_pnl_r, dists..., time, entry, oracle, l2, target
410
+
411
+ # Re-assemble only what is needed
412
+ # (Static 0-4) + (Zeros) + (Dynamic) + (Constants)
413
+
414
+ # Create arrays for constants
415
  zeros = np.zeros(240)
416
+ oracle_arr = np.full(240, oracle_conf)
417
+ l2_arr = np.full(240, 0.7)
418
+ target_arr = np.full(240, 3.0)
419
 
420
+ X_hydra = np.column_stack([
421
+ sl_static[:, 0], sl_static[:, 1], sl_static[:, 2], # RSIs
422
+ sl_static[:, 3], sl_static[:, 4], # BB, Vol
423
+ zeros, # dist_ema
424
+ sl_atr_pct, sl_norm_pnl, sl_max_pnl_r,
425
+ zeros, zeros, # dists
426
+ time_vec, # time
427
+ zeros, oracle_arr, l2_arr, target_arr
428
  ])
429
 
430
  try:
431
+ probs_crash = hydra_models['crash'].predict_proba(X_hydra)[:, 1]
432
+ max_hydra_crash = np.max(probs_crash)
433
+ crash_indices = np.where(probs_crash > 0.6)[0]
434
+ if len(crash_indices) > 0:
435
+ hydra_crash_time = int(fast_1m['timestamp'][start_idx + crash_indices[0]])
 
436
  except: pass
437
 
438
  ai_results.append({
439
+ 'timestamp': ts_val, 'symbol': sym, 'close': entry_price,
440
+ 'real_titan': 0.6,
441
+ 'oracle_conf': oracle_conf,
442
+ 'sniper_score': sniper_score,
443
+ 'risk_hydra_crash': max_hydra_crash,
444
+ 'time_hydra_crash': hydra_crash_time,
445
+ 'risk_legacy_v2': max_legacy_v2,
446
+ 'time_legacy_panic': legacy_panic_time,
447
+ 'signal_type': 'BREAKOUT',
448
  'l1_score': 50.0
449
  })
450
+
451
  dt = time.time() - t0
452
  if ai_results:
453
  pd.DataFrame(ai_results).to_pickle(scores_file)
454
+ print(f" ✅ [{sym}] Completed {len(ai_results)} signals in {dt:.2f} seconds.", flush=True)
455
  else:
456
+ print(f" ⚠️ [{sym}] No valid signals. Time: {dt:.2f}s", flush=True)
457
 
458
+ del frames, fast_1m, numpy_htf, global_v2_probs, global_hydra_static
459
  gc.collect()
460
 
461
+ # ==============================================================
462
+ # PHASE 1 & 2 (Unchanged - Standard Optimization Logic)
463
+ # ==============================================================
464
  async def generate_truth_data(self):
465
  if self.force_start_date and self.force_end_date:
466
  dt_start = datetime.strptime(self.force_start_date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
 
500
  for ts, group in grouped_by_time:
501
  active = list(wallet["positions"].keys())
502
  current_prices = {row['symbol']: row['close'] for _, row in group.iterrows()}
 
503
  for sym in active:
504
  if sym in current_prices:
505
  curr = current_prices[sym]
 
524
  if row['symbol'] in wallet['positions']: continue
525
  if row['oracle_conf'] < oracle_thresh: continue
526
  if row['sniper_score'] < sniper_thresh: continue
527
+
528
  size = 10.0
529
  if wallet['balance'] >= size:
530
  wallet['positions'][row['symbol']] = {
 
565
 
566
  async def run_optimization(self, target_regime="RANGE"):
567
  await self.generate_truth_data()
 
568
  oracle_range = [0.5, 0.6, 0.7]
569
  sniper_range = [0.4, 0.5, 0.6]
570
  hydra_range = [0.75, 0.85, 0.95]
 
571
  combinations = []
572
  for o, s, h in itertools.product(oracle_range, sniper_range, hydra_range):
573
  combinations.append({
 
630
  best_cfg, best_stats = await optimizer.run_optimization(target_regime=target)
631
  if best_cfg:
632
  hub.submit_challenger(target, best_cfg, best_stats)
633
+
634
  await hub._save_state_to_r2()
635
  print("✅ [System] ALL Strategic DNA Updated & Saved.")
636