File size: 9,580 Bytes
b66240d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
"""HuggingFace Cryptocurrency Data Engine - Main Application"""
from __future__ import annotations
import time
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded

from core.config import settings, get_supported_symbols, get_supported_intervals
from core.aggregator import get_aggregator
from core.cache import cache, cache_key, get_or_set
from core.models import (
    OHLCVResponse, PricesResponse, SentimentResponse,
    MarketOverviewResponse, HealthResponse, ErrorResponse, ErrorDetail, CacheInfo
)

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


# Rate limiter
limiter = Limiter(key_func=get_remote_address)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Lifecycle manager for the application"""
    logger.info("Starting HuggingFace Crypto Data Engine...")
    logger.info(f"Version: {settings.VERSION}")
    logger.info(f"Environment: {settings.ENV}")

    # Initialize aggregator
    aggregator = get_aggregator()

    yield

    # Cleanup
    logger.info("Shutting down...")
    await aggregator.close()


# Create FastAPI app
app = FastAPI(
    title="HuggingFace Cryptocurrency Data Engine",
    description="Comprehensive cryptocurrency data aggregator with multi-provider support",
    version=settings.VERSION,
    lifespan=lifespan
)

# Add rate limiter
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """Global exception handler"""
    logger.error(f"Unhandled exception: {exc}", exc_info=True)

    return JSONResponse(
        status_code=500,
        content=ErrorResponse(
            error=ErrorDetail(
                code="INTERNAL_ERROR",
                message=str(exc)
            ),
            timestamp=int(time.time() * 1000)
        ).dict()
    )


@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "service": "HuggingFace Cryptocurrency Data Engine",
        "version": settings.VERSION,
        "status": "online",
        "endpoints": {
            "health": "/api/health",
            "ohlcv": "/api/ohlcv",
            "prices": "/api/prices",
            "sentiment": "/api/sentiment",
            "market": "/api/market/overview",
            "docs": "/docs"
        }
    }


@app.get("/api/health", response_model=HealthResponse)
@limiter.limit(f"{settings.RATE_LIMIT_HEALTH or 999999}/minute")
async def health_check(request: Request):
    """Health check endpoint with provider status"""
    aggregator = get_aggregator()

    # Get provider health
    providers = await aggregator.get_all_provider_health()

    # Determine overall status
    online_count = sum(1 for p in providers if p.status == "online")
    if online_count == 0:
        overall_status = "unhealthy"
    elif online_count < len(providers) / 2:
        overall_status = "degraded"
    else:
        overall_status = "healthy"

    # Get cache stats
    cache_stats = cache.get_stats()

    return HealthResponse(
        status=overall_status,
        uptime=aggregator.get_uptime(),
        version=settings.VERSION,
        providers=providers,
        cache=CacheInfo(**cache_stats)
    )


@app.get("/api/ohlcv", response_model=OHLCVResponse)
@limiter.limit(f"{settings.RATE_LIMIT_OHLCV}/minute")
async def get_ohlcv(
    request: Request,
    symbol: str = Query(..., description="Symbol (e.g., BTC, BTCUSDT, BTC/USDT)"),
    interval: str = Query("1h", description="Interval (1m, 5m, 15m, 1h, 4h, 1d, 1w)"),
    limit: int = Query(100, ge=1, le=1000, description="Number of candles (1-1000)")
):
    """Get OHLCV candlestick data with multi-provider fallback"""

    # Validate interval
    if interval not in get_supported_intervals():
        raise HTTPException(
            status_code=400,
            detail=f"Invalid interval. Supported: {', '.join(get_supported_intervals())}"
        )

    # Normalize symbol
    normalized_symbol = symbol.upper().replace("/", "").replace("-", "")

    # Generate cache key
    key = cache_key("ohlcv", symbol=normalized_symbol, interval=interval, limit=limit)

    async def fetch():
        aggregator = get_aggregator()
        data, source = await aggregator.fetch_ohlcv(normalized_symbol, interval, limit)
        return {"data": data, "source": source}

    try:
        # Get from cache or fetch
        result = await get_or_set(key, settings.CACHE_TTL_OHLCV, fetch)

        return OHLCVResponse(
            data=result["data"],
            symbol=normalized_symbol,
            interval=interval,
            count=len(result["data"]),
            source=result["source"],
            timestamp=int(time.time() * 1000)
        )

    except Exception as e:
        logger.error(f"OHLCV fetch failed: {e}")
        raise HTTPException(
            status_code=503,
            detail=ErrorDetail(
                code="PROVIDER_ERROR",
                message=f"All data providers failed: {str(e)}"
            ).dict()
        )


@app.get("/api/prices", response_model=PricesResponse)
@limiter.limit(f"{settings.RATE_LIMIT_PRICES}/minute")
async def get_prices(
    request: Request,
    symbols: str = Query(None, description="Comma-separated symbols (e.g., BTC,ETH,SOL)"),
    convert: str = Query("USDT", description="Convert to currency (USD, USDT)")
):
    """Get real-time prices with multi-provider aggregation"""

    # Parse symbols
    if symbols:
        symbol_list = [s.strip().upper() for s in symbols.split(",")]
    else:
        # Use default symbols
        symbol_list = get_supported_symbols()

    # Generate cache key
    key = cache_key("prices", symbols=",".join(sorted(symbol_list)))

    async def fetch():
        aggregator = get_aggregator()
        data, source = await aggregator.fetch_prices(symbol_list)
        return {"data": data, "source": source}

    try:
        # Get from cache or fetch
        result = await get_or_set(key, settings.CACHE_TTL_PRICES, fetch)

        return PricesResponse(
            data=result["data"],
            timestamp=int(time.time() * 1000),
            source=result["source"]
        )

    except Exception as e:
        logger.error(f"Price fetch failed: {e}")
        raise HTTPException(
            status_code=503,
            detail=ErrorDetail(
                code="PROVIDER_ERROR",
                message=f"All price providers failed: {str(e)}"
            ).dict()
        )


@app.get("/api/sentiment", response_model=SentimentResponse)
@limiter.limit(f"{settings.RATE_LIMIT_SENTIMENT}/minute")
async def get_sentiment(request: Request):
    """Get market sentiment data (Fear & Greed Index)"""

    if not settings.ENABLE_SENTIMENT:
        raise HTTPException(
            status_code=503,
            detail="Sentiment analysis is disabled"
        )

    # Cache key
    key = cache_key("sentiment")

    async def fetch():
        aggregator = get_aggregator()
        return await aggregator.fetch_sentiment()

    try:
        # Get from cache or fetch
        data = await get_or_set(key, settings.CACHE_TTL_SENTIMENT, fetch)

        return SentimentResponse(
            data=data,
            timestamp=int(time.time() * 1000)
        )

    except Exception as e:
        logger.error(f"Sentiment fetch failed: {e}")
        raise HTTPException(
            status_code=503,
            detail=ErrorDetail(
                code="PROVIDER_ERROR",
                message=f"Failed to fetch sentiment: {str(e)}"
            ).dict()
        )


@app.get("/api/market/overview", response_model=MarketOverviewResponse)
@limiter.limit(f"{settings.RATE_LIMIT_SENTIMENT}/minute")
async def get_market_overview(request: Request):
    """Get market overview with global statistics"""

    # Cache key
    key = cache_key("market_overview")

    async def fetch():
        aggregator = get_aggregator()
        return await aggregator.fetch_market_overview()

    try:
        # Get from cache or fetch
        data = await get_or_set(key, settings.CACHE_TTL_MARKET, fetch)

        return MarketOverviewResponse(
            data=data,
            timestamp=int(time.time() * 1000)
        )

    except Exception as e:
        logger.error(f"Market overview fetch failed: {e}")
        raise HTTPException(
            status_code=503,
            detail=ErrorDetail(
                code="PROVIDER_ERROR",
                message=f"Failed to fetch market overview: {str(e)}"
            ).dict()
        )


@app.post("/api/cache/clear")
async def clear_cache():
    """Clear all cached data"""
    cache.clear()
    return {"success": True, "message": "Cache cleared"}


@app.get("/api/cache/stats")
async def cache_stats():
    """Get cache statistics"""
    return cache.get_stats()


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=(settings.ENV == "development"),
        log_level="info"
    )