tomirisg25 commited on
Commit
f1c97eb
·
verified ·
1 Parent(s): 4121b9d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -11
app.py CHANGED
@@ -21,7 +21,7 @@ for module_name, pip_name in REQUIRED_PACKAGES.items():
21
  print(f"✅ {pip_name} установлен!")
22
 
23
  # ============================================
24
- # 👑 TOMIRIS SPACE 25 v2.1 — INTERMARKET CORRELATION ENGINE (Hub-Connected)
25
  # ============================================
26
  import os, time, json, logging, asyncio
27
  from typing import Dict, Any, List, Optional, Tuple
@@ -58,6 +58,9 @@ TICKER_MAP = {
58
  HUB_URL = os.getenv("SPACE17_URL", "https://tomiris-ai-name5-5.hf.space")
59
  TWELVE_DATA_KEY = os.getenv("TWELVE_DATA_KEY", "e3740c072fda4fe8b8539d40b07e445e")
60
 
 
 
 
61
  HISTORY_FILE = "correlation_history.json"
62
  CACHE_TTL = 300
63
 
@@ -275,14 +278,17 @@ async def analyze_correlations(symbol: str) -> Dict[str, Any]:
275
  # ================= ОТПРАВКА В HUB =================
276
  async def send_signal_to_hub(symbol: str, direction: str, confidence: float):
277
  try:
278
- await http_client.post(f"{HUB_URL}/signal", json={
279
  "space": "space_25_correlation",
280
  "symbol": symbol,
281
  "direction": direction,
282
  "confidence": confidence,
283
  "raw": json.dumps({"source": "space_25_correlation"})
284
- })
285
- logger.info(f"📤 {symbol}: {direction} conf={confidence:.3f} отправлен в Hub")
 
 
 
286
  except Exception as e:
287
  logger.error(f"Ошибка отправки в Hub: {e}")
288
 
@@ -292,7 +298,6 @@ async def get_correlation_signal(symbol: str = "XAU/USD") -> Dict[str, Any]:
292
  analysis = await analyze_correlations(symbol)
293
  latency = int((time.time() - start) * 1000)
294
 
295
- # Отправка в Hub
296
  await send_signal_to_hub(symbol, analysis['direction'], analysis['confidence'])
297
 
298
  result = {
@@ -314,15 +319,30 @@ async def get_correlation_signal(symbol: str = "XAU/USD") -> Dict[str, Any]:
314
  "latency_ms": latency
315
  }
316
 
317
- logger.info(f"🔗 Correlation {symbol}: {analysis['direction']} conf={analysis['confidence']:.3f} divs={analysis['divergence_count']}")
318
  return result
319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  # ================= FASTAPI =================
321
- app = FastAPI(title="Tomiris Space 25 v2.1 — Intermarket Correlation Engine (Hub)")
322
 
323
  @app.on_event("startup")
324
  async def startup():
325
- pass
 
326
 
327
  @app.on_event("shutdown")
328
  async def shutdown():
@@ -332,9 +352,10 @@ async def shutdown():
332
  async def health():
333
  return {
334
  "status": "operational",
335
- "version": "2.1",
 
 
336
  "symbols": SYMBOLS,
337
- "hub_connected": True,
338
  "history_length": len(DIVERGENCE_HISTORY)
339
  }
340
 
@@ -369,8 +390,16 @@ async def all_correlations():
369
  results[sym] = await analyze_correlations(sym)
370
  return results
371
 
 
 
 
 
 
 
 
 
372
  if __name__ == "__main__":
373
  import uvicorn
374
  uvicorn.run(app, host="0.0.0.0", port=7860)
375
 
376
- print("🚀 SPACE 25 v2.1 — INTERMARKET CORRELATION ENGINE (Hub-Connected) ЗАПУЩЕН!")
 
21
  print(f"✅ {pip_name} установлен!")
22
 
23
  # ============================================
24
+ # 👑 TOMIRIS SPACE 25 v2.2 — INTERMARKET CORRELATION ENGINE (АВТО-ОТПРАВКА)
25
  # ============================================
26
  import os, time, json, logging, asyncio
27
  from typing import Dict, Any, List, Optional, Tuple
 
58
  HUB_URL = os.getenv("SPACE17_URL", "https://tomiris-ai-name5-5.hf.space")
59
  TWELVE_DATA_KEY = os.getenv("TWELVE_DATA_KEY", "e3740c072fda4fe8b8539d40b07e445e")
60
 
61
+ # Интервал авто-отправки
62
+ AUTO_SEND_INTERVAL = int(os.getenv("AUTO_SEND_INTERVAL", "300"))
63
+
64
  HISTORY_FILE = "correlation_history.json"
65
  CACHE_TTL = 300
66
 
 
278
  # ================= ОТПРАВКА В HUB =================
279
  async def send_signal_to_hub(symbol: str, direction: str, confidence: float):
280
  try:
281
+ resp = await http_client.post(f"{HUB_URL}/signal", json={
282
  "space": "space_25_correlation",
283
  "symbol": symbol,
284
  "direction": direction,
285
  "confidence": confidence,
286
  "raw": json.dumps({"source": "space_25_correlation"})
287
+ }, timeout=10)
288
+ if resp.status_code == 200:
289
+ logger.info(f"📤 {symbol}: {direction} conf={confidence:.3f} отправлен в Hub")
290
+ else:
291
+ logger.warning(f"Hub вернул {resp.status_code}")
292
  except Exception as e:
293
  logger.error(f"Ошибка отправки в Hub: {e}")
294
 
 
298
  analysis = await analyze_correlations(symbol)
299
  latency = int((time.time() - start) * 1000)
300
 
 
301
  await send_signal_to_hub(symbol, analysis['direction'], analysis['confidence'])
302
 
303
  result = {
 
319
  "latency_ms": latency
320
  }
321
 
322
+ logger.info(f"🔗 Correlation {symbol}: {analysis['direction']} conf={analysis['confidence']:.3f}")
323
  return result
324
 
325
+ # ================= АВТО-ОТПРАВКА =================
326
+ async def auto_send_loop():
327
+ logger.info(f"🔄 Авто-отправка Correlation Engine запущена (интервал {AUTO_SEND_INTERVAL}с)")
328
+ await asyncio.sleep(30)
329
+ while True:
330
+ try:
331
+ for symbol in SYMBOLS:
332
+ await get_correlation_signal(symbol)
333
+ await asyncio.sleep(2)
334
+ logger.info("✅ Correlation Engine авто-отправка завершена")
335
+ except Exception as e:
336
+ logger.error(f"Ошибка авто-отправки: {e}")
337
+ await asyncio.sleep(AUTO_SEND_INTERVAL)
338
+
339
  # ================= FASTAPI =================
340
+ app = FastAPI(title="Tomiris Space 25 v2.2 — Intermarket Correlation Engine (Auto-Hub)")
341
 
342
  @app.on_event("startup")
343
  async def startup():
344
+ asyncio.create_task(auto_send_loop())
345
+ logger.info("🚀 Space 25 v2.2 запущен с авто-отправкой в Hub")
346
 
347
  @app.on_event("shutdown")
348
  async def shutdown():
 
352
  async def health():
353
  return {
354
  "status": "operational",
355
+ "version": "2.2",
356
+ "hub_url": HUB_URL,
357
+ "auto_send_interval": AUTO_SEND_INTERVAL,
358
  "symbols": SYMBOLS,
 
359
  "history_length": len(DIVERGENCE_HISTORY)
360
  }
361
 
 
390
  results[sym] = await analyze_correlations(sym)
391
  return results
392
 
393
+ @app.get("/send_now")
394
+ async def send_now():
395
+ results = {}
396
+ for symbol in SYMBOLS:
397
+ analysis = await get_correlation_signal(symbol)
398
+ results[symbol] = analysis.get("signal", {}).get("direction", "WAIT")
399
+ return {"status": "sent", "results": results}
400
+
401
  if __name__ == "__main__":
402
  import uvicorn
403
  uvicorn.run(app, host="0.0.0.0", port=7860)
404
 
405
+ print("🚀 SPACE 25 v2.2 — INTERMARKET CORRELATION ENGINE (АВТО-ОТПРАВКА) ЗАПУЩЕН!")