Spaces:
Paused
Paused
Update ml_engine/data_manager.py
Browse files1234564 unmodified lines111213141516171819206 unmodified lines2728293031323334353613 unmodified lines5051525354555657585960616226 unmodified lines8990919293949596977 unmodified lines10510610710810911011111211311411511611711811939 unmodified lines159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404# ============================================================# 📂 ml_engine/data_manager.py# (V47.5 - GEM-Architect: Flash-Pulse & Hyper-Matrix)# ============================================================import asyncio4 unmodified linesimport numpy as npimport pandas_ta as tafrom typing import List, Dict, Any, Tupleimport ccxt.async_support as ccxt# ✅ استيراد الدستور الديناميكيtry:from ml_engine.processor import SystemLimitsexcept ImportError:6 unmodified linesclass DataManager:"""DataManager V47.5 (Flash-Pulse Edition)- Hyper-Matrix Sensor: Detects BULL, BEAR, RANGE, DEAD.- Flash-Pulse Filter: Uses 24h Ticker Data (Change, Range Pos, Spread)to pre-sort candidates BEFORE fetching candles."""def __init__(self, contracts_db, whale_monitor, r2_service=None):13 unmodified linesself.NETWORK_HEADS = ['ETH/USDT', 'SOL/USDT', 'BNB/USDT', 'AVAX/USDT']self.BENCHMARK_SYMBOL = 'BTC/USDT'# القائمة السوداءself.BLACKLIST_TOKENS = ['USDT', 'USDC', 'DAI', 'TUSD', 'BUSD', 'FDUSD', 'EUR', 'PAX','UP', 'DOWN', 'BEAR', 'BULL', '3S', '3L', 'USDD', 'USDP', 'HT', 'KCS']print(f"📦 [DataManager V47.5] Flash-Pulse Engine Active.")async def initialize(self):print(" > [DataManager] Starting Matrix Initialization...")26 unmodified linesdef get_contracts_db(self): return self.contracts_db# ==================================================================# 🧠 The Hyper-Sensor (Matrix Logic)# ==================================================================async def update_hyper_regime(self):print(" 🧠 [Matrix] Scanning Market Dimensions...")try:fg_index, fg_label = await self._fetch_fear_greed()7 unmodified linesif breadth_score >= 0.50: regime = "BULL"else: regime = "RANGE"elif btc_data['trend'] == 'BEAR':if fg_index < 20: regime = "BEAR" # Capitulation Huntingelse: regime = "BEAR"elif btc_data['trend'] == 'NEUTRAL':if btc_data['volatility_state'] == 'LOW' and breadth_score < 0.3: regime = "DEAD"else: regime = "RANGE"SystemLimits.CURRENT_REGIME = regimeprint(f" 🌍 Regime: {regime} | FG: {fg_index} | Breadth: {breadth_score*100:.0f}% | BTC: {btc_data['trend']}")except Exception as e:print(f"❌ [Matrix Error] {e}")39 unmodified linesreturn (bull_count / valid) if valid > 0 else 0.0, "|".join(details)# ==================================================================# ⚡ Stage 0: The Flash-Pulse Filter (New & Improved)# ==================================================================async def _stage0_universe_filter(self) -> List[Dict[str, Any]]:"""Uses Ticker Snapshot (Percentage, High, Low, Volume, Spread)to filter candidates BEFORE fetching candles."""try:regime = SystemLimits.CURRENT_REGIMEprint(f" ⚡ [Flash-Pulse] Sorting Universe for {regime}...")tickers = await self.exchange.fetch_tickers()candidates = []for symbol, ticker in tickers.items():if not symbol.endswith('/USDT'): continueif any(bad in symbol for bad in self.BLACKLIST_TOKENS): continue# Basic Datalast = ticker.get('last')if not last or last < 0.0005: continue # Ignore penny dustquote_vol = ticker.get('quoteVolume', 0)if quote_vol < 1_000_000: continue # Liquidity Floor# 1. Spread Check (Quality Control)bid = ticker.get('bid'); ask = ticker.get('ask')if bid and ask and bid > 0:spread_pct = (ask - bid) / bidif spread_pct > 0.01: continue # Skip if spread > 1% (Illiquid/Risky)# 2. Advanced Metricschange_24h = float(ticker.get('percentage', 0.0))high_24h = ticker.get('high')low_24h = ticker.get('low')# Position in Daily Range (0.0 = Low, 1.0 = High)range_pos = 0.5if high_24h and low_24h and high_24h > low_24h:range_pos = (last - low_24h) / (high_24h - low_24h)# 3. Regime-Specific Scoring (The Magic)sort_score = 0.0if regime == "BULL":# We want leaders: High Volume + Positive Change + Near Highs# But not too extended (>30% is dangerous FOMO)if 2.0 <= change_24h <= 25.0:sort_score = quote_vol * range_pos # Liquidity + Strengthelif regime == "BEAR":# We want Capitulation: High Volume + Negative Change + Near Lowsif change_24h < -5.0 and range_pos < 0.2:# High volume on a dump = Panic Selling = Reversal Opportunitysort_score = quote_vol * (1 - range_pos) * abs(change_24h)elif regime == "DEAD":# We want pure Liquidity + Stability (Squeeze Candidates)if -3.0 < change_24h < 3.0:sort_score = quote_vol # Just show me where the money iselse: # RANGE (Anti-FOMO)# We want active coins but not pumped onesif -8.0 < change_24h < 8.0:sort_score = quote_volif sort_score > 0:candidates.append({'symbol': symbol,'quote_volume': quote_vol,'current_price': last,'change_24h': change_24h,'range_pos': range_pos,'sort_score': sort_score})# Sort by the Regime-Specific Scorecandidates.sort(key=lambda x: x['sort_score'], reverse=True)# Return top 300 for Deep Analysisreturn candidates[:300]except Exception as e:print(f"❌ [Flash-Pulse Error] {e}")return []# ==================================================================# 🛡️ Layer 1: Polymorphic Screening# ==================================================================async def layer1_rapid_screening(self) -> List[Dict[str, Any]]:# 1. Update Matrixawait self.update_hyper_regime()regime = SystemLimits.CURRENT_REGIME# 2. Flash-Pulse Filter (Smart Universe Selection)initial_candidates = await self._stage0_universe_filter()if not initial_candidates: return []# 3. Fetch Technicalsenriched_data = await self._fetch_technical_data_batch(initial_candidates)filtered_list = []# 4. Logic Switcherfor item in enriched_data:classification = {'type': 'NONE', 'score': 0.0}if regime == "BULL": classification = self._apply_bull_logic(item)elif regime == "BEAR": classification = self._apply_bear_logic(item)elif regime == "DEAD": classification = self._apply_dead_logic(item)else: classification = self._apply_range_logic(item)if classification['type'] != 'NONE':item['l1_score'] = classification['score']item['type'] = classification['type']filtered_list.append(item)filtered_list.sort(key=lambda x: x['l1_score'], reverse=True)return filtered_list[:40]# ==================================================================# 🐂 Logic: BULL# ==================================================================def _apply_bull_logic(self, data: Dict[str, Any]) -> Dict[str, Any]:try:df_1h = self._calc_indicators(data['ohlcv_1h'])if df_1h.empty: return {'type': 'NONE'}curr = df_1h.iloc[-1]if not (curr['close'] > curr['ema50']): return {'type': 'NONE'}if self._get_change_4h(df_1h) > 20.0: return {'type': 'NONE'}if 50 <= curr['rsi'] <= 80:vol_ma = df_1h['volume'].rolling(20).mean().iloc[-1]if curr['volume'] > vol_ma * 1.3:return {'type': 'BULL_MOMENTUM', 'score': curr['volume'] / vol_ma}except: passreturn {'type': 'NONE'}# ==================================================================# 🐻 Logic: BEAR# ==================================================================def _apply_bear_logic(self, data: Dict[str, Any]) -> Dict[str, Any]:try:df_1h = self._calc_indicators(data['ohlcv_1h'])if df_1h.empty: return {'type': 'NONE'}curr = df_1h.iloc[-1]if self._get_change_4h(df_1h) > 4.0: return {'type': 'NONE'}if curr['rsi'] < 32:dist_ema = (curr['ema20'] - curr['close']) / curr['close']if dist_ema > 0.04:return {'type': 'BEAR_OVERSOLD', 'score': (32 - curr['rsi']) * 2}except: passreturn {'type': 'NONE'}# ==================================================================# 🦀 Logic: RANGE# ==================================================================def _apply_range_logic(self, data: Dict[str, Any]) -> Dict[str, Any]:try:df_1h = self._calc_indicators(data['ohlcv_1h'])df_15m = self._calc_indicators(data['ohlcv_15m'])except: return {'type': 'NONE'}if df_1h.empty or df_15m.empty: return {'type': 'NONE'}curr_1h = df_1h.iloc[-1]; curr_15m = df_15m.iloc[-1]change_4h = self._get_change_4h(df_1h)# Strict Filtersif change_4h > 8.0 or data.get('change_24h', 0) > 12.0: return {'type': 'NONE'}if curr_1h['rsi'] > 70: return {'type': 'NONE'}# Breakoutif (curr_1h['ema20'] > curr_1h['ema50']) and 45 <= curr_1h['rsi'] <= 68:vol_ma20 = df_15m['volume'].rolling(20).mean().iloc[-1]if curr_15m['volume'] >= 1.5 * vol_ma20:return {'type': 'RANGE_BREAKOUT', 'score': curr_15m['volume'] / vol_ma20}# Reversalif 20 <= curr_1h['rsi'] <= 40 and change_4h <= -2.0:return {'type': 'RANGE_REVERSAL', 'score': (100 - curr_1h['rsi'])}return {'type': 'NONE'}# ==================================================================# 🧟 Logic: DEAD# ==================================================================def _apply_dead_logic(self, data: Dict[str, Any]) -> Dict[str, Any]:try:df_1h = self._calc_indicators(data['ohlcv_1h'])if df_1h.empty: return {'type': 'NONE'}curr = df_1h.iloc[-1]std = df_1h['close'].rolling(20).std().iloc[-1]bb_width = (std * 4) / curr['close']if bb_width < 0.04:vol_ma = df_1h['volume'].rolling(20).mean().iloc[-1]if curr['volume'] > vol_ma * 1.5:return {'type': 'DEAD_SQUEEZE', 'score': (1/bb_width)}except: passreturn {'type': 'NONE'}# ==================================================================# 🏗️ Helpers# ==================================================================def _calc_indicators(self, ohlcv_list):if not ohlcv_list: return pd.DataFrame()df = pd.DataFrame(ohlcv_list, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])delta = df['close'].diff()gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()rs = gain / lossdf['rsi'] = 100 - (100 / (1 + rs))df['ema20'] = df['close'].ewm(span=20, adjust=False).mean()df['ema50'] = df['close'].ewm(span=50, adjust=False).mean()df.fillna(0, inplace=True)return dfdef _get_change_4h(self, df_1h):try:if len(df_1h) >= 5:return ((df_1h.iloc[-1]['close'] - df_1h.iloc[-5]['close']) / df_1h.iloc[-5]['close']) * 100return 0.0except: return 0.0async def _fetch_technical_data_batch(self, candidates: List[Dict[str, Any]]) -> List[Dict[str, Any]]:chunk_size = 15results = []for i in range(0, len(candidates), chunk_size):chunk = candidates[i:i + chunk_size]results.extend([r for r in await asyncio.gather(*[self._fetch_single_tech_data(c) for c in chunk]) if r])await asyncio.sleep(0.05)return resultsasync def _fetch_single_tech_data(self, candidate: Dict[str, Any]) -> Any:try:h1 = await self.exchange.fetch_ohlcv(candidate['symbol'], '1h', limit=60)m15 = await self.exchange.fetch_ohlcv(candidate['symbol'], '15m', limit=60)if not h1 or not m15: return Nonecandidate['ohlcv_1h'] = h1; candidate['ohlcv_15m'] = m15return candidateexcept: return Noneasync def get_latest_price_async(self, symbol: str) -> float:try: return float((await self.exchange.fetch_ticker(symbol))['last'])except: return 0.01234564 unmodified lines11121314151617181920216 unmodified lines2829303132333435363713 unmodified lines51525354555657585960616226 unmodified lines89909192939495969798991001017 unmodified lines10911011111211311411511611711811912012112239 unmodified lines162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339# ============================================================# 📂 ml_engine/data_manager.py# (V49.0 - GEM-Architect: Structural Integrity Guard)# ============================================================import asyncio4 unmodified linesimport numpy as npimport pandas_ta as tafrom typing import List, Dict, Any, Tuplefrom datetime import datetimeimport ccxt.async_support as ccxt# ✅ استيراد الدستور الديناميكي (لتحديث الحالة فقط)try:from ml_engine.processor import SystemLimitsexcept ImportError:6 unmodified linesclass DataManager:"""DataManager V49.0 (Structural Integrity Guard)- Logic: PURE STRUCTURAL FILTERING. No Technical Analysis Logic here.- Regime: Detects Regime ONLY to update SystemLimits (Thresholds).- Filters: Spread, Depth, Age, Volume, Data Quality."""def __init__(self, contracts_db, whale_monitor, r2_service=None):13 unmodified linesself.NETWORK_HEADS = ['ETH/USDT', 'SOL/USDT', 'BNB/USDT', 'AVAX/USDT']self.BENCHMARK_SYMBOL = 'BTC/USDT'self.BLACKLIST_TOKENS = ['USDT', 'USDC', 'DAI', 'TUSD', 'BUSD', 'FDUSD', 'EUR', 'PAX','UP', 'DOWN', 'BEAR', 'BULL', '3S', '3L', 'USDD', 'USDP', 'HT', 'KCS']print(f"📦 [DataManager V49.0] Structural Integrity Engine Active.")async def initialize(self):print(" > [DataManager] Starting Matrix Initialization...")26 unmodified linesdef get_contracts_db(self): return self.contracts_db# ==================================================================# 🧠 The Matrix (Regime Sensor) - JUST FOR THRESHOLDS# ==================================================================async def update_hyper_regime(self):"""Updates SystemLimits.CURRENT_REGIME so the Processor knows which DNA to use.Does NOT affect filtering logic in this file."""print(" 🧠 [Matrix] Scanning Market Dimensions...")try:fg_index, fg_label = await self._fetch_fear_greed()7 unmodified linesif breadth_score >= 0.50: regime = "BULL"else: regime = "RANGE"elif btc_data['trend'] == 'BEAR':if fg_index < 20: regime = "BEAR"else: regime = "BEAR"elif btc_data['trend'] == 'NEUTRAL':if btc_data['volatility_state'] == 'LOW' and breadth_score < 0.3: regime = "DEAD"else: regime = "RANGE"SystemLimits.CURRENT_REGIME = regimeprint(f" 🌍 Regime Updated: {regime} (FG:{fg_index} | Breadth:{breadth_score*100:.0f}%)")except Exception as e:print(f"❌ [Matrix Error] {e}")39 unmodified linesreturn (bull_count / valid) if valid > 0 else 0.0, "|".join(details)# ==================================================================# 🕵️ Stage 0: The Structural Guard (Heavy Inspection)# ==================================================================async def _stage0_universe_filter(self) -> List[Dict[str, Any]]:"""1. Fetch ALL Tickers.2. Filter by Volume ($1M+) -> Top 150.3. Deep Inspection on Top 150 (Spread, Depth, Age, Walls)."""try:print(f" 🕵️ [Structural Guard] Scanning Universe...")tickers = await self.exchange.fetch_tickers()# --- Step 1: Initial Volume & Symbol Sweep ---pre_candidates = []for symbol, ticker in tickers.items():if not symbol.endswith('/USDT'): continueif any(bad in symbol for bad in self.BLACKLIST_TOKENS): continue# 7. Volume Floor ($1M)quote_vol = ticker.get('quoteVolume', 0)if quote_vol < 1_000_000: continuepre_candidates.append({'symbol': symbol,'quote_volume': quote_vol,'ticker': ticker})# Sort by Volume Descending & Take Top 150pre_candidates.sort(key=lambda x: x['quote_volume'], reverse=True)top_150 = pre_candidates[:150]print(f" -> Top 150 by Volume selected. inspecting structure...")# --- Step 2: Deep Structural Inspection (Async Batch) ---# We need to fetch OHLCV and OrderBook for these 150 to check spread/depth/agefinal_candidates = []chunk_size = 20for i in range(0, len(top_150), chunk_size):chunk = top_150[i:i+chunk_size]inspected_chunk = await asyncio.gather(*[self._inspect_structure(c) for c in chunk])final_candidates.extend([c for c in inspected_chunk if c is not None])await asyncio.sleep(0.1) # Rate limit protectionprint(f" -> [Structural Guard] {len(final_candidates)} candidates passed strict quality checks.")return final_candidatesexcept Exception as e:print(f"❌ [Filter Error] {e}")traceback.print_exc()return []async def _inspect_structure(self, candidate: Dict[str, Any]) -> Any:"""Performs the heavy lifting: Spread, ATR, Depth, Age, Walls."""symbol = candidate['symbol']ticker = candidate['ticker']try:# Fetch Data Requirements# We need 5m candles (for ATR) and Daily (for Age) and OrderBook (for Depth/Walls)tasks = [self.exchange.fetch_ohlcv(symbol, '5m', limit=50), # For ATR & Wicksself.exchange.fetch_ohlcv(symbol, '1d', limit=200), # For Ageself.exchange.fetch_order_book(symbol, limit=50) # For Depth & Walls]ohlcv_5m, ohlcv_1d, orderbook = await asyncio.gather(*tasks)if not ohlcv_5m or not ohlcv_1d or not orderbook: return None# --- Check 4: Age (New Listings) ---# استبعاد إذا عمر الإدراج < 7 أيامif len(ohlcv_1d) < 7: return None# --- Check 5: Data Integrity (Wicks/Gaps) ---# استبعاد إذا شموع مشوهة# Simple check: If any recent candle has High == Low (Zero volatility) or Volume == 0for candle in ohlcv_5m[-10:]:if candle[5] <= 0: return None # Zero Volume Gap# Wick Integrity: High shouldn't be 20% higher than Open/Close on normal days# (Skipped complex logic to keep it fast, relying on Volume/Spread mostly)# --- Calc Basic Metrics ---current_price = float(ticker['last'])bid = float(orderbook['bids'][0][0]) if orderbook['bids'] else 0ask = float(orderbook['asks'][0][0]) if orderbook['asks'] else 0if bid == 0 or ask == 0: return None# --- Check 1: Spread Analysis ---spread_abs = (ask - bid) / bid# استبعاد إذا Spread > 2.5%if spread_abs > 0.025: return None# Calc ATR(5m)df_5m = pd.DataFrame(ohlcv_5m, columns=['ts', 'o', 'h', 'l', 'c', 'v'])# ATR Manual Calc for speedh_l = df_5m['h'] - df_5m['l']atr_val = h_l.rolling(14).mean().iloc[-1]# أو إذا Spread > max(1.5%, 0.35 × ATR(5m))atr_threshold = 0.35 * (atr_val / current_price) # Normalized ATRdynamic_spread_limit = max(0.015, atr_threshold)if spread_abs > dynamic_spread_limit: return None# --- Check 3: Order Book Depth ---# استبعاد إذا عمق الشراء داخل 0.5% أقل من 2,000$min_depth_price = bid * 0.995bid_depth_usd = 0.0for price, vol in orderbook['bids']:if price < min_depth_price: breakbid_depth_usd += (price * vol)if bid_depth_usd < 2000: return None # Weak Support# --- Check 6: Sell Walls (Future Obstacles) ---# دفتر الطلبات للساعتين القادمتين فيه جدار بيعي قوي# We approximate "2 hours" by looking at the immediate Ask Depth vs Bid Depth ratio# If Ask Depth (Selling Pressure) is > 3x Bid Depth, it's a Wall.max_wall_price = ask * 1.02 # Check 2% upask_depth_usd = 0.0for price, vol in orderbook['asks']:if price > max_wall_price: breakask_depth_usd += (price * vol)# Ratio Check: Is there a massive wall blocking price?# Relaxed ratio to 5x to avoid false positives in volatile marketsif bid_depth_usd > 0 and (ask_depth_usd / bid_depth_usd) > 5.0:return None# ✅ PASSED ALL CHECKScandidate['current_price'] = current_pricecandidate['sort_score'] = candidate['quote_volume'] # Keep Vol as sort keyreturn candidateexcept Exception:return None# ==================================================================# 🛡️ Layer 1: Structural Screening (No Pattern Filtering)# ==================================================================async def layer1_rapid_screening(self) -> List[Dict[str, Any]]:# 1. Update Matrix (Just for thresholds)await self.update_hyper_regime()# 2. Structural Filter (The 7 Pillars)# This returns only Structurally Sound coins (Liquid, Old, Tight Spread)candidates = await self._stage0_universe_filter()if not candidates: return []# 3. Pass to Layer 2 (Just formatting)# We DO NOT apply any BULL/BEAR specific exclusion here.# We just format them so the Processor can run the Models.final_list = []for c in candidates:final_list.append({'symbol': c['symbol'],'quote_volume': c.get('quote_volume', 0),'current_price': c.get('current_price', 0),'type': 'CANDIDATE', # Generic Type'l1_score': c.get('sort_score', 0)})return final_list# ==================================================================# 🏗️ Helpers (Standard)# ==================================================================async def get_latest_price_async(self, symbol: str) -> float:try: return float((await self.exchange.fetch_ticker(symbol))['last'])except: return 0.0
ml_engine/data_manager.py+155-220