Spaces:
Running
Running
Upload pages/api/market-data.js with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778/** * API Route: Market Data Proxy * * This route acts as a proxy to fetch data from external sources. * This bypasses CORS restrictions that occur when calling APIs directly from the browser. * * Current Source: CoinGecko (Free, No Key Required for Demo) * Future Source: Yahoo Finance (Requires 'yahoo-finance2' package installed on server) */
export default async function handler(req, res) { const { symbol = 'bitcoin' } = req.query
// Map common symbols to CoinGecko IDs for demo purposes const symbolMap = { 'bitcoin': 'bitcoin', 'btc': 'bitcoin', 'ethereum': 'ethereum', 'eth': 'ethereum', 'solana': 'solana', 'sol': 'solana', // Add stock mappings here if using a stock API proxy // 'AAPL': 'apple-inc', }
const coinId = symbolMap[symbol.toLowerCase()] || 'bitcoin'
try { // Fetch from CoinGecko Public API // In production, you might want to cache this response to avoid rate limits const response = await fetch( `https://api.coingecko.com/api/v3/coins/${coinId}/market_chart?vs_currency=usd&days=1&interval=minute` )
if (!response.ok) { throw new Error('CoinGecko API failed') }
const data = await response.json() const prices = data.prices const volumes = data.total_volumes
// Get latest data point const latestPricePoint = prices[prices.length - 1] const latestVolumePoint = volumes[volumes.length - 1] // Calculate simple trend (compare current price to 1 hour ago) const oneHourAgoIndex = Math.max(0, prices.length - 60) const priceOneHourAgo = prices[oneHourAgoIndex][1] const currentPrice = latestPricePoint[1] const trend = currentPrice > priceOneHourAgo ? 'UP' : 'DOWN'
res.status(200).json({ symbol: symbol.toUpperCase(), price: currentPrice, volume: latestVolumePoint[1], trend: trend, history: prices.slice(-50).map(p => ({ time: new Date(p[0]).toLocaleTimeString(), price: p[1] })), timestamp: new Date().toISOString() })
} catch (error) { console.error('API Error:', error) // Fallback data if API fails (prevents app crash) res.status(503).json({ error: 'External data source unavailable', fallback: true, symbol: symbol.toUpperCase(), price: 0, volume: 0, trend: 'UNKNOWN', history: [] }) }}pages/api/market-data.jsAdded+78