In this tutorial, we’ll learn how to create a simple live-updating Bitcoin price chart using the Binance API. This straightforward guide will cover all the necessary HTML, JavaScript, and CSS code required to get started with real-time cryptocurrency price tracking.
You don’t need much for this tutorial: β
- Basic understanding of HTML, CSS, and JavaScript.
- A modern web browser.
We’ll create a single HTML document that includes inline JavaScript and CSS. This approach ensures that you can easily copy, paste, and run the example without managing multiple files.
π Execution: To run the Bitcoin price checker, copy the entire HTML code into a file with a .html extension. Open this file in any modern web browser to see the live Bitcoin price updating every few seconds.
You can see it live right here:
Here’s the full HTML document with embedded CSS and JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Bitcoin Price Chart</title>
<style>
body {
font-family: Arial, sans-serif;
}
#chartContainer {
height: 300px;
width: 100%;
margin: 20px auto;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div id="chartContainer"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script>
let priceDataPoints = [];
function updateChartData() {
fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
.then(response => response.json())
.then(data => {
const btcPrice = parseFloat(data.price);
const currentTime = new Date();
priceDataPoints.push({ x: currentTime, y: btcPrice });
if (priceDataPoints.length > 20) {
priceDataPoints.shift();
}
updateChart();
}).catch(error => console.error("Error fetching BTC price:", error));
}
function updateChart() {
let chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Live Bitcoin Price"
},
axisX: {
title: "Time",
valueFormatString: "HH:mm:ss",
labelAngle: -30
},
axisY: {
title: "Price (USD)",
includeZero: false,
prefix: "$"
},
data: [{
type: "line",
xValueType: "dateTime",
dataPoints: priceDataPoints
}]
});
chart.render();
}
updateChartData(); // Initial call to populate the chart
setInterval(updateChartData, 5000); // Update chart every 5 seconds
</script>
</body>
</html>The code works as follows:
HTML Structure: We have a div element where the chart will be displayed.
CSS Styling: Simple styles are applied to ensure the chart container is visually defined.
JavaScript for Live Data:
- Fetching Data: The JavaScript uses the
fetchAPI to pull live Bitcoin prices from Binance’s public API endpoint. - Updating the Chart: We use CanvasJS (a third-party library) to render the price chart. New data points are added every 5 seconds, and the oldest data points are removed to keep the chart clean and readable.
- CanvasJS Library: This is a powerful and easy-to-use chart library, which we include from a CDN. It simplifies drawing the live chart.
