Spaces:
Running
Running
File size: 15,174 Bytes
2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 2f2e02d 3c09406 | 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 |
// 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);
}); |