Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add enhanced Bitcoin price tracker with additional features #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bitcoin Price Tracker</title>
<link rel="stylesheet" href="styles.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
</head>
<body>
<div class="container">
<h1>Bitcoin Price Tracker</h1>
<div class="price-container">
<div id="price">Loading...</div>
<div id="price-change"></div>
</div>
<div id="timestamp"></div>

<div class="stats-container">
<div class="stat">
<label>24h High</label>
<span id="high-price">-</span>
</div>
<div class="stat">
<label>24h Low</label>
<span id="low-price">-</span>
</div>
<div class="stat">
<label>24h Change</label>
<span id="day-change">-</span>
</div>
</div>

<div class="chart-container">
<canvas id="priceChart"></canvas>
</div>

<div class="settings">
<h3>Price Alerts</h3>
<div class="alert-settings">
<input type="number" id="alertPrice" placeholder="Alert price in USD">
<button onclick="tracker.setAlert()">Set Alert</button>
</div>
</div>
</div>
<script src="tracker.js"></script>
</body>
</html>
118 changes: 118 additions & 0 deletions styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f0f2f5;
}

.container {
max-width: 800px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

h1 {
text-align: center;
color: #333;
margin-bottom: 30px;
}

.price-container {
text-align: center;
margin-bottom: 20px;
}

#price {
font-size: 48px;
font-weight: bold;
color: #f7931a;
}

#price-change {
font-size: 18px;
margin-top: 5px;
}

#timestamp {
text-align: center;
color: #666;
font-size: 14px;
margin-bottom: 20px;
}

.stats-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
margin-bottom: 30px;
padding: 20px;
background-color: #f8f9fa;
border-radius: 8px;
}

.stat {
text-align: center;
}

.stat label {
display: block;
color: #666;
margin-bottom: 5px;
}

.stat span {
font-size: 20px;
font-weight: bold;
color: #333;
}

.chart-container {
margin-bottom: 30px;
padding: 20px;
background-color: white;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
height: 300px;
}

.settings {
padding: 20px;
background-color: #f8f9fa;
border-radius: 8px;
}

.alert-settings {
display: flex;
gap: 10px;
}

input {
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
flex: 1;
}

button {
padding: 8px 16px;
background-color: #f7931a;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}

button:hover {
background-color: #e88a0c;
}

.price-up {
color: #28a745;
}

.price-down {
color: #dc3545;
}
169 changes: 147 additions & 22 deletions tracker.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,147 @@
// Bitcoin Price Tracker

const fetchBitcoinPrice = async () => {
try {
const response = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd');
const data = await response.json();
const price = data.bitcoin.usd;

// Update the UI
document.getElementById('price').textContent = `$${price.toLocaleString()}`;
document.getElementById('timestamp').textContent = new Date().toLocaleString();
} catch (error) {
console.error('Error fetching Bitcoin price:', error);
document.getElementById('price').textContent = 'Error fetching price';
}
};

// Fetch initial price
fetchBitcoinPrice();

// Update price every 2 minutes
setInterval(fetchBitcoinPrice, 120000);
class BitcoinPriceTracker {
constructor() {
this.priceHistory = [];
this.maxHistoryPoints = 24;
this.chart = null;
this.alertPrice = null;
this.initializeChart();
this.loadStoredData();
this.startTracking();
}

loadStoredData() {
const stored = localStorage.getItem('btcPriceHistory');
if (stored) {
this.priceHistory = JSON.parse(stored);
this.updateChart();
this.updateStats();
}
}

saveData() {
localStorage.setItem('btcPriceHistory', JSON.stringify(this.priceHistory));
}

initializeChart() {
const ctx = document.getElementById('priceChart').getContext('2d');
this.chart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Bitcoin Price (USD)',
data: [],
borderColor: '#f7931a',
borderWidth: 2,
fill: false,
tension: 0.1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: false
}
}
}
});
}

async fetchPrice() {
try {
const response = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd');
const data = await response.json();
return data.bitcoin.usd;
} catch (error) {
console.error('Error fetching Bitcoin price:', error);
throw error;
}
}

updateChart() {
const labels = this.priceHistory.map(item =>
new Date(item.timestamp).toLocaleTimeString()
);
const prices = this.priceHistory.map(item => item.price);

this.chart.data.labels = labels;
this.chart.data.datasets[0].data = prices;
this.chart.update();
}

updateStats() {
if (this.priceHistory.length > 0) {
const prices = this.priceHistory.map(item => item.price);
const lastPrice = prices[prices.length - 1];
const prevPrice = prices.length > 1 ? prices[prices.length - 2] : lastPrice;

// Update price and change
document.getElementById('price').textContent = `$${lastPrice.toLocaleString()}`;

// Calculate 24h stats
const highPrice = Math.max(...prices);
const lowPrice = Math.min(...prices);
const dayChange = ((lastPrice - prices[0]) / prices[0] * 100).toFixed(2);

// Update UI
document.getElementById('high-price').textContent = `$${highPrice.toLocaleString()}`;
document.getElementById('low-price').textContent = `$${lowPrice.toLocaleString()}`;
document.getElementById('day-change').textContent = `${dayChange}%`;

// Add color coding
document.getElementById('day-change').className = dayChange >= 0 ? 'price-up' : 'price-down';
}
}

setAlert() {
const input = document.getElementById('alertPrice');
const price = parseFloat(input.value);
if (!isNaN(price) && price > 0) {
this.alertPrice = price;
alert(`Alert set for $${price.toLocaleString()}`);
input.value = '';
}
}

checkAlert(price) {
if (this.alertPrice !== null) {
if ((this.alertPrice > price && this.priceHistory[this.priceHistory.length - 2]?.price < this.alertPrice) ||
(this.alertPrice < price && this.priceHistory[this.priceHistory.length - 2]?.price > this.alertPrice)) {
alert(`Bitcoin price has crossed $${this.alertPrice.toLocaleString()}!\nCurrent price: $${price.toLocaleString()}`);
this.alertPrice = null;
}
}
}

async startTracking() {
try {
const price = await this.fetchPrice();

this.priceHistory.push({
price,
timestamp: new Date().toISOString()
});

// Keep only last maxHistoryPoints
if (this.priceHistory.length > this.maxHistoryPoints) {
this.priceHistory.shift();
}

this.updateChart();
this.updateStats();
this.saveData();
this.checkAlert(price);

} catch (error) {
document.getElementById('price').textContent = 'Error fetching price';
}

// Update every 2 minutes
setTimeout(() => this.startTracking(), 120000);
}
}

// Initialize tracker
const tracker = new BitcoinPriceTracker();