"""把 data_provider 的资金面转给 Web,浏览器不直连交易所。""" from __future__ import annotations import logging import requests from flask import Blueprint, jsonify, request from services.runtime.market_data import ( fetch_derivatives, fetch_sentiment_latest, fetch_sentiment_metrics, ) logger = logging.getLogger(__name__) bp = Blueprint("provider", __name__) def _http_error(exc: requests.HTTPError): status = 502 detail = str(exc) if exc.response is not None: status = exc.response.status_code or 502 try: body = exc.response.json() detail = body.get("detail") or body.get("error") or detail except Exception: detail = exc.response.text or detail return jsonify({"error": detail}), status @bp.route("/api/derivatives") def api_derivatives(): symbol = (request.args.get("symbol") or "BTC/USDT:USDT").strip() exchange = (request.args.get("exchange") or "").strip() or None try: return jsonify(fetch_derivatives(symbol, exchange)) except requests.HTTPError as exc: return _http_error(exc) except Exception as exc: logger.warning("derivatives 中转失败: %s", exc) return jsonify({"error": str(exc)}), 503 @bp.route("/api/sentiment/latest") def api_sentiment_latest(): symbol = (request.args.get("symbol") or "BTC/USDT:USDT").strip() try: return jsonify(fetch_sentiment_latest(symbol)) except requests.HTTPError as exc: return _http_error(exc) except Exception as exc: logger.warning("sentiment latest 中转失败: %s", exc) return jsonify({"error": str(exc)}), 503 @bp.route("/api/sentiment/metrics") def api_sentiment_metrics(): metric = (request.args.get("metric") or "").strip() if not metric: return jsonify({"error": "metric required"}), 400 symbol = (request.args.get("symbol") or "BTC/USDT:USDT").strip() start = request.args.get("start", type=int) end = request.args.get("end", type=int) limit = request.args.get("limit", type=int) try: return jsonify(fetch_sentiment_metrics(metric, symbol, start=start, end=end, limit=limit)) except requests.HTTPError as exc: return _http_error(exc) except Exception as exc: logger.warning("sentiment 中转失败: %s", exc) return jsonify({"error": str(exc)}), 503