class RealTimeFeeds extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.shadowRoot.innerHTML = `
Real-Time Crypto & Market Data
`;
this.startRealTimeFeed();
}
async startRealTimeFeed() {
try {
await this.updateCryptoPrices();
setInterval(() => this.updateCryptoPrices(), 60000); // Update every minute
} catch (error) {
this.showError('Failed to initialize feeds');
}
}
async updateCryptoPrices() {
try {
const [cryptoResponse, forexResponse] = await Promise.all([
fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,monero,litecoin&vs_currencies=usd&include_24hr_change=true'),
fetch('https://api.exchangerate-api.com/v4/latest/USD')
]);
if (!cryptoResponse.ok || !forexResponse.ok) {
throw new Error('API response failed');
}
const cryptoPrices = await cryptoResponse.json();
const forexRates = await forexResponse.json();
this.renderContent(cryptoPrices, forexRates);
} catch (error) {
this.showError('Unable to fetch market data');
}
}
renderContent(cryptoPrices, forexRates) {
const content = this.shadowRoot.getElementById('feed-content');
const updateTime = this.shadowRoot.getElementById('update-time');
const cryptoItems = Object.entries(cryptoPrices).map(([coin, data]) => {
const change = data.usd_24h_change || 0;
const changeClass = change >= 0 ? 'price-up' : 'price-down';
const changeSymbol = change >= 0 ? '↗' : '↘';
return `
${coin.toUpperCase()}/USD
$${data.usd.toLocaleString()}
${changeSymbol} ${Math.abs(change).toFixed(2)}%
`;
}).join('');
const forexItems = ['EUR', 'GBP', 'CHF', 'JPY'].map(currency => {
const rate = forexRates.rates[currency];
return `
USD/${currency}
${rate.toFixed(4)}
`;
}).join('');
content.innerHTML = `
Cryptocurrencies
${cryptoItems}
Forex Rates
${forexItems}
`;
updateTime.textContent = `Last updated: ${new Date().toLocaleTimeString()}`;
}
showError(message) {
const content = this.shadowRoot.getElementById('feed-content');
content.innerHTML = `${message}
`;
}
}
customElements.define('real-time-feeds', RealTimeFeeds);