Spaces:
Paused
Paused
Update ml_engine/data_manager.py
Browse files- ml_engine/data_manager.py +155 -220
ml_engine/data_manager.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# ============================================================
|
| 2 |
# 📂 ml_engine/data_manager.py
|
| 3 |
-
# (
|
| 4 |
# ============================================================
|
| 5 |
|
| 6 |
import asyncio
|
|
@@ -11,10 +11,11 @@ import pandas as pd
|
|
| 11 |
import numpy as np
|
| 12 |
import pandas_ta as ta
|
| 13 |
from typing import List, Dict, Any, Tuple
|
|
|
|
| 14 |
|
| 15 |
import ccxt.async_support as ccxt
|
| 16 |
|
| 17 |
-
# ✅ استيراد الدستور الديناميكي
|
| 18 |
try:
|
| 19 |
from ml_engine.processor import SystemLimits
|
| 20 |
except ImportError:
|
|
@@ -27,10 +28,10 @@ logging.getLogger("ccxt").setLevel(logging.WARNING)
|
|
| 27 |
|
| 28 |
class DataManager:
|
| 29 |
"""
|
| 30 |
-
DataManager
|
| 31 |
-
-
|
| 32 |
-
-
|
| 33 |
-
|
| 34 |
"""
|
| 35 |
|
| 36 |
def __init__(self, contracts_db, whale_monitor, r2_service=None):
|
|
@@ -50,13 +51,12 @@ class DataManager:
|
|
| 50 |
self.NETWORK_HEADS = ['ETH/USDT', 'SOL/USDT', 'BNB/USDT', 'AVAX/USDT']
|
| 51 |
self.BENCHMARK_SYMBOL = 'BTC/USDT'
|
| 52 |
|
| 53 |
-
# القائمة السوداء
|
| 54 |
self.BLACKLIST_TOKENS = [
|
| 55 |
'USDT', 'USDC', 'DAI', 'TUSD', 'BUSD', 'FDUSD', 'EUR', 'PAX',
|
| 56 |
'UP', 'DOWN', 'BEAR', 'BULL', '3S', '3L', 'USDD', 'USDP', 'HT', 'KCS'
|
| 57 |
]
|
| 58 |
|
| 59 |
-
print(f"📦 [DataManager
|
| 60 |
|
| 61 |
async def initialize(self):
|
| 62 |
print(" > [DataManager] Starting Matrix Initialization...")
|
|
@@ -89,9 +89,13 @@ class DataManager:
|
|
| 89 |
def get_contracts_db(self): return self.contracts_db
|
| 90 |
|
| 91 |
# ==================================================================
|
| 92 |
-
# 🧠 The
|
| 93 |
# ==================================================================
|
| 94 |
async def update_hyper_regime(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
print(" 🧠 [Matrix] Scanning Market Dimensions...")
|
| 96 |
try:
|
| 97 |
fg_index, fg_label = await self._fetch_fear_greed()
|
|
@@ -105,15 +109,14 @@ class DataManager:
|
|
| 105 |
if breadth_score >= 0.50: regime = "BULL"
|
| 106 |
else: regime = "RANGE"
|
| 107 |
elif btc_data['trend'] == 'BEAR':
|
| 108 |
-
if fg_index < 20: regime = "BEAR"
|
| 109 |
else: regime = "BEAR"
|
| 110 |
elif btc_data['trend'] == 'NEUTRAL':
|
| 111 |
if btc_data['volatility_state'] == 'LOW' and breadth_score < 0.3: regime = "DEAD"
|
| 112 |
else: regime = "RANGE"
|
| 113 |
|
| 114 |
SystemLimits.CURRENT_REGIME = regime
|
| 115 |
-
|
| 116 |
-
print(f" 🌍 Regime: {regime} | FG: {fg_index} | Breadth: {breadth_score*100:.0f}% | BTC: {btc_data['trend']}")
|
| 117 |
|
| 118 |
except Exception as e:
|
| 119 |
print(f"❌ [Matrix Error] {e}")
|
|
@@ -159,246 +162,178 @@ class DataManager:
|
|
| 159 |
return (bull_count / valid) if valid > 0 else 0.0, "|".join(details)
|
| 160 |
|
| 161 |
# ==================================================================
|
| 162 |
-
#
|
| 163 |
# ==================================================================
|
| 164 |
async def _stage0_universe_filter(self) -> List[Dict[str, Any]]:
|
| 165 |
"""
|
| 166 |
-
|
| 167 |
-
|
|
|
|
| 168 |
"""
|
| 169 |
try:
|
| 170 |
-
|
| 171 |
-
print(f" ⚡ [Flash-Pulse] Sorting Universe for {regime}...")
|
| 172 |
-
|
| 173 |
tickers = await self.exchange.fetch_tickers()
|
| 174 |
-
candidates = []
|
| 175 |
|
|
|
|
|
|
|
| 176 |
for symbol, ticker in tickers.items():
|
| 177 |
if not symbol.endswith('/USDT'): continue
|
| 178 |
if any(bad in symbol for bad in self.BLACKLIST_TOKENS): continue
|
| 179 |
|
| 180 |
-
#
|
| 181 |
-
last = ticker.get('last')
|
| 182 |
-
if not last or last < 0.0005: continue # Ignore penny dust
|
| 183 |
-
|
| 184 |
quote_vol = ticker.get('quoteVolume', 0)
|
| 185 |
-
if quote_vol < 1_000_000: continue
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
# 2. Advanced Metrics
|
| 194 |
-
change_24h = float(ticker.get('percentage', 0.0))
|
| 195 |
-
high_24h = ticker.get('high')
|
| 196 |
-
low_24h = ticker.get('low')
|
| 197 |
-
|
| 198 |
-
# Position in Daily Range (0.0 = Low, 1.0 = High)
|
| 199 |
-
range_pos = 0.5
|
| 200 |
-
if high_24h and low_24h and high_24h > low_24h:
|
| 201 |
-
range_pos = (last - low_24h) / (high_24h - low_24h)
|
| 202 |
-
|
| 203 |
-
# 3. Regime-Specific Scoring (The Magic)
|
| 204 |
-
sort_score = 0.0
|
| 205 |
-
|
| 206 |
-
if regime == "BULL":
|
| 207 |
-
# We want leaders: High Volume + Positive Change + Near Highs
|
| 208 |
-
# But not too extended (>30% is dangerous FOMO)
|
| 209 |
-
if 2.0 <= change_24h <= 25.0:
|
| 210 |
-
sort_score = quote_vol * range_pos # Liquidity + Strength
|
| 211 |
-
|
| 212 |
-
elif regime == "BEAR":
|
| 213 |
-
# We want Capitulation: High Volume + Negative Change + Near Lows
|
| 214 |
-
if change_24h < -5.0 and range_pos < 0.2:
|
| 215 |
-
# High volume on a dump = Panic Selling = Reversal Opportunity
|
| 216 |
-
sort_score = quote_vol * (1 - range_pos) * abs(change_24h)
|
| 217 |
-
|
| 218 |
-
elif regime == "DEAD":
|
| 219 |
-
# We want pure Liquidity + Stability (Squeeze Candidates)
|
| 220 |
-
if -3.0 < change_24h < 3.0:
|
| 221 |
-
sort_score = quote_vol # Just show me where the money is
|
| 222 |
-
|
| 223 |
-
else: # RANGE (Anti-FOMO)
|
| 224 |
-
# We want active coins but not pumped ones
|
| 225 |
-
if -8.0 < change_24h < 8.0:
|
| 226 |
-
sort_score = quote_vol
|
| 227 |
-
|
| 228 |
-
if sort_score > 0:
|
| 229 |
-
candidates.append({
|
| 230 |
-
'symbol': symbol,
|
| 231 |
-
'quote_volume': quote_vol,
|
| 232 |
-
'current_price': last,
|
| 233 |
-
'change_24h': change_24h,
|
| 234 |
-
'range_pos': range_pos,
|
| 235 |
-
'sort_score': sort_score
|
| 236 |
-
})
|
| 237 |
-
|
| 238 |
-
# Sort by the Regime-Specific Score
|
| 239 |
-
candidates.sort(key=lambda x: x['sort_score'], reverse=True)
|
| 240 |
|
| 241 |
-
#
|
| 242 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
except Exception as e:
|
| 245 |
-
print(f"❌ [
|
|
|
|
| 246 |
return []
|
| 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 |
-
item['type'] = classification['type']
|
| 275 |
-
filtered_list.append(item)
|
| 276 |
|
| 277 |
-
|
| 278 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
curr = df_1h.iloc[-1]
|
| 288 |
|
| 289 |
-
if
|
| 290 |
-
if self._get_change_4h(df_1h) > 20.0: return {'type': 'NONE'}
|
| 291 |
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
curr = df_1h.iloc[-1]
|
| 307 |
-
|
| 308 |
-
if self._get_change_4h(df_1h) > 4.0: return {'type': 'NONE'}
|
| 309 |
-
if curr['rsi'] < 32:
|
| 310 |
-
dist_ema = (curr['ema20'] - curr['close']) / curr['close']
|
| 311 |
-
if dist_ema > 0.04:
|
| 312 |
-
return {'type': 'BEAR_OVERSOLD', 'score': (32 - curr['rsi']) * 2}
|
| 313 |
-
except: pass
|
| 314 |
-
return {'type': 'NONE'}
|
| 315 |
|
| 316 |
# ==================================================================
|
| 317 |
-
#
|
| 318 |
# ==================================================================
|
| 319 |
-
def
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
df_15m = self._calc_indicators(data['ohlcv_15m'])
|
| 323 |
-
except: return {'type': 'NONE'}
|
| 324 |
-
if df_1h.empty or df_15m.empty: return {'type': 'NONE'}
|
| 325 |
-
|
| 326 |
-
curr_1h = df_1h.iloc[-1]; curr_15m = df_15m.iloc[-1]
|
| 327 |
-
change_4h = self._get_change_4h(df_1h)
|
| 328 |
-
|
| 329 |
-
# Strict Filters
|
| 330 |
-
if change_4h > 8.0 or data.get('change_24h', 0) > 12.0: return {'type': 'NONE'}
|
| 331 |
-
if curr_1h['rsi'] > 70: return {'type': 'NONE'}
|
| 332 |
|
| 333 |
-
#
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
if curr_15m['volume'] >= 1.5 * vol_ma20:
|
| 337 |
-
return {'type': 'RANGE_BREAKOUT', 'score': curr_15m['volume'] / vol_ma20}
|
| 338 |
|
| 339 |
-
|
| 340 |
-
if 20 <= curr_1h['rsi'] <= 40 and change_4h <= -2.0:
|
| 341 |
-
return {'type': 'RANGE_REVERSAL', 'score': (100 - curr_1h['rsi'])}
|
| 342 |
-
return {'type': 'NONE'}
|
| 343 |
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
return {'type': 'NONE'}
|
| 360 |
|
| 361 |
# ==================================================================
|
| 362 |
-
# 🏗️ Helpers
|
| 363 |
# ==================================================================
|
| 364 |
-
def _calc_indicators(self, ohlcv_list):
|
| 365 |
-
if not ohlcv_list: return pd.DataFrame()
|
| 366 |
-
df = pd.DataFrame(ohlcv_list, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
|
| 367 |
-
delta = df['close'].diff()
|
| 368 |
-
gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
|
| 369 |
-
loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
|
| 370 |
-
rs = gain / loss
|
| 371 |
-
df['rsi'] = 100 - (100 / (1 + rs))
|
| 372 |
-
df['ema20'] = df['close'].ewm(span=20, adjust=False).mean()
|
| 373 |
-
df['ema50'] = df['close'].ewm(span=50, adjust=False).mean()
|
| 374 |
-
df.fillna(0, inplace=True)
|
| 375 |
-
return df
|
| 376 |
-
|
| 377 |
-
def _get_change_4h(self, df_1h):
|
| 378 |
-
try:
|
| 379 |
-
if len(df_1h) >= 5:
|
| 380 |
-
return ((df_1h.iloc[-1]['close'] - df_1h.iloc[-5]['close']) / df_1h.iloc[-5]['close']) * 100
|
| 381 |
-
return 0.0
|
| 382 |
-
except: return 0.0
|
| 383 |
-
|
| 384 |
-
async def _fetch_technical_data_batch(self, candidates: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 385 |
-
chunk_size = 15
|
| 386 |
-
results = []
|
| 387 |
-
for i in range(0, len(candidates), chunk_size):
|
| 388 |
-
chunk = candidates[i:i + chunk_size]
|
| 389 |
-
results.extend([r for r in await asyncio.gather(*[self._fetch_single_tech_data(c) for c in chunk]) if r])
|
| 390 |
-
await asyncio.sleep(0.05)
|
| 391 |
-
return results
|
| 392 |
-
|
| 393 |
-
async def _fetch_single_tech_data(self, candidate: Dict[str, Any]) -> Any:
|
| 394 |
-
try:
|
| 395 |
-
h1 = await self.exchange.fetch_ohlcv(candidate['symbol'], '1h', limit=60)
|
| 396 |
-
m15 = await self.exchange.fetch_ohlcv(candidate['symbol'], '15m', limit=60)
|
| 397 |
-
if not h1 or not m15: return None
|
| 398 |
-
candidate['ohlcv_1h'] = h1; candidate['ohlcv_15m'] = m15
|
| 399 |
-
return candidate
|
| 400 |
-
except: return None
|
| 401 |
-
|
| 402 |
async def get_latest_price_async(self, symbol: str) -> float:
|
| 403 |
try: return float((await self.exchange.fetch_ticker(symbol))['last'])
|
| 404 |
except: return 0.0
|
|
|
|
| 1 |
# ============================================================
|
| 2 |
# 📂 ml_engine/data_manager.py
|
| 3 |
+
# (V49.0 - GEM-Architect: Structural Integrity Guard)
|
| 4 |
# ============================================================
|
| 5 |
|
| 6 |
import asyncio
|
|
|
|
| 11 |
import numpy as np
|
| 12 |
import pandas_ta as ta
|
| 13 |
from typing import List, Dict, Any, Tuple
|
| 14 |
+
from datetime import datetime
|
| 15 |
|
| 16 |
import ccxt.async_support as ccxt
|
| 17 |
|
| 18 |
+
# ✅ استيراد الدستور الديناميكي (لتحديث الحالة فقط)
|
| 19 |
try:
|
| 20 |
from ml_engine.processor import SystemLimits
|
| 21 |
except ImportError:
|
|
|
|
| 28 |
|
| 29 |
class DataManager:
|
| 30 |
"""
|
| 31 |
+
DataManager V49.0 (Structural Integrity Guard)
|
| 32 |
+
- Logic: PURE STRUCTURAL FILTERING. No Technical Analysis Logic here.
|
| 33 |
+
- Regime: Detects Regime ONLY to update SystemLimits (Thresholds).
|
| 34 |
+
- Filters: Spread, Depth, Age, Volume, Data Quality.
|
| 35 |
"""
|
| 36 |
|
| 37 |
def __init__(self, contracts_db, whale_monitor, r2_service=None):
|
|
|
|
| 51 |
self.NETWORK_HEADS = ['ETH/USDT', 'SOL/USDT', 'BNB/USDT', 'AVAX/USDT']
|
| 52 |
self.BENCHMARK_SYMBOL = 'BTC/USDT'
|
| 53 |
|
|
|
|
| 54 |
self.BLACKLIST_TOKENS = [
|
| 55 |
'USDT', 'USDC', 'DAI', 'TUSD', 'BUSD', 'FDUSD', 'EUR', 'PAX',
|
| 56 |
'UP', 'DOWN', 'BEAR', 'BULL', '3S', '3L', 'USDD', 'USDP', 'HT', 'KCS'
|
| 57 |
]
|
| 58 |
|
| 59 |
+
print(f"📦 [DataManager V49.0] Structural Integrity Engine Active.")
|
| 60 |
|
| 61 |
async def initialize(self):
|
| 62 |
print(" > [DataManager] Starting Matrix Initialization...")
|
|
|
|
| 89 |
def get_contracts_db(self): return self.contracts_db
|
| 90 |
|
| 91 |
# ==================================================================
|
| 92 |
+
# 🧠 The Matrix (Regime Sensor) - JUST FOR THRESHOLDS
|
| 93 |
# ==================================================================
|
| 94 |
async def update_hyper_regime(self):
|
| 95 |
+
"""
|
| 96 |
+
Updates SystemLimits.CURRENT_REGIME so the Processor knows which DNA to use.
|
| 97 |
+
Does NOT affect filtering logic in this file.
|
| 98 |
+
"""
|
| 99 |
print(" 🧠 [Matrix] Scanning Market Dimensions...")
|
| 100 |
try:
|
| 101 |
fg_index, fg_label = await self._fetch_fear_greed()
|
|
|
|
| 109 |
if breadth_score >= 0.50: regime = "BULL"
|
| 110 |
else: regime = "RANGE"
|
| 111 |
elif btc_data['trend'] == 'BEAR':
|
| 112 |
+
if fg_index < 20: regime = "BEAR"
|
| 113 |
else: regime = "BEAR"
|
| 114 |
elif btc_data['trend'] == 'NEUTRAL':
|
| 115 |
if btc_data['volatility_state'] == 'LOW' and breadth_score < 0.3: regime = "DEAD"
|
| 116 |
else: regime = "RANGE"
|
| 117 |
|
| 118 |
SystemLimits.CURRENT_REGIME = regime
|
| 119 |
+
print(f" 🌍 Regime Updated: {regime} (FG:{fg_index} | Breadth:{breadth_score*100:.0f}%)")
|
|
|
|
| 120 |
|
| 121 |
except Exception as e:
|
| 122 |
print(f"❌ [Matrix Error] {e}")
|
|
|
|
| 162 |
return (bull_count / valid) if valid > 0 else 0.0, "|".join(details)
|
| 163 |
|
| 164 |
# ==================================================================
|
| 165 |
+
# 🕵️ Stage 0: The Structural Guard (Heavy Inspection)
|
| 166 |
# ==================================================================
|
| 167 |
async def _stage0_universe_filter(self) -> List[Dict[str, Any]]:
|
| 168 |
"""
|
| 169 |
+
1. Fetch ALL Tickers.
|
| 170 |
+
2. Filter by Volume ($1M+) -> Top 150.
|
| 171 |
+
3. Deep Inspection on Top 150 (Spread, Depth, Age, Walls).
|
| 172 |
"""
|
| 173 |
try:
|
| 174 |
+
print(f" 🕵️ [Structural Guard] Scanning Universe...")
|
|
|
|
|
|
|
| 175 |
tickers = await self.exchange.fetch_tickers()
|
|
|
|
| 176 |
|
| 177 |
+
# --- Step 1: Initial Volume & Symbol Sweep ---
|
| 178 |
+
pre_candidates = []
|
| 179 |
for symbol, ticker in tickers.items():
|
| 180 |
if not symbol.endswith('/USDT'): continue
|
| 181 |
if any(bad in symbol for bad in self.BLACKLIST_TOKENS): continue
|
| 182 |
|
| 183 |
+
# 7. Volume Floor ($1M)
|
|
|
|
|
|
|
|
|
|
| 184 |
quote_vol = ticker.get('quoteVolume', 0)
|
| 185 |
+
if quote_vol < 1_000_000: continue
|
| 186 |
+
|
| 187 |
+
pre_candidates.append({
|
| 188 |
+
'symbol': symbol,
|
| 189 |
+
'quote_volume': quote_vol,
|
| 190 |
+
'ticker': ticker
|
| 191 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
+
# Sort by Volume Descending & Take Top 150
|
| 194 |
+
pre_candidates.sort(key=lambda x: x['quote_volume'], reverse=True)
|
| 195 |
+
top_150 = pre_candidates[:150]
|
| 196 |
+
print(f" -> Top 150 by Volume selected. inspecting structure...")
|
| 197 |
+
|
| 198 |
+
# --- Step 2: Deep Structural Inspection (Async Batch) ---
|
| 199 |
+
# We need to fetch OHLCV and OrderBook for these 150 to check spread/depth/age
|
| 200 |
+
final_candidates = []
|
| 201 |
|
| 202 |
+
chunk_size = 20
|
| 203 |
+
for i in range(0, len(top_150), chunk_size):
|
| 204 |
+
chunk = top_150[i:i+chunk_size]
|
| 205 |
+
inspected_chunk = await asyncio.gather(*[self._inspect_structure(c) for c in chunk])
|
| 206 |
+
final_candidates.extend([c for c in inspected_chunk if c is not None])
|
| 207 |
+
await asyncio.sleep(0.1) # Rate limit protection
|
| 208 |
+
|
| 209 |
+
print(f" -> [Structural Guard] {len(final_candidates)} candidates passed strict quality checks.")
|
| 210 |
+
return final_candidates
|
| 211 |
+
|
| 212 |
except Exception as e:
|
| 213 |
+
print(f"❌ [Filter Error] {e}")
|
| 214 |
+
traceback.print_exc()
|
| 215 |
return []
|
| 216 |
|
| 217 |
+
async def _inspect_structure(self, candidate: Dict[str, Any]) -> Any:
|
| 218 |
+
"""
|
| 219 |
+
Performs the heavy lifting: Spread, ATR, Depth, Age, Walls.
|
| 220 |
+
"""
|
| 221 |
+
symbol = candidate['symbol']
|
| 222 |
+
ticker = candidate['ticker']
|
| 223 |
+
try:
|
| 224 |
+
# Fetch Data Requirements
|
| 225 |
+
# We need 5m candles (for ATR) and Daily (for Age) and OrderBook (for Depth/Walls)
|
| 226 |
+
tasks = [
|
| 227 |
+
self.exchange.fetch_ohlcv(symbol, '5m', limit=50), # For ATR & Wicks
|
| 228 |
+
self.exchange.fetch_ohlcv(symbol, '1d', limit=200), # For Age
|
| 229 |
+
self.exchange.fetch_order_book(symbol, limit=50) # For Depth & Walls
|
| 230 |
+
]
|
| 231 |
+
ohlcv_5m, ohlcv_1d, orderbook = await asyncio.gather(*tasks)
|
| 232 |
+
|
| 233 |
+
if not ohlcv_5m or not ohlcv_1d or not orderbook: return None
|
| 234 |
+
|
| 235 |
+
# --- Check 4: Age (New Listings) ---
|
| 236 |
+
# استبعاد إذا عمر الإدراج < 7 أيام
|
| 237 |
+
if len(ohlcv_1d) < 7: return None
|
| 238 |
+
|
| 239 |
+
# --- Check 5: Data Integrity (Wicks/Gaps) ---
|
| 240 |
+
# استبعاد إذا شموع مشوهة
|
| 241 |
+
# Simple check: If any recent candle has High == Low (Zero volatility) or Volume == 0
|
| 242 |
+
for candle in ohlcv_5m[-10:]:
|
| 243 |
+
if candle[5] <= 0: return None # Zero Volume Gap
|
| 244 |
+
# Wick Integrity: High shouldn't be 20% higher than Open/Close on normal days
|
| 245 |
+
# (Skipped complex logic to keep it fast, relying on Volume/Spread mostly)
|
| 246 |
+
|
| 247 |
+
# --- Calc Basic Metrics ---
|
| 248 |
+
current_price = float(ticker['last'])
|
| 249 |
+
bid = float(orderbook['bids'][0][0]) if orderbook['bids'] else 0
|
| 250 |
+
ask = float(orderbook['asks'][0][0]) if orderbook['asks'] else 0
|
| 251 |
+
if bid == 0 or ask == 0: return None
|
| 252 |
+
|
| 253 |
+
# --- Check 1: Spread Analysis ---
|
| 254 |
+
spread_abs = (ask - bid) / bid
|
| 255 |
|
| 256 |
+
# استبعاد إذا Spread > 2.5%
|
| 257 |
+
if spread_abs > 0.025: return None
|
|
|
|
|
|
|
| 258 |
|
| 259 |
+
# Calc ATR(5m)
|
| 260 |
+
df_5m = pd.DataFrame(ohlcv_5m, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
|
| 261 |
+
# ATR Manual Calc for speed
|
| 262 |
+
h_l = df_5m['h'] - df_5m['l']
|
| 263 |
+
atr_val = h_l.rolling(14).mean().iloc[-1]
|
| 264 |
+
|
| 265 |
+
# أو إذا Spread > max(1.5%, 0.35 × ATR(5m))
|
| 266 |
+
atr_threshold = 0.35 * (atr_val / current_price) # Normalized ATR
|
| 267 |
+
dynamic_spread_limit = max(0.015, atr_threshold)
|
| 268 |
+
|
| 269 |
+
if spread_abs > dynamic_spread_limit: return None
|
| 270 |
|
| 271 |
+
# --- Check 3: Order Book Depth ---
|
| 272 |
+
# استبعاد إذا عمق الشراء داخل 0.5% أقل من 2,000$
|
| 273 |
+
min_depth_price = bid * 0.995
|
| 274 |
+
bid_depth_usd = 0.0
|
| 275 |
+
for price, vol in orderbook['bids']:
|
| 276 |
+
if price < min_depth_price: break
|
| 277 |
+
bid_depth_usd += (price * vol)
|
|
|
|
| 278 |
|
| 279 |
+
if bid_depth_usd < 2000: return None # Weak Support
|
|
|
|
| 280 |
|
| 281 |
+
# --- Check 6: Sell Walls (Future Obstacles) ---
|
| 282 |
+
# دفتر الطلبات للساعتين القادمتين فيه جدار بيعي قوي
|
| 283 |
+
# We approximate "2 hours" by looking at the immediate Ask Depth vs Bid Depth ratio
|
| 284 |
+
# If Ask Depth (Selling Pressure) is > 3x Bid Depth, it's a Wall.
|
| 285 |
+
|
| 286 |
+
max_wall_price = ask * 1.02 # Check 2% up
|
| 287 |
+
ask_depth_usd = 0.0
|
| 288 |
+
for price, vol in orderbook['asks']:
|
| 289 |
+
if price > max_wall_price: break
|
| 290 |
+
ask_depth_usd += (price * vol)
|
| 291 |
+
|
| 292 |
+
# Ratio Check: Is there a massive wall blocking price?
|
| 293 |
+
# Relaxed ratio to 5x to avoid false positives in volatile markets
|
| 294 |
+
if bid_depth_usd > 0 and (ask_depth_usd / bid_depth_usd) > 5.0:
|
| 295 |
+
return None
|
| 296 |
|
| 297 |
+
# ✅ PASSED ALL CHECKS
|
| 298 |
+
candidate['current_price'] = current_price
|
| 299 |
+
candidate['sort_score'] = candidate['quote_volume'] # Keep Vol as sort key
|
| 300 |
+
return candidate
|
| 301 |
+
|
| 302 |
+
except Exception:
|
| 303 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
# ==================================================================
|
| 306 |
+
# 🛡️ Layer 1: Structural Screening (No Pattern Filtering)
|
| 307 |
# ==================================================================
|
| 308 |
+
async def layer1_rapid_screening(self) -> List[Dict[str, Any]]:
|
| 309 |
+
# 1. Update Matrix (Just for thresholds)
|
| 310 |
+
await self.update_hyper_regime()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
|
| 312 |
+
# 2. Structural Filter (The 7 Pillars)
|
| 313 |
+
# This returns only Structurally Sound coins (Liquid, Old, Tight Spread)
|
| 314 |
+
candidates = await self._stage0_universe_filter()
|
|
|
|
|
|
|
| 315 |
|
| 316 |
+
if not candidates: return []
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
+
# 3. Pass to Layer 2 (Just formatting)
|
| 319 |
+
# We DO NOT apply any BULL/BEAR specific exclusion here.
|
| 320 |
+
# We just format them so the Processor can run the Models.
|
| 321 |
+
|
| 322 |
+
final_list = []
|
| 323 |
+
for c in candidates:
|
| 324 |
+
final_list.append({
|
| 325 |
+
'symbol': c['symbol'],
|
| 326 |
+
'quote_volume': c.get('quote_volume', 0),
|
| 327 |
+
'current_price': c.get('current_price', 0),
|
| 328 |
+
'type': 'CANDIDATE', # Generic Type
|
| 329 |
+
'l1_score': c.get('sort_score', 0)
|
| 330 |
+
})
|
| 331 |
+
|
| 332 |
+
return final_list
|
|
|
|
| 333 |
|
| 334 |
# ==================================================================
|
| 335 |
+
# 🏗️ Helpers (Standard)
|
| 336 |
# ==================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
async def get_latest_price_async(self, symbol: str) -> float:
|
| 338 |
try: return float((await self.exchange.fetch_ticker(symbol))['last'])
|
| 339 |
except: return 0.0
|