Riy777 commited on
Commit
60bded8
ยท
verified ยท
1 Parent(s): ac0cc30

Update ml_engine/data_manager.py

Browse files
Files changed (1) hide show
  1. ml_engine/data_manager.py +50 -43
ml_engine/data_manager.py CHANGED
@@ -1,6 +1,6 @@
1
  # ============================================================
2
  # ๐Ÿ“‚ ml_engine/data_manager.py
3
- # (V55.0 - GEM-Architect: KuCoin API Compliance Fix)
4
  # ============================================================
5
 
6
  import asyncio
@@ -28,9 +28,10 @@ logging.getLogger("ccxt").setLevel(logging.WARNING)
28
 
29
  class DataManager:
30
  """
31
- DataManager V55.0 (API Compliance Fix)
32
- - FIXED: fetch_order_book limit set to 20 (KuCoin requirement: 20 or 100).
33
- - Logic: Strict Structural Integrity (V53 Logic).
 
34
  """
35
 
36
  def __init__(self, contracts_db, whale_monitor, r2_service=None):
@@ -55,7 +56,7 @@ class DataManager:
55
  'UP', 'DOWN', 'BEAR', 'BULL', '3S', '3L', 'USDD', 'USDP', 'HT', 'KCS'
56
  ]
57
 
58
- print(f"๐Ÿ“ฆ [DataManager V55.0] API Compliance Engine Active.")
59
 
60
  async def initialize(self):
61
  print(" > [DataManager] Starting Matrix Initialization...")
@@ -174,19 +175,21 @@ class DataManager:
174
  else: quote_vol = 0.0
175
  else: quote_vol = float(quote_vol)
176
 
177
- # STRICT Volume Floor: $1M
178
  if quote_vol < 1_000_000: continue
179
 
180
  pre_candidates.append({'symbol': symbol, 'quote_volume': quote_vol, 'ticker': ticker})
181
 
182
  pre_candidates.sort(key=lambda x: x['quote_volume'], reverse=True)
 
183
  top_150 = pre_candidates[:150]
184
  print(f" -> Valid Universe: {len(pre_candidates)}. Inspecting Top {len(top_150)}...")
185
 
186
- # --- Step 2: Deep Inspection (Safe Batching) ---
187
  final_candidates = []
188
- chunk_size = 10 # Slightly increased for speed since limit is fixed
189
- reject_stats = {'spread': 0, 'depth': 0, 'age': 0, 'integrity': 0, 'wall': 0, 'other': 0}
 
190
 
191
  for i in range(0, len(top_150), chunk_size):
192
  chunk = top_150[i:i+chunk_size]
@@ -197,7 +200,7 @@ class DataManager:
197
  if len(final_candidates) == 0:
198
  print(f" โš ๏ธ ALL REJECTED! Stats: {reject_stats}")
199
  else:
200
- print(f" -> [Structural Guard] {len(final_candidates)} candidates passed Strict Checks.")
201
 
202
  return final_candidates
203
 
@@ -210,7 +213,7 @@ class DataManager:
210
  symbol = candidate['symbol']
211
  ticker = candidate['ticker']
212
  try:
213
- # โœ… FIXED: limit=20 (KuCoin accepts 20 or 100)
214
  tasks = [
215
  self.exchange.fetch_ohlcv(symbol, '5m', limit=50),
216
  self.exchange.fetch_ohlcv(symbol, '1d', limit=200),
@@ -222,19 +225,17 @@ class DataManager:
222
  stats['other'] += 1
223
  return None
224
 
225
- # 1. Age Check (> 7 days)
226
  if len(ohlcv_1d) < 7:
227
  stats['age'] += 1
228
  return None
229
 
230
- # 2. Integrity Check (Zero Volume)
231
  for candle in ohlcv_5m[-10:]:
232
  if candle[5] <= 0:
233
  stats['integrity'] += 1
234
  return None
235
 
236
  current_price = float(ticker['last'])
237
- # KuCoin orderbook might be empty or have fewer bids
238
  if not orderbook.get('bids') or not orderbook.get('asks'):
239
  stats['other'] += 1
240
  return None
@@ -242,32 +243,11 @@ class DataManager:
242
  bid = float(orderbook['bids'][0][0])
243
  ask = float(orderbook['asks'][0][0])
244
 
245
- if bid == 0 or ask == 0:
246
- stats['other'] += 1
247
- return None
248
-
249
- # 3. Spread Check (< 2.5% OR Dynamic)
250
  spread_abs = (ask - bid) / bid
251
-
252
- # Dynamic calculation
253
- df_5m = pd.DataFrame(ohlcv_5m, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
254
- h_l = df_5m['h'] - df_5m['l']
255
- atr_val = h_l.rolling(14).mean().iloc[-1]
256
- atr_threshold = 0.35 * (atr_val / current_price) if current_price > 0 else 0
257
-
258
- limit_spread = max(0.015, atr_threshold)
259
-
260
- # Hard limit check
261
- if spread_abs > 0.025:
262
  stats['spread'] += 1
263
- return None
264
-
265
- # Dynamic check
266
- if spread_abs > limit_spread:
267
- stats['spread'] += 1
268
- return None
269
 
270
- # 4. Depth Check (>$2,000 within 0.5%)
271
  min_depth_price = bid * 0.995
272
  bid_depth_usd = 0.0
273
  for price, vol in orderbook['bids']:
@@ -278,7 +258,6 @@ class DataManager:
278
  stats['depth'] += 1
279
  return None
280
 
281
- # 5. Sell Walls (Ratio > 5x)
282
  max_wall_price = ask * 1.02
283
  ask_depth_usd = 0.0
284
  for price, vol in orderbook['asks']:
@@ -289,15 +268,43 @@ class DataManager:
289
  stats['wall'] += 1
290
  return None
291
 
292
- # โœ… PASSED
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  candidate['current_price'] = current_price
294
  candidate['sort_score'] = candidate['quote_volume']
295
  return candidate
296
 
297
- except Exception as e:
298
- # Only print real errors, ignore expected ones to keep logs clean
299
- # stats['other'] += 1
300
- if "limit argument" in str(e): print(f"API ERROR: {e}") # Should not happen now
301
  stats['other'] += 1
302
  return None
303
 
 
1
  # ============================================================
2
  # ๐Ÿ“‚ ml_engine/data_manager.py
3
+ # (V56.0 - GEM-Architect: Oracle-Aligned Structural Filter)
4
  # ============================================================
5
 
6
  import asyncio
 
28
 
29
  class DataManager:
30
  """
31
+ DataManager V56.0 (Oracle Alignment)
32
+ - Structural Integrity: Keeps V53 strict checks (Spread, Depth, Walls).
33
+ - Oracle Alignment: Adds lightweight technical checks (RSI, Slope)
34
+ to ensure candidates match Oracle's feature expectations.
35
  """
36
 
37
  def __init__(self, contracts_db, whale_monitor, r2_service=None):
 
56
  'UP', 'DOWN', 'BEAR', 'BULL', '3S', '3L', 'USDD', 'USDP', 'HT', 'KCS'
57
  ]
58
 
59
+ print(f"๐Ÿ“ฆ [DataManager V56.0] Oracle-Aligned Engine Active.")
60
 
61
  async def initialize(self):
62
  print(" > [DataManager] Starting Matrix Initialization...")
 
175
  else: quote_vol = 0.0
176
  else: quote_vol = float(quote_vol)
177
 
178
+ # ๐Ÿ”’ STRICT: Volume Floor ($1M)
179
  if quote_vol < 1_000_000: continue
180
 
181
  pre_candidates.append({'symbol': symbol, 'quote_volume': quote_vol, 'ticker': ticker})
182
 
183
  pre_candidates.sort(key=lambda x: x['quote_volume'], reverse=True)
184
+ # Increased scan depth slightly to find matching tech candidates
185
  top_150 = pre_candidates[:150]
186
  print(f" -> Valid Universe: {len(pre_candidates)}. Inspecting Top {len(top_150)}...")
187
 
188
+ # --- Step 2: Deep Inspection ---
189
  final_candidates = []
190
+ chunk_size = 20
191
+ # Diagnostics extended
192
+ reject_stats = {'spread': 0, 'depth': 0, 'age': 0, 'integrity': 0, 'wall': 0, 'tech': 0, 'other': 0}
193
 
194
  for i in range(0, len(top_150), chunk_size):
195
  chunk = top_150[i:i+chunk_size]
 
200
  if len(final_candidates) == 0:
201
  print(f" โš ๏ธ ALL REJECTED! Stats: {reject_stats}")
202
  else:
203
+ print(f" -> [Structural Guard] {len(final_candidates)} candidates passed Integrity & Oracle-Align Checks.")
204
 
205
  return final_candidates
206
 
 
213
  symbol = candidate['symbol']
214
  ticker = candidate['ticker']
215
  try:
216
+ # ๐Ÿ”’ STRICT DATA
217
  tasks = [
218
  self.exchange.fetch_ohlcv(symbol, '5m', limit=50),
219
  self.exchange.fetch_ohlcv(symbol, '1d', limit=200),
 
225
  stats['other'] += 1
226
  return None
227
 
228
+ # 1. Structural Checks (The Old Guard)
229
  if len(ohlcv_1d) < 7:
230
  stats['age'] += 1
231
  return None
232
 
 
233
  for candle in ohlcv_5m[-10:]:
234
  if candle[5] <= 0:
235
  stats['integrity'] += 1
236
  return None
237
 
238
  current_price = float(ticker['last'])
 
239
  if not orderbook.get('bids') or not orderbook.get('asks'):
240
  stats['other'] += 1
241
  return None
 
243
  bid = float(orderbook['bids'][0][0])
244
  ask = float(orderbook['asks'][0][0])
245
 
 
 
 
 
 
246
  spread_abs = (ask - bid) / bid
247
+ if spread_abs > 0.025:
 
 
 
 
 
 
 
 
 
 
248
  stats['spread'] += 1
249
+ return None
 
 
 
 
 
250
 
 
251
  min_depth_price = bid * 0.995
252
  bid_depth_usd = 0.0
253
  for price, vol in orderbook['bids']:
 
258
  stats['depth'] += 1
259
  return None
260
 
 
261
  max_wall_price = ask * 1.02
262
  ask_depth_usd = 0.0
263
  for price, vol in orderbook['asks']:
 
268
  stats['wall'] += 1
269
  return None
270
 
271
+ # ======================================================
272
+ # ๐Ÿง  NEW: ORACLE ALIGNMENT (Technical Vitality Check)
273
+ # ======================================================
274
+ # Here we perform a quick check to see if the coin
275
+ # has the features Oracle loves (Momentum, Uptrend).
276
+
277
+ df_5m = pd.DataFrame(ohlcv_5m, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
278
+ closes = df_5m['c']
279
+
280
+ # A. RSI Check
281
+ # Oracle tends to reject RSI < 35 (Falling Knife) unless specific Bear setup.
282
+ # Oracle tends to reject RSI > 85 (Overextended)
283
+ current_rsi = ta.rsi(closes, length=14).iloc[-1]
284
+ if current_rsi < 35 or current_rsi > 85:
285
+ stats['tech'] += 1
286
+ return None
287
+
288
+ # B. Trend Alignment (Slope & EMA)
289
+ # Oracle uses 'slope' feature. If slope is sharply negative, Oracle predicts Short.
290
+ # We filter out sharp downtrends.
291
+ slope = ta.slope(closes, length=7).iloc[-1]
292
+
293
+ # Also use EMA for trend context
294
+ ema_50 = ta.ema(closes, length=50).iloc[-1]
295
+
296
+ # Rule: Must not be crashing.
297
+ # If Slope is negative AND Price < EMA50 -> It's a downtrend -> Oracle will Reject.
298
+ if slope < 0 and current_price < ema_50:
299
+ stats['tech'] += 1
300
+ return None
301
+
302
+ # โœ… PASSED ALL CHECKS (Structural + Technical)
303
  candidate['current_price'] = current_price
304
  candidate['sort_score'] = candidate['quote_volume']
305
  return candidate
306
 
307
+ except Exception:
 
 
 
308
  stats['other'] += 1
309
  return None
310