Spaces:
Running
Running
Download script.js from JamesJ1995/cryptovision-tracker: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/spaces/JamesJ1995/cryptovision-tracker/resolve/main/script.js
- Command line
-
hf download hf://spaces/JamesJ1995/cryptovision-tracker/script.js
-
curl -L -o script.js https://huggingface.co/spaces/JamesJ1995/cryptovision-tracker/resolve/main/script.js
15.2 kB
| // Main application script | |
| document.addEventListener('DOMContentLoaded', function() { | |
| // Technical indicators | |
| let rsi = 0; | |
| let macd = {value: 0, signal: 0}; | |
| let movingAverages = {sma50: 0, sma200: 0}; | |
| let recommendation = "Hold"; | |
| let recommendationReason = ""; | |
| // Initialize Chart | |
| const ctx = document.getElementById('price-chart').getContext('2d'); | |
| let priceChart = new Chart(ctx, { | |
| type: 'line', | |
| data: { | |
| labels: [], | |
| datasets: [{ | |
| label: 'BTC/USD', | |
| data: [], | |
| borderColor: '#3B82F6', | |
| backgroundColor: 'rgba(59, 130, 246, 0.1)', | |
| borderWidth: 2, | |
| tension: 0.4, | |
| pointRadius: 0, | |
| fill: true | |
| }] | |
| }, | |
| options: { | |
| responsive: true, | |
| maintainAspectRatio: false, | |
| plugins: { | |
| legend: { | |
| display: false | |
| }, | |
| tooltip: { | |
| mode: 'index', | |
| intersect: false, | |
| } | |
| }, | |
| scales: { | |
| x: { | |
| grid: { | |
| display: false, | |
| drawBorder: false | |
| }, | |
| ticks: { | |
| color: '#9CA3AF' | |
| } | |
| }, | |
| y: { | |
| grid: { | |
| color: 'rgba(156, 163, 175, 0.1)', | |
| drawBorder: false | |
| }, | |
| ticks: { | |
| color: '#9CA3AF' | |
| } | |
| } | |
| }, | |
| interaction: { | |
| mode: 'nearest', | |
| axis: 'x', | |
| intersect: false | |
| } | |
| } | |
| }); | |
| // Fetch real-time price data from CoinGecko API | |
| async function fetchPriceData() { | |
| try { | |
| const response = await fetch('https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=30&interval=daily'); | |
| const data = await response.json(); | |
| const prices = data.prices; | |
| const timestamps = prices.map(price => | |
| new Date(price[0]).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) | |
| ); | |
| const values = prices.map(price => price[1]); | |
| // Update chart | |
| priceChart.data.labels = timestamps; | |
| priceChart.data.datasets[0].data = values; | |
| priceChart.update(); | |
| // Calculate technical indicators (simplified) | |
| const lastPrices = values.slice(-14); // Last 14 days for RSI | |
| rsi = calculateRSI(lastPrices); | |
| macd = calculateMACD(values); | |
| movingAverages = calculateMovingAverages(values); | |
| // Update current price display | |
| const currentPrice = values[values.length - 1]; | |
| const prevPrice = values[values.length - 2]; | |
| const priceChange = ((currentPrice - prevPrice) / prevPrice) * 100; | |
| document.getElementById('btc-price').textContent = `${currentPrice.toLocaleString('en-US', {maximumFractionDigits: 2})}`; | |
| const changeElement = document.getElementById('price-change'); | |
| if (priceChange >= 0) { | |
| changeElement.textContent = `(+${priceChange.toFixed(2)}%)`; | |
| changeElement.className = 'ml-2 text-lg text-green-400'; | |
| document.getElementById('btc-price').classList.add('price-up'); | |
| setTimeout(() => document.getElementById('btc-price').classList.remove('price-up'), 1000); | |
| } else { | |
| changeElement.textContent = `(${priceChange.toFixed(2)}%)`; | |
| changeElement.className = 'ml-2 text-lg text-red-400'; | |
| document.getElementById('btc-price').classList.add('price-down'); | |
| setTimeout(() => document.getElementById('btc-price').classList.remove('price-down'), 1000); | |
| } | |
| // Generate recommendation | |
| generateRecommendation(currentPrice, priceChange); | |
| // Update technical indicators display | |
| document.getElementById('rsi-value').textContent = rsi.toFixed(2); | |
| document.getElementById('macd-value').textContent = macd.value.toFixed(2); | |
| document.getElementById('sma50-value').textContent = movingAverages.sma50.toFixed(2); | |
| document.getElementById('sma200-value').textContent = movingAverages.sma200.toFixed(2); | |
| document.getElementById('recommendation').textContent = recommendation; | |
| document.getElementById('recommendation-reason').textContent = recommendationReason; | |
| // Update market data from additional API call | |
| fetchMarketData(); | |
| } catch (error) { | |
| console.error('Error fetching price data:', error); | |
| } | |
| } | |
| // Fetch additional market data | |
| async function fetchMarketData() { | |
| try { | |
| const response = await fetch('https://api.coingecko.com/api/v3/coins/bitcoin'); | |
| const data = await response.json(); | |
| document.getElementById('high-24h').textContent = `${data.market_data.high_24h.usd.toLocaleString('en-US', {maximumFractionDigits: 2})}`; | |
| document.getElementById('low-24h').textContent = `${data.market_data.low_24h.usd.toLocaleString('en-US', {maximumFractionDigits: 2})}`; | |
| document.getElementById('volume-24h').textContent = `${data.market_data.total_volume.btc.toLocaleString('en-US', {maximumFractionDigits: 0})} BTC`; | |
| document.getElementById('market-cap').textContent = `${data.market_data.market_cap.usd.toLocaleString('en-US', {maximumFractionDigits: 0})}`; | |
| document.getElementById('update-time').textContent = new Date().toLocaleTimeString(); | |
| document.getElementById('sentiment').textContent = data.sentiment_votes_up_percentage > 50 ? 'Bullish' : 'Bearish'; | |
| document.getElementById('hash-rate').textContent = `${(data.market_data.hash_rate / 1000000000000000000).toFixed(2)} EH/s`; | |
| document.getElementById('difficulty').textContent = `${(data.market_data.difficulty / 1000000000000).toFixed(2)} T`; | |
| document.getElementById('dominance').textContent = `${data.market_data.market_cap_percentage.toFixed(1)}%`; | |
| document.getElementById('supply').textContent = `${data.market_data.circulating_supply.toLocaleString('en-US', {maximumFractionDigits: 0})}`; | |
| } catch (error) { | |
| console.error('Error fetching market data:', error); | |
| } | |
| } | |
| // Calculate RSI (simplified) | |
| function calculateRSI(prices) { | |
| let gains = 0; | |
| let losses = 0; | |
| for (let i = 1; i < prices.length; i++) { | |
| const change = prices[i] - prices[i - 1]; | |
| if (change > 0) { | |
| gains += change; | |
| } else { | |
| losses -= change; | |
| } | |
| } | |
| const avgGain = gains / 14; | |
| const avgLoss = losses / 14; | |
| const rs = avgGain / avgLoss; | |
| return 100 - (100 / (1 + rs)); | |
| } | |
| // Calculate MACD (simplified) | |
| function calculateMACD(prices) { | |
| const ema12 = prices.slice(-12).reduce((a, b) => a + b, 0) / 12; | |
| const ema26 = prices.slice(-26).reduce((a, b) => a + b, 0) / 26; | |
| const macdValue = ema12 - ema26; | |
| const signal = prices.slice(-9).reduce((a, b) => a + b, 0) / 9; | |
| return {value: macdValue, signal}; | |
| } | |
| // Calculate moving averages | |
| function calculateMovingAverages(prices) { | |
| const sma50 = prices.slice(-50).reduce((a, b) => a + b, 0) / 50; | |
| const sma200 = prices.slice(-200).reduce((a, b) => a + b, 0) / 200; | |
| return {sma50, sma200}; | |
| } | |
| // Generate trading recommendation | |
| function generateRecommendation(currentPrice, priceChange) { | |
| const bullishFactors = []; | |
| const bearishFactors = []; | |
| // Technical factors | |
| if (rsi < 30) bullishFactors.push("RSI indicates oversold conditions"); | |
| if (rsi > 70) bearishFactors.push("RSI indicates overbought conditions"); | |
| if (macd.value > macd.signal) bullishFactors.push("MACD shows bullish crossover"); | |
| if (macd.value < macd.signal) bearishFactors.push("MACD shows bearish crossover"); | |
| if (currentPrice > movingAverages.sma50 && currentPrice > movingAverages.sma200) { | |
| bullishFactors.push("Price above both 50-day and 200-day moving averages"); | |
| } else if (currentPrice < movingAverages.sma50 && currentPrice < movingAverages.sma200) { | |
| bearishFactors.push("Price below both 50-day and 200-day moving averages"); | |
| } | |
| // Price momentum | |
| if (priceChange > 2) bullishFactors.push("Strong upward momentum"); | |
| if (priceChange < -2) bearishFactors.push("Strong downward momentum"); | |
| // Determine recommendation | |
| if (bullishFactors.length > bearishFactors.length + 2) { | |
| recommendation = "Buy"; | |
| recommendationReason = bullishFactors.join(", "); | |
| } else if (bearishFactors.length > bullishFactors.length + 2) { | |
| recommendation = "Sell"; | |
| recommendationReason = bearishFactors.join(", "); | |
| } else { | |
| recommendation = "Hold"; | |
| recommendationReason = "Market conditions are neutral. " + | |
| (bullishFactors.length > 0 ? "Bullish factors: " + bullishFactors.join(", ") : "") + | |
| (bearishFactors.length > 0 ? " Bearish factors: " + bearishFactors.join(", ") : ""); | |
| } | |
| } | |
| // Fetch real news from CryptoPanic API | |
| async function fetchNews() { | |
| try { | |
| const response = await fetch('https://cryptopanic.com/api/v1/posts/?auth_token=YOUR_API_KEY¤cies=BTC&public=true'); | |
| const data = await response.json(); | |
| const newsContainer = document.getElementById('news-container'); | |
| newsContainer.innerHTML = ''; | |
| data.results.slice(0, 3).forEach(newsItem => { | |
| const newsCard = document.createElement('div'); | |
| newsCard.className = 'news-card bg-gray-800 rounded-xl shadow-lg overflow-hidden hover:shadow-xl transition-all duration-200'; | |
| const imageUrl = newsItem.metadata?.image || | |
| `http://static.photos/${newsItem.sentiment === 'positive' ? 'green' : newsItem.sentiment === 'negative' ? 'red' : 'blue'}/640x360/${Math.floor(Math.random() * 100)}`; | |
| newsCard.innerHTML = ` | |
| <img src="${imageUrl}" alt="${newsItem.title}" class="w-full h-32 object-cover"> | |
| <div class="p-6"> | |
| <h3 class="text-xl font-semibold mb-2">${newsItem.title}</h3> | |
| <p class="text-gray-400 text-sm mb-3">Source: ${newsItem.source.title}</p> | |
| <p class="text-gray-300">${newsItem.excerpt || 'Click to read more'}</p> | |
| <a href="${newsItem.url}" target="_blank" class="inline-block mt-3 text-blue-400 hover:text-blue-300">Read more →</a> | |
| </div> | |
| `; | |
| newsContainer.appendChild(newsCard); | |
| }); | |
| } catch (error) { | |
| console.error('Error fetching news:', error); | |
| // Fallback to static news if API fails | |
| const newsContainer = document.getElementById('news-container'); | |
| newsContainer.innerHTML = ''; | |
| const fallbackNews = [ | |
| { | |
| title: 'Bitcoin ETFs See Record Inflows Amid Market Rally', | |
| source: 'Bloomberg Crypto', | |
| summary: 'Bitcoin exchange-traded funds have attracted $1.2 billion in inflows this week as institutional interest grows.', | |
| image: 'http://static.photos/finance/640x360/5', | |
| url: 'https://example.com/news1' | |
| }, | |
| { | |
| title: 'Halving Event Expected to Tighten Bitcoin Supply', | |
| source: 'CoinTelegraph', | |
| summary: 'With the next Bitcoin halving approaching, analysts predict supply shock could drive prices higher.', | |
| image: 'http://static.photos/technology/640x360/6', | |
| url: 'https://example.com/news2' | |
| }, | |
| { | |
| title: 'Regulatory Clarity Boosts Crypto Market Confidence', | |
| source: 'CryptoBriefing', | |
| summary: 'Recent regulatory developments have improved investor sentiment across cryptocurrency markets.', | |
| image: 'http://static.photos/legal/640x360/7', | |
| url: 'https://example.com/news3' | |
| } | |
| ]; | |
| fallbackNews.forEach(news => { | |
| const newsCard = document.createElement('div'); | |
| newsCard.className = 'news-card bg-gray-800 rounded-xl shadow-lg overflow-hidden hover:shadow-xl transition-all duration-200'; | |
| newsCard.innerHTML = ` | |
| <img src="${news.image}" alt="${news.title}" class="w-full h-32 object-cover"> | |
| <div class="p-6"> | |
| <h3 class="text-xl font-semibold mb-2">${news.title}</h3> | |
| <p class="text-gray-400 text-sm mb-3">Source: ${news.source}</p> | |
| <p class="text-gray-300">${news.summary}</p> | |
| <a href="${news.url}" target="_blank" class="inline-block mt-3 text-blue-400 hover:text-blue-300">Read more →</a> | |
| </div> | |
| `; | |
| newsContainer.appendChild(newsCard); | |
| }); | |
| } | |
| } | |
| // Time period buttons functionality | |
| document.getElementById('1h-btn').addEventListener('click', function() { | |
| // In a real app, this would fetch 1h data | |
| alert('Switching to 1-hour view (simulated)'); | |
| }); | |
| document.getElementById('24h-btn').addEventListener('click', function() { | |
| // In a real app, this would fetch 24h data | |
| alert('Switching to 24-hour view (simulated)'); | |
| }); | |
| document.getElementById('7d-btn').addEventListener('click', function() { | |
| // In a real app, this would fetch 7d data | |
| alert('Switching to 7-day view (simulated)'); | |
| }); | |
| document.getElementById('30d-btn').addEventListener('click', function() { | |
| // In a real app, this would fetch 30d data | |
| alert('Switching to 30-day view (simulated)'); | |
| }); | |
| // Initial data fetch | |
| fetchPriceData(); | |
| fetchNews(); | |
| // Set up periodic refresh (every 30 seconds in this demo) | |
| setInterval(fetchPriceData, 30000); | |
| setInterval(fetchNews, 300000); | |
| }); |