Sure! Below is an HTML file that fetches BTCUSDC 1-minute prices between selected dates (with default dates of November 1, 2024, to November 5, 2024), calculates a 99-point moving average, its first derivative, and its second derivative, and then plots these on a chart using Chart.js.
Please note:
- Since the dates are in the future (as of my knowledge cutoff in 2023-10), actual future data won't be available. For demonstration purposes, you might need to adjust the dates to a past timeframe where data is available.
- The Binance API is used to fetch the BTCUSDC data.
- Chart.js library is used for plotting the data.
Here's the complete HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BTCUSDC Moving Average and Derivatives</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<h1>BTCUSDC Moving Average and Derivatives</h1>
<label for="startDate">Start Date:</label>
<input type="date" id="startDate" value="2024-11-01">
<label for="endDate">End Date:</label>
<input type="date" id="endDate" value="2024-11-05">
<button id="fetchData">Fetch Data</button>
<canvas id="chart" width="800" height="400"></canvas>
<script>
document.getElementById('fetchData').addEventListener('click', function() {
main();
});
async function main() {
const startDateInput = document.getElementById('startDate').value;
const endDateInput = document.getElementById('endDate').value;
// Convert dates to Unix timestamps in milliseconds
const startTime = new Date(startDateInput).getTime();
const endTime = new Date(endDateInput).getTime();
// Fetch BTCUSDC 1-minute prices from Binance API
const symbol = 'BTCUSDC';
const interval = '1m';
const klines = await fetchKlines(symbol, interval, startTime, endTime);
// Extract closing prices and timestamps
const timestamps = klines.map(k => k[0]); // Open time
const closePrices = klines.map(k => parseFloat(k[4])); // Close price
// Calculate 99-point moving average
const ma99 = movingAverage(closePrices, 99);
// Calculate first derivative of MA99
const derivative = firstDerivative(ma99);
// Calculate second derivative of MA99
const secondDerivative = firstDerivative(derivative);
// Prepare data for plotting
const labels = timestamps.slice(98).map(ts => new Date(ts).toLocaleString());
const ma99Data = ma99.slice(98); // Align data
const derivativeData = derivative.slice(98);
const secondDerivativeData = secondDerivative.slice(98);
// Plot the data
plotData(labels, ma99Data, derivativeData, secondDerivativeData);
}
async function fetchKlines(symbol, interval, startTime, endTime) {
const limit = 1000; // Max limit per request
let klines = [];
let fetchTime = startTime;
while (fetchTime < endTime) {
const url = `https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=${interval}&startTime=${fetchTime}&endTime=${endTime}&limit=${limit}`;
const response = await fetch(url);
const data = await response.json();
if (data.code) {
// Handle error
alert('Error fetching data: ' + data.msg);
break;
}
if (data.length === 0) {
break;
}
klines = klines.concat(data);
fetchTime = data[data.length - 1][0] + 60000; // Next minute
}
return klines;
}
function movingAverage(data, windowSize) {
let ma = [];
for (let i = 0; i < data.length; i++) {
if (i < windowSize - 1) {
ma.push(null); // Not enough data to calculate MA
} else {
const windowData = data.slice(i - windowSize + 1, i + 1);
const sum = windowData.reduce((acc, val) => acc + val, 0);
ma.push(sum / windowSize);
}
}
return ma;
}
function firstDerivative(data) {
let derivative = [];
for (let i = 0; i < data.length; i++) {
if (i === 0 || data[i - 1] === null || data[i] === null) {
derivative.push(null); // Cannot calculate derivative
} else {
derivative.push(data[i] - data[i - 1]);
}
}
return derivative;
}
function plotData(labels, ma99Data, derivativeData, secondDerivativeData) {
const ctx = document.getElementById('chart').getContext('2d');
// Clear existing chart if any
if (window.myChart instanceof Chart) {
window.myChart.destroy();
}
window.myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: 'Moving Average (99)',
data: ma99Data,
borderColor: 'blue',
fill: false,
yAxisID: 'y',
},
{
label: 'First Derivative',
data: derivativeData,
borderColor: 'green',
fill: false,
yAxisID: 'y1',
},
{
label: 'Second Derivative',
data: secondDerivativeData,
borderColor: 'red',
fill: false,
yAxisID: 'y1',
}
]
},
options: {
responsive: true,
scales: {
x: {
display: true,
ticks: {
maxRotation: 90,
minRotation: 90,
maxTicksLimit: 20,
}
},
y: {
type: 'linear',
display: true,
position: 'left',
title: {
display: true,
text: 'Price / Moving Average'
}
},
y1: {
type: 'linear',
display: true,
position: 'right',
grid: {
drawOnChartArea: false,
},
title: {
display: true,
text: 'Derivatives'
}
}
}
}
});
}
// Automatically fetch data on page load
main();
</script>
</body>
</html>
Instructions:
-
Save the code: Copy the above code into a text editor and save it as an HTML file, e.g., btc_ma_derivatives.html.
-
Open in a Browser: Open the saved HTML file in a modern web browser (e.g., Chrome, Firefox).
-
Adjust Dates if Necessary: If you're testing before November 2024, adjust the value attributes of the startDate and endDate inputs to dates where data is available.
-
Fetch Data: Click the "Fetch Data" button to retrieve the data and generate the chart.
Explanation:
-
Date Inputs: Two date inputs allow you to select the start and end dates for fetching data. Default dates are set to November 1, 2024, and November 5, 2024.
-
Data Fetching:
-
The fetchKlines function retrieves BTCUSDC 1-minute klines (candlestick data) from the Binance API between the selected dates.
-
Binance API limits each request to 1000 data points, so the function loops as needed to fetch all data within the date range.
-
Calculations:
-
The movingAverage function calculates the 99-point moving average of the closing prices.
-
The firstDerivative function calculates the derivative by computing the difference between consecutive points.
-
The second derivative is calculated by applying the firstDerivative function to the first derivative data.
-
Plotting:
-
The plotData function uses Chart.js to plot the moving average, first derivative, and second derivative on the same chart.
-
Two Y-axes are used: one for the moving average (price) on the left and one for the derivatives on the right.
-
Automatic Data Fetching:
- The
main function is called automatically on page load to fetch and display data immediately.
Note: Since future data cannot be fetched, you should adjust the default dates to a recent past period where data is available.