tomirisai80 commited on
Commit
cb9172b
·
verified ·
1 Parent(s): 0cb5acf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -17
app.py CHANGED
@@ -22,7 +22,7 @@ for module_name, pip_name in REQUIRED_PACKAGES.items():
22
  print(f"✅ {pip_name} установлен!")
23
 
24
  # ============================================
25
- # 👑 TOMIRIS SPACE 20 v1.3 — ETHEREUM L2 & DEFI PULSE
26
  # ============================================
27
  from fastapi import FastAPI, Query
28
  from typing import Optional, Dict, Any, List
@@ -93,7 +93,7 @@ def send_signal_to_hub(symbol: str, signal: str, confidence: float, features: Di
93
  "signal": signal,
94
  "confidence": round(confidence, 4),
95
  "features": features,
96
- "metadata": {"version": "1.3"},
97
  "timestamp": datetime.now().isoformat()
98
  }
99
 
@@ -128,19 +128,25 @@ def fetch_chain_tvl(chain: str) -> Optional[Dict[str, Any]]:
128
  r = requests.get(f"https://api.llama.fi/tvl/{chain}", timeout=10)
129
  if r.status_code == 200:
130
  text = r.text.strip()
131
- if not text:
 
132
  return None
133
  try:
134
  data = r.json()
135
  except:
 
136
  return None
137
 
138
  if isinstance(data, (int, float)):
139
  tvl = float(data)
 
 
140
  change_24h = 0
141
  change_7d = 0
142
  elif isinstance(data, dict):
143
  tvl = data.get('tvl', 0)
 
 
144
  change_24h = data.get('change_1d', 0)
145
  change_7d = data.get('change_7d', 0)
146
  else:
@@ -156,6 +162,7 @@ def fetch_chain_tvl(chain: str) -> Optional[Dict[str, Any]]:
156
  }
157
  CACHE[cache_key] = result
158
  CACHE_TIMES[cache_key] = time.time()
 
159
  return result
160
  except Exception as e:
161
  logger.warning(f"⚠️ TVL {chain}: {e}")
@@ -169,13 +176,23 @@ def fetch_all_l2_tvl() -> Dict[str, Any]:
169
 
170
  for chain, name in L2_CHAINS.items():
171
  data = fetch_chain_tvl(chain)
172
- if data:
173
  l2_data[chain] = data
174
  total_tvl += data['tvl']
175
- total_change += data['change_24h']
176
  active_chains += 1
177
  else:
178
- l2_data[chain] = {"error": "no_data"}
 
 
 
 
 
 
 
 
 
 
179
 
180
  avg_change = total_change / active_chains if active_chains > 0 else 0
181
 
@@ -215,7 +232,7 @@ def fetch_staking_metrics() -> Dict[str, Any]:
215
  r = requests.get("https://api.llama.fi/tvl/lido", timeout=10)
216
  if r.status_code == 200:
217
  text = r.text.strip()
218
- if text:
219
  try:
220
  data = r.json()
221
  if isinstance(data, (int, float)):
@@ -234,7 +251,7 @@ def fetch_staking_metrics() -> Dict[str, Any]:
234
  r = requests.get("https://api.llama.fi/tvl/eigenlayer", timeout=10)
235
  if r.status_code == 200:
236
  text = r.text.strip()
237
- if text:
238
  try:
239
  data = r.json()
240
  if isinstance(data, (int, float)):
@@ -248,7 +265,11 @@ def fetch_staking_metrics() -> Dict[str, Any]:
248
  except:
249
  result['eigenlayer_tvl'] = 0
250
 
251
- result['lido_tvl_billions'] = round(result.get('lido_tvl', 0) / 1e9, 2)
 
 
 
 
252
 
253
  eigen_change = result.get('eigenlayer_change_24h', 0) or 0
254
  if eigen_change > 5:
@@ -281,7 +302,7 @@ def fetch_dex_volumes() -> Dict[str, Any]:
281
  change24h = data.get('change_1d', 0)
282
  result = {
283
  'total_volume_24h': total24h,
284
- 'volume_billions': round(total24h / 1e9, 2),
285
  'change_24h': change24h,
286
  'trend': 'UP' if change24h > 0 else 'DOWN',
287
  'signal': 'BULLISH' if change24h > 10 else 'BEARISH' if change24h < -10 else 'NEUTRAL'
@@ -343,6 +364,7 @@ def analyze_ecosystem() -> Dict[str, Any]:
343
  signals = []
344
  score = 50.0
345
 
 
346
  if l2.get('trend') == 'GROWING':
347
  signals.append({"signal": "BULLISH", "reason": f"L2 растёт (+{l2.get('avg_change_24h', 0):.1f}%)"})
348
  score += 15
@@ -350,17 +372,21 @@ def analyze_ecosystem() -> Dict[str, Any]:
350
  signals.append({"signal": "BEARISH", "reason": "L2 падает"})
351
  score -= 15
352
 
353
- if eth_tvl.get('trend') == 'UP' and eth_tvl.get('change_24h', 0) > 2:
 
 
354
  signals.append({"signal": "BULLISH", "reason": "TVL ETH растёт"})
355
  score += 10
356
- elif eth_tvl.get('trend') == 'DOWN' and eth_tvl.get('change_24h', 0) < -2:
357
  signals.append({"signal": "BEARISH", "reason": "TVL ETH падает"})
358
  score -= 10
359
 
 
360
  if staking.get('restaking_growth') == 'HIGH':
361
  signals.append({"signal": "BULLISH", "reason": "Рестейкинг растёт"})
362
  score += 5
363
 
 
364
  if dex.get('signal') == 'BULLISH':
365
  signals.append({"signal": "BULLISH", "reason": "DEX объёмы растут"})
366
  score += 8
@@ -368,10 +394,12 @@ def analyze_ecosystem() -> Dict[str, Any]:
368
  signals.append({"signal": "BEARISH", "reason": "DEX объёмы падают"})
369
  score -= 8
370
 
 
371
  if ultrasound.get('is_deflationary'):
372
  signals.append({"signal": "BULLISH", "reason": "ETH дефляционный"})
373
  score += 8
374
 
 
375
  if dev.get('activity') == 'HIGH':
376
  signals.append({"signal": "BULLISH", "reason": "Высокая активность разработчиков"})
377
  score += 3
@@ -451,19 +479,19 @@ def keep_alive():
451
  threading.Thread(target=keep_alive, daemon=True).start()
452
 
453
  # ================= FASTAPI =================
454
- app = FastAPI(title="TOMIRIS SPACE 20 v1.3 — L2 & DEFI PULSE")
455
 
456
  @app.on_event("startup")
457
  async def startup():
458
  asyncio.create_task(auto_send_loop())
459
- logger.info(f"🚀 Space 20 v1.3 ЗАПУЩЕН | Хаб: {HUB_URL}")
460
 
461
  @app.get("/health")
462
  async def health():
463
  return {
464
  "space_id": SPACE_ID,
465
  "status": "operational",
466
- "version": "1.3",
467
  "hub_url": HUB_URL,
468
  "l2_chains": list(L2_CHAINS.keys())
469
  }
@@ -510,12 +538,13 @@ async def send_now():
510
 
511
  @app.get("/")
512
  async def root():
513
- return {"name": "L2 & DeFi Pulse v1.3", "space_id": SPACE_ID, "hub": HUB_URL}
514
 
515
  if __name__ == "__main__":
516
  import uvicorn
517
  uvicorn.run(app, host="0.0.0.0", port=7860)
518
 
519
- print(f"🚀 SPACE 20 v1.3 — L2 & DEFI PULSE ЗАПУЩЕН!")
520
  print(f"🔷 Мониторинг: Arbitrum, Optimism, Base, Polygon ZkEVM | DEX | Staking | Ultrasound")
 
521
  print(f"✅ Готов к бою!")
 
22
  print(f"✅ {pip_name} установлен!")
23
 
24
  # ============================================
25
+ # 👑 TOMIRIS SPACE 20 v1.4 — ETHEREUM L2 & DEFI PULSE (TVL FIX)
26
  # ============================================
27
  from fastapi import FastAPI, Query
28
  from typing import Optional, Dict, Any, List
 
93
  "signal": signal,
94
  "confidence": round(confidence, 4),
95
  "features": features,
96
+ "metadata": {"version": "1.4"},
97
  "timestamp": datetime.now().isoformat()
98
  }
99
 
 
128
  r = requests.get(f"https://api.llama.fi/tvl/{chain}", timeout=10)
129
  if r.status_code == 200:
130
  text = r.text.strip()
131
+ if not text or text == "0" or text == "0.0":
132
+ logger.warning(f"TVL {chain}: пустой ответ или 0")
133
  return None
134
  try:
135
  data = r.json()
136
  except:
137
+ logger.warning(f"TVL {chain}: не JSON")
138
  return None
139
 
140
  if isinstance(data, (int, float)):
141
  tvl = float(data)
142
+ if tvl == 0:
143
+ return None
144
  change_24h = 0
145
  change_7d = 0
146
  elif isinstance(data, dict):
147
  tvl = data.get('tvl', 0)
148
+ if tvl == 0:
149
+ return None
150
  change_24h = data.get('change_1d', 0)
151
  change_7d = data.get('change_7d', 0)
152
  else:
 
162
  }
163
  CACHE[cache_key] = result
164
  CACHE_TIMES[cache_key] = time.time()
165
+ logger.debug(f"✅ TVL {chain}: ${result['tvl_billions']}B")
166
  return result
167
  except Exception as e:
168
  logger.warning(f"⚠️ TVL {chain}: {e}")
 
176
 
177
  for chain, name in L2_CHAINS.items():
178
  data = fetch_chain_tvl(chain)
179
+ if data and data.get('tvl', 0) > 0:
180
  l2_data[chain] = data
181
  total_tvl += data['tvl']
182
+ total_change += data.get('change_24h', 0)
183
  active_chains += 1
184
  else:
185
+ l2_data[chain] = {"error": "no_data", "tvl": 0}
186
+
187
+ # 🔥 ФИКС: Если все L2 TVL = 0, используем Ethereum TVL как прокси (20%)
188
+ if total_tvl == 0:
189
+ logger.info("🔄 Все L2 TVL = 0, использую Ethereum как прокси...")
190
+ eth_data = fetch_chain_tvl("ethereum")
191
+ if eth_data and eth_data.get('tvl', 0) > 0:
192
+ total_tvl = eth_data['tvl'] * 0.20 # ~20% TVL ETH на L2
193
+ total_change = eth_data.get('change_24h', 0)
194
+ active_chains = 1
195
+ logger.info(f"🔄 Прокси L2 TVL: ${round(total_tvl/1e9, 2)}B (20% от ETH TVL)")
196
 
197
  avg_change = total_change / active_chains if active_chains > 0 else 0
198
 
 
232
  r = requests.get("https://api.llama.fi/tvl/lido", timeout=10)
233
  if r.status_code == 200:
234
  text = r.text.strip()
235
+ if text and text != "0":
236
  try:
237
  data = r.json()
238
  if isinstance(data, (int, float)):
 
251
  r = requests.get("https://api.llama.fi/tvl/eigenlayer", timeout=10)
252
  if r.status_code == 200:
253
  text = r.text.strip()
254
+ if text and text != "0":
255
  try:
256
  data = r.json()
257
  if isinstance(data, (int, float)):
 
265
  except:
266
  result['eigenlayer_tvl'] = 0
267
 
268
+ result['lido_tvl'] = result.get('lido_tvl', 0)
269
+ result['eigenlayer_tvl'] = result.get('eigenlayer_tvl', 0)
270
+ result['lido_tvl_billions'] = round(result['lido_tvl'] / 1e9, 2)
271
+ result['lido_change_24h'] = result.get('lido_change_24h', 0)
272
+ result['eigenlayer_change_24h'] = result.get('eigenlayer_change_24h', 0)
273
 
274
  eigen_change = result.get('eigenlayer_change_24h', 0) or 0
275
  if eigen_change > 5:
 
302
  change24h = data.get('change_1d', 0)
303
  result = {
304
  'total_volume_24h': total24h,
305
+ 'volume_billions': round(total24h / 1e9, 2) if total24h else 0,
306
  'change_24h': change24h,
307
  'trend': 'UP' if change24h > 0 else 'DOWN',
308
  'signal': 'BULLISH' if change24h > 10 else 'BEARISH' if change24h < -10 else 'NEUTRAL'
 
364
  signals = []
365
  score = 50.0
366
 
367
+ # L2 TVL
368
  if l2.get('trend') == 'GROWING':
369
  signals.append({"signal": "BULLISH", "reason": f"L2 растёт (+{l2.get('avg_change_24h', 0):.1f}%)"})
370
  score += 15
 
372
  signals.append({"signal": "BEARISH", "reason": "L2 падает"})
373
  score -= 15
374
 
375
+ # ETH TVL
376
+ eth_change = eth_tvl.get('change_24h', 0)
377
+ if eth_tvl.get('trend') == 'UP' and eth_change > 2:
378
  signals.append({"signal": "BULLISH", "reason": "TVL ETH растёт"})
379
  score += 10
380
+ elif eth_tvl.get('trend') == 'DOWN' and eth_change < -2:
381
  signals.append({"signal": "BEARISH", "reason": "TVL ETH падает"})
382
  score -= 10
383
 
384
+ # Staking
385
  if staking.get('restaking_growth') == 'HIGH':
386
  signals.append({"signal": "BULLISH", "reason": "Рестейкинг растёт"})
387
  score += 5
388
 
389
+ # DEX
390
  if dex.get('signal') == 'BULLISH':
391
  signals.append({"signal": "BULLISH", "reason": "DEX объёмы растут"})
392
  score += 8
 
394
  signals.append({"signal": "BEARISH", "reason": "DEX объёмы падают"})
395
  score -= 8
396
 
397
+ # Ultrasound
398
  if ultrasound.get('is_deflationary'):
399
  signals.append({"signal": "BULLISH", "reason": "ETH дефляционный"})
400
  score += 8
401
 
402
+ # Developers
403
  if dev.get('activity') == 'HIGH':
404
  signals.append({"signal": "BULLISH", "reason": "Высокая активность разработчиков"})
405
  score += 3
 
479
  threading.Thread(target=keep_alive, daemon=True).start()
480
 
481
  # ================= FASTAPI =================
482
+ app = FastAPI(title="TOMIRIS SPACE 20 v1.4 — L2 & DEFI PULSE")
483
 
484
  @app.on_event("startup")
485
  async def startup():
486
  asyncio.create_task(auto_send_loop())
487
+ logger.info(f"🚀 Space 20 v1.4 ЗАПУЩЕН | Хаб: {HUB_URL}")
488
 
489
  @app.get("/health")
490
  async def health():
491
  return {
492
  "space_id": SPACE_ID,
493
  "status": "operational",
494
+ "version": "1.4",
495
  "hub_url": HUB_URL,
496
  "l2_chains": list(L2_CHAINS.keys())
497
  }
 
538
 
539
  @app.get("/")
540
  async def root():
541
+ return {"name": "L2 & DeFi Pulse v1.4", "space_id": SPACE_ID, "hub": HUB_URL}
542
 
543
  if __name__ == "__main__":
544
  import uvicorn
545
  uvicorn.run(app, host="0.0.0.0", port=7860)
546
 
547
+ print(f"🚀 SPACE 20 v1.4 — L2 & DEFI PULSE ЗАПУЩЕН!")
548
  print(f"🔷 Мониторинг: Arbitrum, Optimism, Base, Polygon ZkEVM | DEX | Staking | Ultrasound")
549
+ print(f"🔄 Прокси L2 TVL: 20% от ETH TVL если DeFiLlama недоступна")
550
  print(f"✅ Готов к бою!")