in html, get btcusdc 1m prices from binance api between selected dates (default start date; 1-11-2024). then calculate moving average 99. after that calculate the sum between price curve and ma99 curve (if price is smaller than ma99, sum element is negative). lastly, calculate the derivative of the sum curve. draw price, ma99, sum, and derivative of the sum on same graph.
Assistant
Certainly! Below is an HTML page that fetches BTC/USDC 1-minute price data from the Binance API between selected dates (default start date: November 1, 2023). It calculates the 99-period moving average, computes the cumulative sum of the differences between the price and the moving average (assigning negative values when the price is below the moving average), calculates the derivative of the sum curve, and finally plots all four datasets on the same graph.
For the charting, we'll use the Chart.js library, which is a simple yet powerful JavaScript library for data visualization.
Note: To ensure this code works seamlessly, please make sure you have a stable internet connection and that your browser allows CORS requests to the Binance API.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BTC/USDC Price Analysis</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<h1>BTC/USDC Price Analysis</h1>
<label for="start-date">Start Date:</label>
<input type="datetime-local" id="start-date">
<label for="end-date">End Date:</label>
<input type="datetime-local" id="end-date">
<button id="fetch-data">Fetch Data</button>
<canvas id="myChart" width="1000" height="600"></canvas>
<script>
document.getElementById('start-date').value = new Date('2023-11-01T00:00').toISOString().slice(0,16);
document.getElementById('end-date').value = new Date().toISOString().slice(0,16);
document.getElementById('fetch-data').addEventListener('click', function() {
const startDate = new Date(document.getElementById('start-date').value);
const endDate = new Date(document.getElementById('end-date').value);
fetchAndPlotData(startDate, endDate);
});
async function fetchAndPlotData(startDate, endDate) {
const apiUrl = 'https://api.binance.com/api/v3/klines';
const symbol = 'BTCUSDC';
const interval = '1m';
const startTime = startDate.getTime();
const endTime = endDate.getTime();
let allData = [];
let fetchStartTime = startTime;
const limit = 1000; // Max limit per API request
while (fetchStartTime < endTime) {
const url = `${apiUrl}?symbol=${symbol}&interval=${interval}&startTime=${fetchStartTime}&endTime=${endTime}&limit=${limit}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
if (data.length === 0) {
break;
}
allData = allData.concat(data);
fetchStartTime = data[data.length - 1][0] + 60000; // Move to next minute
} catch (error) {
console.error('Error fetching data:', error);
break;
}
// Respect API rate limits
await new Promise(resolve => setTimeout(resolve, 500));
}
if (allData.length === 0) {
alert('No data fetched for the selected date range.');
return;
}
processAndPlotData(allData);
}
function processAndPlotData(data) {
const prices = data.map(item => parseFloat(item[4])); // Closing prices
const times = data.map(item => new Date(item[0]));
// Calculate 99-period moving average
const ma99 = [];
for (let i = 0; i < prices.length; i++) {
if (i < 98) {
ma99.push(null); // Not enough data to calculate MA
} else {
const sum = prices.slice(i - 98, i + 1).reduce((a, b) => a + b, 0);
ma99.push(sum / 99);
}
}
// Calculate cumulative sum between price and ma99
let cumulativeSum = [];
let sum = 0;
for (let i = 0; i < prices.length; i++) {
if (ma99[i] === null) {
cumulativeSum.push(null);
continue;
}
const diff = prices[i] - ma99[i];
sum += diff;
cumulativeSum.push(sum);
}
// Calculate derivative of the cumulative sum
const derivative = [];
for (let i = 0; i < cumulativeSum.length; i++) {
if (i === 0 || cumulativeSum[i] === null || cumulativeSum[i - 1] === null) {
derivative.push(null);
} else {
derivative.push(cumulativeSum[i] - cumulativeSum[i - 1]);
}
}
plotChart(times, prices, ma99, cumulativeSum, derivative);
}
function plotChart(times, prices, ma99, cumulativeSum, derivative) {
const ctx = document.getElementById('myChart').getContext('2d');
// Clean previous chart
if (window.myChart) {
window.myChart.destroy();
}
window.myChart = new Chart(ctx, {
type: 'line',
data: {
labels: times,
datasets: [
{
label: 'Price',
data: prices,
borderColor: 'blue',
fill: false,
yAxisID: 'y1',
},
{
label: 'MA99',
data: ma99,
borderColor: 'orange',
fill: false,
yAxisID: 'y1',
},
{
label: 'Cumulative Sum',
data: cumulativeSum,
borderColor: 'green',
fill: false,
yAxisID: 'y2',
},
{
label: 'Derivative of Sum',
data: derivative,
borderColor: 'red',
fill: false,
yAxisID: 'y2',
}
]
},
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'hour'
}
},
y1: {
type: 'linear',
position: 'left',
title: {
display: true,
text: 'Price'
}
},
y2: {
type: 'linear',
position: 'right',
title: {
display: true,
text: 'Sum / Derivative'
},
grid: {
drawOnChartArea: false
}
}
},
plugins: {
tooltip: {
mode: 'index',
intersect: false,
},
zoom: {
pan: {
enabled: true,
mode: 'x',
},
zoom: {
enabled: true,
mode: 'x',
}
}
},
interaction: {
mode: 'index',
intersect: false,
}
}
});
}
// Fetch data on page load with default dates
(function(){
const startDate = new Date(document.getElementById('start-date').value);
const endDate = new Date(document.getElementById('end-date').value);
fetchAndPlotData(startDate, endDate);
})();
</script>
</body>
</html>
Explanation:
HTML Structure: The page contains two date-time input fields for selecting the start and end dates, a button to fetch the data, and a canvas element where the chart will be rendered.
Default Dates: The start date is set to November 1, 2023, and the end date defaults to the current date and time.
Data Fetching:
The fetchAndPlotData function handles fetching data from the Binance API. Since the API returns a maximum of 1000 data points per request, we loop and fetch data in chunks until we've covered the entire date range.
We use fetch to make HTTP requests to the Binance API, construct the URL with the necessary query parameters, and handle potential errors.
We include a delay of 500 milliseconds between requests to respect the API rate limits.
Data Processing:
After fetching the data, we extract the closing prices and timestamps.
We calculate the 99-period moving average (ma99) by iterating through the price array and computing the average of the current price and the previous 98 prices.
We compute the cumulative sum of the differences between the price and the moving average, assigning negative values when the price is below the moving average.
The derivative of the sum curve is calculated by finding the difference between consecutive cumulative sum values.
Chart Plotting:
We use Chart.js to plot the data. The chart displays four datasets: Price, MA99, Cumulative Sum, and Derivative of Sum.
We use two y-axes to accommodate datasets with different scales: one for Price and MA99, and another for Cumulative Sum and Derivative.
The x-axis is a time axis, and we format it to display time units appropriately.
Interactivity:
The chart includes tooltips that show data values when hovering.
Users can zoom and pan through the data for a closer look.
Notes:
Ensure that your browser allows cross-origin requests to the Binance API. If you encounter CORS issues, you might need to use a CORS proxy or run the code on a local server.
The Binance API has rate limits. In this code, we include a delay between requests to prevent hitting the limits.
Example Usage:
Open the HTML file in a modern web browser.
Adjust the start and end dates if desired, using the date-time pickers.
Click the "Fetch Data" button to retrieve and display the data.
Disclaimer: The above code is for educational purposes. Always make sure to comply with the API's terms of service when fetching data.