""" Crypto Perpetual Futures Signal Analysis Backend ================================================ FastAPI application entry point. Lifecycle: - On startup: initialise DB, create exchange clients, start background signal loop - On shutdown: cancel background task, close HTTP clients Background loop: - Runs every UPDATE_INTERVAL seconds - For each active pair: collect data → compute signal → save to DB → broadcast via WS """ import os import time import asyncio import logging from contextlib import asynccontextmanager from typing import Any from fastapi import Depends, FastAPI, Request, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.gzip import GZipMiddleware from pydantic import BaseModel import config from config import UPDATE_INTERVAL, CORS_ORIGINS from security import is_auth_configured, require_api_token, require_cron_or_api_token from database.db import ( init_db, async_get_active_pairs, async_get_stale_active_pairs, async_save_signal, async_save_snapshot, async_save_snapshots_batch, async_get_pair, async_insert_pair, async_update_pair_exchanges, async_update_pair_streak, async_prune_old_records, ) from exchanges.binance import BinanceClient from exchanges.bybit import BybitClient from exchanges.okx import OKXClient from exchanges.hyperliquid import HyperliquidClient from exchanges.bitget import BitgetClient from engine.data_collector import DataCollector from engine.outcome_evaluator import async_evaluate_pending_predictions, async_log_prediction_if_new from engine.signal_engine import SignalEngine from engine.bulk_fetcher import bulk_fetcher from routers import signals as signals_router from routers import ws as ws_router from routers import market as market_router from routers import ai as ai_router from routers import journal as journal_router from routers import execution as execution_router from routers.ws import broadcast logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", ) logger = logging.getLogger(__name__) # Transparent DNS-over-HTTPS bypass for blocked ISP (Telkomsel/Internet Baik) from engine.doh_resolver import enable_doh_bypass enable_doh_bypass() signal_engine = SignalEngine() _background_tasks: set[asyncio.Task] = set() def _spawn_background_task(coro: Any) -> asyncio.Task: """Create a background task with a strong reference so GC cannot drop it prematurely.""" task = asyncio.create_task(coro) _background_tasks.add(task) task.add_done_callback(_background_tasks.discard) return task # ───────────────────────────────────────────────────────────────────────────── # Background task # ───────────────────────────────────────────────────────────────────────────── _btc_market_context: dict[str, Any] | None = None _pair_locks: dict[str, asyncio.Lock] = {} def _get_pair_lock(symbol: str) -> asyncio.Lock: sym = symbol.upper().strip() lock = _pair_locks.get(sym) if lock is None: lock = asyncio.Lock() _pair_locks[sym] = lock return lock def _extract_btc_context(btc_signal: dict[str, Any], raw: dict[str, Any]) -> dict[str, Any]: """Build lightweight BTC macro trend context to guard altcoin longs during active BTC dumps.""" btc_1h_pct = 0.0 for ex_name in ("binance", "bybit", "okx", "bitget"): ex = raw.get(ex_name) c1h = ((ex or {}).get("ohlcv") or {}).get("1h") or [] if len(c1h) >= 2 and (c1h[-2].get("close") or 0) > 0 and c1h[-1].get("close") is not None: btc_1h_pct = (float(c1h[-1]["close"]) - float(c1h[-2]["close"])) / float(c1h[-2]["close"]) * 100.0 break return { "btc_direction": btc_signal.get("direction", "NEUTRAL"), "btc_conviction": int(btc_signal.get("conviction") or 0), "btc_regime": str(btc_signal.get("market_condition") or "trending"), "btc_1h_change_pct": round(btc_1h_pct, 4), } async def _process_pair( pair: dict, collector: DataCollector, market_context: dict[str, Any] | None = None, ) -> None: symbol = pair["symbol"] async with _get_pair_lock(symbol): await _process_pair_unlocked(pair, collector, market_context=market_context) async def _process_pair_unlocked( pair: dict, collector: DataCollector, market_context: dict[str, Any] | None = None, ) -> None: symbol = pair["symbol"] on_binance = bool(pair.get("on_binance", False)) on_bybit = bool(pair.get("on_bybit", False)) on_okx = bool(pair.get("on_okx", False)) on_bitget = bool(pair.get("on_bitget", False)) on_hyperliquid = bool(pair.get("on_hyperliquid", False)) # Auto-Discovery: Check in parallel if newly listed on any exchange where it was previously marked unavailable exchanges_updated = False probe_tasks: dict[str, Any] = {} if not on_binance: probe_tasks["binance"] = collector._binance.check_symbol_exists(symbol) elif on_binance and len(collector._binance._known_symbols) > 100: if not collector._binance.resolve_symbol(symbol): on_binance = False exchanges_updated = True logger.info("ℹ️ [%s] Auto-Correct: Tidak terdaftar di Binance linear perps. Menonaktifkan Binance feed.", symbol) if not on_bybit: probe_tasks["bybit"] = collector._bybit.check_symbol_exists(symbol) elif on_bybit and len(collector._bybit._known_symbols) > 100: if not collector._bybit.resolve_symbol(symbol): on_bybit = False exchanges_updated = True logger.info("ℹ️ [%s] Auto-Correct: Tidak terdaftar di Bybit linear perps. Menonaktifkan Bybit feed.", symbol) if not on_okx: probe_tasks["okx"] = collector._okx.check_symbol_exists(symbol) if not on_bitget: probe_tasks["bitget"] = collector._bitget.check_symbol_exists(symbol) if not on_hyperliquid: probe_tasks["hyperliquid"] = collector._hyperliquid.check_symbol_exists(symbol) if probe_tasks: probe_keys = list(probe_tasks.keys()) probe_results = await asyncio.gather(*probe_tasks.values(), return_exceptions=True) for ex_name, exists in zip(probe_keys, probe_results): if exists is True: exchanges_updated = True if ex_name == "binance": on_binance = True logger.info("🎉 [%s] Auto-Discovery: Terdeteksi di Binance! Mengaktifkan Binance feed.", symbol) elif ex_name == "bybit": on_bybit = True logger.info("🎉 [%s] Auto-Discovery: Terdeteksi di Bybit! Mengaktifkan Bybit feed.", symbol) elif ex_name == "okx": on_okx = True logger.info("🎉 [%s] Auto-Discovery: Terdeteksi di OKX! Mengaktifkan OKX feed.", symbol) elif ex_name == "bitget": on_bitget = True logger.info("🎉 [%s] Auto-Discovery: Terdeteksi di Bitget! Mengaktifkan Bitget feed.", symbol) elif ex_name == "hyperliquid": on_hyperliquid = True logger.info("🎉 [%s] Auto-Discovery: Terdeteksi di Hyperliquid! Mengaktifkan Hyperliquid feed.", symbol) if exchanges_updated: try: updated_pair = await async_update_pair_exchanges(symbol, on_binance, on_bybit, on_okx, on_bitget, on_hyperliquid) if updated_pair: await broadcast({"type": "pair_updated", "data": updated_pair}) except Exception as exc: logger.warning("[%s] Failed to persist auto-discovered exchange status: %s", symbol, exc) try: raw = await collector.collect( symbol, on_binance=on_binance, on_bybit=on_bybit, on_okx=on_okx, on_hyperliquid=on_hyperliquid, on_bitget=on_bitget, ) except Exception as exc: logger.error("[%s] Data collection error: %s", symbol, exc) return try: global _btc_market_context ctx = market_context if market_context is not None else _btc_market_context signal = signal_engine.compute(raw, market_context=None if symbol == "BTCUSDT" else ctx) if symbol == "BTCUSDT": _btc_market_context = _extract_btc_context(signal, raw) except Exception as exc: logger.error("[%s] Signal computation error: %s", symbol, exc) return # Calculate signal streak curr_dir = signal.get("direction", "NEUTRAL") curr_conv = signal.get("conviction", 0) prev_streak = int(pair.get("streak_count", 0)) if pair.get("streak_count") is not None else 0 prev_dir = str(pair.get("streak_direction", "NEUTRAL")) if pair.get("streak_direction") is not None else "NEUTRAL" prev_conv = int(pair.get("last_conviction", 0)) if pair.get("last_conviction") is not None else 0 if curr_dir in ("LONG", "SHORT") and curr_conv >= 3: if curr_dir == prev_dir and curr_conv >= max(3, prev_conv - 1): new_streak = prev_streak + 1 else: new_streak = 1 else: new_streak = 0 signal["streak"] = new_streak signal["streak_direction"] = curr_dir if new_streak != prev_streak or curr_dir != prev_dir or curr_conv != prev_conv: pair["streak_count"] = new_streak pair["streak_direction"] = curr_dir pair["last_conviction"] = curr_conv try: updated_p = await async_update_pair_streak(symbol, new_streak, curr_dir, curr_conv) if updated_p: await broadcast({"type": "pair_updated", "data": updated_p}) except Exception as exc: logger.debug("[%s] Failed to persist streak: %s", symbol, exc) # Persist signal await async_save_signal( symbol=symbol, timeframe=signal.get("active_timeframe", "adaptive"), direction=signal["direction"], conviction=signal["conviction"], signal_data=signal, ) try: from engine.factor_calibrator import record_microstructure_tape_slice record_microstructure_tape_slice(symbol, signal, exchange_data=raw) except Exception as tape_exc: logger.debug("[%s] Failed to record tape slice: %s", symbol, tape_exc) try: await async_log_prediction_if_new(signal) except Exception as exc: logger.debug("[%s] Failed to log forward prediction: %s", symbol, exc) finally: signal.pop("_shadow_trade_levels", None) # Persist market snapshots in a single batch roundtrip snapshots_to_save = [] for exch_name, exch_data in signal.get("exchange_data", {}).items(): if exch_data: snapshots_to_save.append(( symbol, exch_name, exch_data.get("funding_rate"), exch_data.get("oi"), exch_data.get("long_ratio"), exch_data.get("short_ratio"), exch_data.get("mark_price"), exch_data.get("index_price"), exch_data.get("basis_pct"), )) if snapshots_to_save: await async_save_snapshots_batch(snapshots_to_save) # Broadcast to WS clients await broadcast({"type": "signal_update", "data": signal}) logger.info( "[%s] Signal: %s (conviction=%d, score=%d)", symbol, signal["direction"], signal["conviction"], signal["score"], ) async def _signal_loop(collector: DataCollector) -> None: """ Tier 2: Dynamic Auto-Partitioned Shard Worker Loop. Automatically slices active pairs into balanced shards (e.g. 15 pairs per shard), pre-fetches bulk market data across Binance & Bybit, executes shard concurrent workers, and applies staggered micro-intervals between shards for smooth throughput and zero rate-limiting. """ SHARD_SIZE = 15 CONCURRENCY_PER_SHARD = 5 loop_count = 0 while True: cycle_start = time.time() try: global _btc_market_context pairs = await async_get_active_pairs() if not pairs: _btc_market_context = None logger.info("No active pairs — sleeping %ds", UPDATE_INTERVAL) else: try: from engine.ws_trade_stream import trade_streamer, trade_stream_buffer b_syms: list[str] = [] y_syms: list[str] = [] o_syms: list[str] = [] bg_syms: list[str] = [] hl_syms: list[str] = [] for p in pairs: raw_sym = str(p.get("symbol", "")).upper().strip() if not raw_sym: continue if p.get("on_binance"): b_syms.append(collector._binance.resolve_symbol(raw_sym) or raw_sym) if p.get("on_bybit"): y_syms.append(collector._bybit.resolve_symbol(raw_sym) or raw_sym) if p.get("on_okx", True): o_sym = collector._okx.resolve_symbol(raw_sym) if hasattr(collector._okx, "resolve_symbol") else raw_sym o_syms.append(o_sym or raw_sym) # Sync cached OKX contract specs to WS buffer for accurate SWAP qty scaling if hasattr(collector._okx, "_to_inst_id") and hasattr(collector._okx, "_contract_specs"): inst_id = collector._okx._to_inst_id(raw_sym) spec = getattr(collector._okx, "_contract_specs", {}).get(inst_id) if isinstance(spec, tuple) and len(spec) == 2: trade_stream_buffer.set_okx_contract_spec(inst_id, spec[0], spec[1]) if p.get("on_bitget", True): bg_sym = collector._bitget.resolve_symbol(raw_sym) if hasattr(collector._bitget, "resolve_symbol") else raw_sym bg_syms.append(bg_sym or raw_sym) if p.get("on_hyperliquid", True): hl_syms.append(raw_sym) trade_streamer.set_venue_symbols( b_syms, y_syms, okx_symbols=o_syms, bitget_symbols=bg_syms, hyperliquid_symbols=hl_syms, ) except Exception: pass # Run BTCUSDT first when active so altcoins receive fresh BTC macro context btc_pair = next((p for p in pairs if str(p.get("symbol", "")).upper() == "BTCUSDT"), None) if btc_pair is None: _btc_market_context = None other_pairs = [p for p in pairs if p is not btc_pair] total_pairs = len(pairs) shards = [other_pairs[i:i + SHARD_SIZE] for i in range(0, len(other_pairs), SHARD_SIZE)] num_shards = len(shards) logger.info( "Processing %d active pair(s) across %d auto-partitioned shard(s) (shard_size=%d, concurrency=%d)...", total_pairs, max(1, num_shards), SHARD_SIZE, CONCURRENCY_PER_SHARD ) # Pre-fetch bulk market snapshots across exchanges in one swift call try: await bulk_fetcher.refresh_if_stale(force=True) except Exception as b_err: logger.debug("Bulk fetch pre-loop note: %s", b_err) if btc_pair is not None: try: await _process_pair(btc_pair, collector) except Exception as btc_exc: logger.error("[BTCUSDT] Macro context pair error: %s", btc_exc) semaphore = asyncio.Semaphore(CONCURRENCY_PER_SHARD) async def _guarded_process(p: dict) -> None: async with semaphore: try: await _process_pair(p, collector) except Exception as exc: logger.error("[%s] Unexpected error in _guarded_process: %s", p.get("symbol"), exc) for idx, shard in enumerate(shards): try: await bulk_fetcher.refresh_if_stale(force=False) except Exception: pass tasks = [_guarded_process(p) for p in shard] await asyncio.gather(*tasks, return_exceptions=True) # Stagger micro-interval between shards if multiple exist to distribute network and DB I/O if idx < num_shards - 1: stagger = max(1.5, min(4.0, (UPDATE_INTERVAL * 0.4) / max(1, num_shards))) await asyncio.sleep(stagger) loop_count += 1 # Run DB retention pruning once every 60 iterations (~1 hour) to keep Neon free tier healthy if loop_count % 60 == 0: try: await async_prune_old_records() except Exception as prune_err: logger.warning("Periodic DB pruning error: %s", prune_err) except asyncio.CancelledError: logger.info("Signal loop cancelled.") raise except Exception as loop_err: logger.error("Error in signal loop iteration: %s", loop_err, exc_info=True) elapsed = time.time() - cycle_start sleep_time = max(3.0, UPDATE_INTERVAL - elapsed) await asyncio.sleep(sleep_time) async def process_active_pairs_batch(collector: DataCollector, limit: int = 30) -> int: """ Process active pairs in parallel shards, prioritizing the least recently updated pairs first. Pre-fetches bulk cache first. Returns count of processed pairs. """ try: target_pairs = await async_get_stale_active_pairs(limit=limit) if not target_pairs: return 0 try: await bulk_fetcher.refresh_if_stale(force=True) except Exception: pass semaphore = asyncio.Semaphore(6) async def _guarded(p: dict) -> None: async with semaphore: try: await _process_pair(p, collector) except Exception as e: logger.error("[%s] Batch processing error: %s", p.get("symbol"), e) tasks = [_guarded(p) for p in target_pairs] await asyncio.gather(*tasks, return_exceptions=True) return len(target_pairs) except Exception as exc: logger.error("process_active_pairs_batch failed: %s", exc) return 0 # ───────────────────────────────────────────────────────────────────────────── # FastAPI lifespan # ───────────────────────────────────────────────────────────────────────────── @asynccontextmanager async def lifespan(app: FastAPI): # ── Startup ────────────────────────────────────────────────────────── logger.info("Starting up Perps Signal Backend...") is_serverless = bool(os.getenv("VERCEL") or os.getenv("AWS_LAMBDA_FUNCTION_NAME")) # Init DB (safe, non-blocking, deadlock-protected) try: init_db() safe_host = config.DATABASE_URL.split("@")[-1] if "@" in config.DATABASE_URL else config.DATABASE_URL logger.info("Neon PostgreSQL database initialised at: %s", safe_host) except Exception as exc: logger.warning("DB init bypassed during startup: %s", exc) # Initial DB retention cleanup on boot (persistent server mode only, avoided during serverless cold starts) if not is_serverless: try: await async_prune_old_records() except Exception as exc: logger.warning("Initial DB pruning failed: %s", exc) # Exchange clients binance = BinanceClient() bybit = BybitClient() okx = OKXClient() bitget = BitgetClient() hyperliquid = HyperliquidClient() app.state.binance = binance app.state.bybit = bybit app.state.okx = okx app.state.bitget = bitget app.state.hyperliquid = hyperliquid collector = DataCollector(binance=binance, bybit=bybit, okx=okx, hyperliquid=hyperliquid, bitget=bitget) app.state.collector = collector # Background signal loop & eager bulk warmup (only in persistent server mode, not in ephemeral serverless lambdas) task = None def _task_error_callback(t: asyncio.Task) -> None: try: if not t.cancelled() and t.exception(): logger.critical("Background signal loop crashed with exception: %s", t.exception(), exc_info=t.exception()) except Exception: pass if not is_serverless: # Warm up symbol caches and bulk market pre-fetcher in non-blocking background tasks on persistent boot _spawn_background_task(bulk_fetcher.refresh_if_stale(force=True)) _spawn_background_task(binance._load_symbols()) _spawn_background_task(bybit._load_symbols()) _spawn_background_task(okx._load_symbols()) _spawn_background_task(bitget._refresh_symbols_universe()) _spawn_background_task(hyperliquid._refresh_meta()) # Dedicated DB retention janitor worker (runs every 30 minutes in the background) async def _retention_janitor_loop(): while True: try: await asyncio.sleep(1800) # 30 minutes await async_prune_old_records(retention_hours_snapshots=2, retention_days_signals=2) except asyncio.CancelledError: break except Exception as exc: logger.warning("[DB Janitor] Periodic retention pruning failed: %s", exc) janitor_task = asyncio.create_task(_retention_janitor_loop()) app.state.janitor_task = janitor_task async def _prediction_evaluator_loop(): while True: try: await asyncio.sleep(900) # 15 minutes await async_evaluate_pending_predictions(binance, bybit, okx, bitget, hyperliquid) try: from engine.factor_calibrator import async_evaluate_microstructure_tape candles_map = {} for p in await async_get_active_pairs(): sym = p["symbol"] ohlcv = await collector.get_ohlcv_merged(sym) if ohlcv and ohlcv.get("15m"): candles_map[sym] = ohlcv["15m"] if candles_map: await asyncio.to_thread(async_evaluate_microstructure_tape, candles_map) except Exception as tape_eval_err: logger.debug("Periodic tape evaluation skipped: %s", tape_eval_err) except asyncio.CancelledError: break except Exception as exc: logger.warning("[Prediction Evaluator] Periodic evaluation failed: %s", exc) evaluator_task = asyncio.create_task(_prediction_evaluator_loop()) app.state.evaluator_task = evaluator_task task = asyncio.create_task(_signal_loop(collector)) task.add_done_callback(_task_error_callback) app.state.signal_task = task try: from engine.ws_trade_stream import trade_streamer await trade_streamer.start() app.state.trade_streamer = trade_streamer except Exception as ws_start_err: logger.debug("WS trade streamer startup skipped: %s", ws_start_err) try: from engine.hl_whale_tracker import get_hl_whale_tracker hl_tracker = get_hl_whale_tracker() await asyncio.to_thread(hl_tracker.load_from_db) hl_tracker.start_background_loop(client=hyperliquid) app.state.hl_whale_tracker = hl_tracker except Exception as hl_start_err: logger.debug("HL whale tracker startup skipped: %s", hl_start_err) else: logger.info("Running in Serverless mode (Vercel) — standing background loop & eager bulk warmup disabled.") yield # ── Shutdown ───────────────────────────────────────────────────────── logger.info("Shutting down...") if not is_serverless: if hasattr(app.state, "hl_whale_tracker") and app.state.hl_whale_tracker: try: app.state.hl_whale_tracker.stop_background_loop() except Exception: pass if hasattr(app.state, "trade_streamer") and app.state.trade_streamer: try: await app.state.trade_streamer.stop() except Exception: pass if hasattr(app.state, "janitor_task") and app.state.janitor_task: app.state.janitor_task.cancel() try: await app.state.janitor_task except asyncio.CancelledError: pass if hasattr(app.state, "evaluator_task") and app.state.evaluator_task: app.state.evaluator_task.cancel() try: await app.state.evaluator_task except asyncio.CancelledError: pass if task: task.cancel() try: await task except asyncio.CancelledError: pass pending_bg = [t for t in list(_background_tasks) if not t.done()] for bg_t in pending_bg: bg_t.cancel() if pending_bg: try: await asyncio.wait_for(asyncio.gather(*pending_bg, return_exceptions=True), timeout=2.0) except Exception: pass await bulk_fetcher.close() await binance.close() await bybit.close() await okx.close() await bitget.close() await hyperliquid.close() from engine.data_collector import _SPOT_HTTP_CLIENT if _SPOT_HTTP_CLIENT and not _SPOT_HTTP_CLIENT.is_closed: await _SPOT_HTTP_CLIENT.aclose() from routers.ai import _AI_HTTP_CLIENT if _AI_HTTP_CLIENT and not _AI_HTTP_CLIENT.is_closed: await _AI_HTTP_CLIENT.aclose() logger.info("Shutdown complete.") # ───────────────────────────────────────────────────────────────────────────── # App factory # ───────────────────────────────────────────────────────────────────────────── app = FastAPI( title="Crypto Perps Signal API", version="1.0.0", description="Real-time perpetual futures signal analysis for Binance & Bybit", lifespan=lifespan, ) # High-Performance HTTP GZip Compression (compress payloads > 1000 bytes for lightning fast transfers) app.add_middleware(GZipMiddleware, minimum_size=1000) # CORS (Support Web, Android WebView, Capacitor capacitor://, and local loopback) if CORS_ORIGINS == ["*"]: app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=False, allow_methods=["*"], allow_headers=["*"], ) else: app.add_middleware( CORSMiddleware, allow_origins=CORS_ORIGINS, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # ── Routers ────────────────────────────────────────────────────────────────── app.include_router(signals_router.router) app.include_router(market_router.router) app.include_router(ai_router.router) app.include_router(journal_router.router) app.include_router(execution_router.router) app.include_router(ws_router.router) # ── Pairs routes (need Request for app.state access) ───────────────────────── def _normalize_symbol(raw: str) -> str: """Normalize user input: auto-strip symbols, uppercase, and auto-append USDT if quote currency is omitted.""" s = raw.strip().upper().replace("/", "").replace("-", "").replace("_", "").replace(" ", "") if not s: return s quote_currencies = ("USDT", "USDC", "USD", "BUSD", "EUR") if any(s.endswith(quote) for quote in quote_currencies): return s return f"{s}USDT" class ValidateRequest(BaseModel): symbol: str class AddPairRequest(BaseModel): symbol: str display_name: str | None = None @app.get("/api/auth/status", tags=["auth"]) async def auth_status(): """Report server authentication readiness without disclosing secrets.""" return { "auth_configured": is_auth_configured(), "stateless_execution": True, } @app.post("/api/auth/verify", tags=["auth"], dependencies=[Depends(require_api_token)]) async def auth_verify(): """Verify caller-provided Bearer PERPS_API_TOKEN.""" return {"valid": True} @app.get("/api/pairs", tags=["pairs"], dependencies=[Depends(require_api_token)]) async def list_pairs(): """List all pairs (active and inactive).""" from database.db import async_get_all_pairs try: return await async_get_all_pairs() except Exception as exc: logger.warning("Failed to list pairs: %s", exc) return [] @app.post("/api/pairs/validate", tags=["pairs"], dependencies=[Depends(require_api_token)]) async def validate_pair(body: ValidateRequest, request: Request): """ Check if a symbol exists on Binance, Bybit, OKX, Bitget, or Hyperliquid as a perpetual. Automatically appends USDT if only base asset is provided (e.g. 'BTC' -> 'BTCUSDT'). Returns: {"symbol": str, "on_binance": bool, "on_bybit": bool, "on_okx": bool, "on_bitget": bool, "on_hyperliquid": bool, "valid": bool} """ symbol = _normalize_symbol(body.symbol) binance: BinanceClient = request.app.state.binance bybit: BybitClient = request.app.state.bybit okx: OKXClient = getattr(request.app.state, "okx", None) bitget: BitgetClient = getattr(request.app.state, "bitget", None) hl: HyperliquidClient = getattr(request.app.state, "hyperliquid", None) tasks = [ binance.check_symbol_exists(symbol), bybit.check_symbol_exists(symbol), ] if okx: tasks.append(okx.check_symbol_exists(symbol)) if bitget: tasks.append(bitget.check_symbol_exists(symbol)) if hl: tasks.append(hl.check_symbol_exists(symbol)) results = await asyncio.gather(*tasks, return_exceptions=True) idx = 2 on_binance = bool(results[0]) if not isinstance(results[0], Exception) else False on_bybit = bool(results[1]) if not isinstance(results[1], Exception) else False on_okx = False if okx: on_okx = bool(results[idx]) if not isinstance(results[idx], Exception) else False idx += 1 on_bitget = False if bitget: on_bitget = bool(results[idx]) if not isinstance(results[idx], Exception) else False idx += 1 on_hl = False if hl: on_hl = bool(results[idx]) if not isinstance(results[idx], Exception) else False idx += 1 is_valid = bool(on_binance or on_bybit or on_okx or on_bitget or on_hl) return { "symbol": symbol, "on_binance": on_binance, "on_bybit": on_bybit, "on_okx": on_okx, "on_bitget": on_bitget, "on_hyperliquid": on_hl, "valid": is_valid, "message": "Valid perpetual pair" if is_valid else "Symbol not found on Binance, Bybit, OKX, Bitget, or Hyperliquid" } @app.post("/api/pairs", status_code=201, tags=["pairs"], dependencies=[Depends(require_api_token)]) async def add_pair(body: AddPairRequest, request: Request): """ Add a pair to the watchlist. Automatically normalizes symbol (e.g. 'BTC' -> 'BTCUSDT') and validates across all exchanges. """ symbol = _normalize_symbol(body.symbol) existing = await async_get_pair(symbol) if existing and existing.get("is_active"): from fastapi import HTTPException raise HTTPException(status_code=409, detail=f"{symbol} already active") elif existing and not existing.get("is_active"): from database.db import async_toggle_pair await async_toggle_pair(symbol) pair = await async_get_pair(symbol) collector = getattr(request.app.state, "collector", None) if collector and pair: _spawn_background_task(_process_pair(pair, collector)) return pair binance: BinanceClient = request.app.state.binance bybit: BybitClient = request.app.state.bybit okx: OKXClient = getattr(request.app.state, "okx", None) bitget: BitgetClient = getattr(request.app.state, "bitget", None) hl: HyperliquidClient = getattr(request.app.state, "hyperliquid", None) tasks = [ binance.check_symbol_exists(symbol), bybit.check_symbol_exists(symbol), ] if okx: tasks.append(okx.check_symbol_exists(symbol)) if bitget: tasks.append(bitget.check_symbol_exists(symbol)) if hl: tasks.append(hl.check_symbol_exists(symbol)) results = await asyncio.gather(*tasks, return_exceptions=True) idx = 2 on_binance = bool(results[0]) if not isinstance(results[0], Exception) else False on_bybit = bool(results[1]) if not isinstance(results[1], Exception) else False on_okx = False if okx: on_okx = bool(results[idx]) if not isinstance(results[idx], Exception) else False idx += 1 on_bitget = False if bitget: on_bitget = bool(results[idx]) if not isinstance(results[idx], Exception) else False idx += 1 on_hl = False if hl: on_hl = bool(results[idx]) if not isinstance(results[idx], Exception) else False idx += 1 if not (on_binance or on_bybit or on_okx or on_bitget or on_hl): from fastapi import HTTPException raise HTTPException( status_code=422, detail=f"{symbol} not found on Binance, Bybit, OKX, Bitget, or Hyperliquid as a perpetual", ) coin = symbol quote_suffix = "USDT" for q in ("USDT", "USDC", "USD", "BUSD", "EUR"): if symbol.endswith(q): coin = symbol[:-len(q)] quote_suffix = q break display_name = body.display_name or f"{coin}/{quote_suffix}" pair = await async_insert_pair( symbol, display_name, on_binance=on_binance, on_bybit=on_bybit, on_okx=on_okx, on_bitget=on_bitget, on_hyperliquid=on_hl, ) # Immediately compute signal in background for the newly added pair collector = getattr(request.app.state, "collector", None) if collector: _spawn_background_task(_process_pair(pair, collector)) return pair @app.delete("/api/pairs/{identifier}", tags=["pairs"], dependencies=[Depends(require_api_token)]) async def delete_pair(identifier: str): from database.db import async_delete_pair_by_identifier from fastapi import HTTPException deleted = await async_delete_pair_by_identifier(identifier) if not deleted: raise HTTPException(status_code=404, detail=f"Pair {identifier} not found") return {"detail": f"Pair {identifier} removed"} @app.patch("/api/pairs/{identifier}/toggle", tags=["pairs"], dependencies=[Depends(require_api_token)]) async def toggle_pair(identifier: str): from database.db import async_toggle_pair_by_identifier from fastapi import HTTPException pair = await async_toggle_pair_by_identifier(identifier) if not pair: raise HTTPException(status_code=404, detail=f"Pair {identifier} not found") return pair # ── Health check & Serverless Cron ─────────────────────────────────────────── @app.get("/health", tags=["health"]) @app.get("/api/health", tags=["health"]) async def health(): return { "status": "ok", "version": "1.0.0", "database_configured": bool(config.DATABASE_URL), } @app.get("/api/cron/refresh", tags=["cron"], dependencies=[Depends(require_cron_or_api_token)]) async def cron_refresh(request: Request): """Trigger a refresh of active pairs (used by Vercel Cron or on-demand).""" collector = getattr(request.app.state, "collector", None) if not collector: from fastapi import HTTPException raise HTTPException(status_code=503, detail="Collector not initialized") from database.db import async_get_active_pairs pairs = await async_get_active_pairs() if not pairs: global _btc_market_context _btc_market_context = None return {"status": "ok", "message": "No active pairs to refresh"} try: await bulk_fetcher.refresh_if_stale(force=True) except Exception: pass btc_pair = next((p for p in pairs if str(p.get("symbol", "")).upper() == "BTCUSDT"), None) if btc_pair is None: _btc_market_context = None else: try: await _process_pair(btc_pair, collector) except Exception as btc_exc: logger.error("[Cron Refresh] BTCUSDT context error: %s", btc_exc) other_pairs = [p for p in pairs if p is not btc_pair] semaphore = asyncio.Semaphore(5) async def _guarded_cron(p: dict) -> None: async with semaphore: await _process_pair(p, collector) if other_pairs: await asyncio.gather(*[_guarded_cron(p) for p in other_pairs], return_exceptions=True) try: await async_evaluate_pending_predictions( getattr(request.app.state, "binance", None), getattr(request.app.state, "bybit", None), getattr(request.app.state, "okx", None), getattr(request.app.state, "bitget", None), getattr(request.app.state, "hyperliquid", None), ) except Exception as exc: logger.warning("[Cron Refresh] Outcome evaluation failed: %s", exc) return {"status": "ok", "refreshed": len(pairs)} # ── Static Frontend Serving (All-In-One Fullstack Deployment) ────────────────── from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse STATIC_DIR = os.getenv( "STATIC_DIR", os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "frontend", "dist")) ) if not os.path.exists(STATIC_DIR): STATIC_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "static")) if os.path.exists(STATIC_DIR): assets_dir = os.path.join(STATIC_DIR, "assets") if os.path.exists(assets_dir): app.mount("/assets", StaticFiles(directory=assets_dir), name="assets") @app.get("/{full_path:path}", include_in_schema=False) async def serve_spa(full_path: str): if ( full_path in ("api", "ws", "health", "docs", "openapi.json", "redoc") or full_path.startswith("api/") or full_path.startswith("ws/") ): raise HTTPException(status_code=404, detail="Not Found") static_root = os.path.realpath(STATIC_DIR) target_file = os.path.realpath(os.path.join(static_root, full_path)) try: in_static = os.path.commonpath([static_root, target_file]) == static_root except ValueError: in_static = False if not in_static: raise HTTPException(status_code=404, detail="Not Found") if os.path.isfile(target_file): return FileResponse(target_file) index_file = os.path.join(STATIC_DIR, "index.html") if os.path.exists(index_file): return FileResponse(index_file) raise HTTPException(status_code=404, detail="Frontend index.html not found") # ── Entry point ─────────────────────────────────────────────────────────────── if __name__ == "__main__": import uvicorn uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)