in html, get btcusdc 1m price between selected dates (default dates are 1 11 2024 and 5…
- User
in html, get btcusdc 1m price between selected dates (default dates are 1 11 2024 and 5 11 2024) from binance api. calculate moving average 99. then calculate sum between price curve and ma99 curve with window 99 (if price is below ma99 then it means a negative sum element). then, i want you to find the derivative of the sum curve. lastly, draw actual price, ma99, sum, and derivative of sum. i need this to done in one page html
- Assistant
Certainly! Below is an HTML page that fetches BTCUSDC 1-minute price data between selected dates (default dates are November 1, 2023, and November 5, 2023) from the Binance API. It calculates the 99-period moving average (MA99), computes the sum between the price curve and MA99 with a window of 99 (considering negative sums when the price is below MA99), finds the derivative of the sum curve, and finally plots the actual price, MA99, sum, and derivative of the sum.
You can save this code as an
.htmlfile and open it in your web browser to see it in action.<!DOCTYPE html> <html> <head> <title>BTCUSDC Price Analysis</title> <!-- Include Plotly.js library via CDN --> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <h1>BTCUSDC Price Analysis</h1> <p>Analyze BTCUSDC 1-minute price data between selected dates.</p> <!-- Date selection inputs --> <label for="startDate">From:</label> <input type="date" id="startDate" value="2023-11-01"> <label for="endDate">To:</label> <input type="date" id="endDate" value="2023-11-05"> <button id="fetchData">Fetch Data</button> <!-- Divs for plots --> <div id="priceChart"></div> <div id="sumChart"></div> <div id="derivativeChart"></div> <script> // Add an event listener to the "Fetch Data" button document.getElementById('fetchData').addEventListener('click', function() { // Get the start and end dates from the input fields let startDateInput = document.getElementById('startDate').value; let endDateInput = document.getElementById('endDate').value; // Convert the dates to timestamps in milliseconds let startTime = new Date(startDateInput).getTime(); let endTime = new Date(endDateInput).getTime(); // Check that the start date is before the end date if (startTime >= endTime) { alert('Start date must be before end date.'); return; } // Fetch the data using the provided dates fetchData(startTime, endTime); }); async function fetchData(startTime, endTime) { // Binance API parameters let symbol = 'BTCUSDC'; let interval = '1m'; let limit = 1000; // Maximum limit per request let klines = []; // Array to hold the candlestick data let currentTime = startTime; // Start time for fetching data // Fetch data in a loop to handle API limitations while (currentTime < endTime) { // Construct the API URL with the required parameters let url = `https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=${interval}&startTime=${currentTime}&endTime=${endTime}&limit=${limit}`; try { let response = await fetch(url); let data = await response.json(); if (data && data.length > 0) { // Append the fetched data to the klines array klines = klines.concat(data); currentTime = data[data.length - 1][0] + 60000; // Move to the next data point (add 1 minute) // Break the loop if we have fetched all data or there's less data than the limit if (currentTime > endTime || data.length < limit) break; } else { break; } } catch (error) { console.error('Error fetching data:', error); break; } } // Process the fetched data processData(klines); } function processData(klines) { // Arrays to hold timestamps and prices let timestamps = []; let prices = []; // Extract the closing price and timestamp from each kline klines.forEach(kline => { let time = kline[0]; let closePrice = parseFloat(kline[4]); timestamps.push(new Date(time)); prices.push(closePrice); }); // Calculate the 99-period moving average (MA99) let ma99 = calculateMA(prices, 99); // Calculate the sum between price and MA99 with window 99 let sumDiff = calculateSumDiff(prices, ma99, 99); // Calculate the derivative of the sum curve let derivativeSum = calculateDerivative(sumDiff); // Plot the data plotData(timestamps, prices, ma99, sumDiff, derivativeSum); } function calculateMA(prices, windowSize) { let ma = []; let sum = 0; for (let i = 0; i < prices.length; i++) { sum += prices[i]; if (i >= windowSize) { sum -= prices[i - windowSize]; ma.push(sum / windowSize); } else if (i === windowSize - 1) { ma.push(sum / windowSize); } else { ma.push(null); // Not enough data to calculate MA } } return ma; } function calculateSumDiff(prices, ma, windowSize) { let sumDiff = []; let sum = 0; for (let i = 0; i < prices.length; i++) { let diff = (prices[i] - ma[i]) || 0; if (i >= windowSize) { let prevDiff = (prices[i - windowSize] - ma[i - windowSize]) || 0; sum = sum + diff - prevDiff; sumDiff.push(sum); } else if (i === windowSize - 1) { for (let j = i - windowSize + 1; j <= i; j++) { let tempDiff = (prices[j] - ma[j]) || 0; sum += tempDiff; } sumDiff.push(sum); } else { sumDiff.push(null); } } return sumDiff; } function calculateDerivative(data) { let derivative = []; for (let i = 0; i < data.length; i++) { if (i == 0 || data[i - 1] === null || data[i] === null) { derivative.push(null); } else { derivative.push(data[i] - data[i - 1]); } } return derivative; } function plotData(timestamps, prices, ma99, sumDiff, derivativeSum) { // Plot actual price and MA99 let tracePrice = { x: timestamps, y: prices, name: 'Price', mode: 'lines', type: 'scatter' }; let traceMA99 = { x: timestamps, y: ma99, name: 'MA99', mode: 'lines', type: 'scatter' }; let layoutPrice = { title: 'BTCUSDC Price and MA99', xaxis: { title: 'Time' }, yaxis: { title: 'Price' } }; // Plot the actual price and MA99 on the same chart Plotly.newPlot('priceChart', [tracePrice, traceMA99], layoutPrice); // Plot SumDiff let traceSumDiff = { x: timestamps, y: sumDiff, name: 'Sum', mode: 'lines', type: 'scatter' }; let layoutSum = { title: 'Sum between Price and MA99 with window 99', xaxis: { title: 'Time' }, yaxis: { title: 'Sum' } }; // Plot the sum between price and MA99 Plotly.newPlot('sumChart', [traceSumDiff], layoutSum); // Plot derivative of Sum let traceDerivative = { x: timestamps, y: derivativeSum, name: 'Derivative of Sum', mode: 'lines', type: 'scatter' }; let layoutDerivative = { title: 'Derivative of Sum', xaxis: { title: 'Time' }, yaxis: { title: 'Derivative' } }; // Plot the derivative of the sum Plotly.newPlot('derivativeChart', [traceDerivative], layoutDerivative); } </script> </body> </html>Explanation of the Code:
-
HTML Structure:
- Includes date inputs for selecting the start and end dates, with default dates set to November 1, 2023, and November 5, 2023.
- Includes three
<div>elements where the plots will be rendered. - The Plotly.js library is included via a CDN link to handle the plotting.
-
JavaScript Functionality:
- Event Listener: Attached to the "Fetch Data" button to initiate data fetching when clicked.
- Data Fetching (
fetchData): Uses the Binance API to fetch BTCUSDC 1-minute interval price data between the selected dates. It handles the API's limit on the number of data points per request by fetching data in chunks. - Data Processing (
processData):- Extracts timestamps and closing prices from the fetched data.
- Calculates the 99-period moving average (MA99) using
calculateMA. - Calculates the sum between the price and MA99 over a window of 99 using
calculateSumDiff, considering negative values when the price is below the MA99. - Calculates the derivative of the sum using
calculateDerivative.
- Plotting (
plotData): Uses Plotly to plot:- The actual price and MA99 on the same chart.
- The sum between the price and MA99.
- The derivative of the sum.
How to Use the Page:
- Select Dates (Optional): You can adjust the dates by clicking on the date inputs. By default, the dates are set from November 1, 2023, to November 5, 2023.
- Fetch Data: Click the "Fetch Data" button to start the analysis.
- View Plots: Once the data is fetched and processed, the plots will be displayed in the corresponding sections:
- BTCUSDC Price and MA99: Shows the actual price and the 99-period moving average.
- Sum between Price and MA99 with window 99: Displays the cumulative sum of differences between the price and MA99 over a window of 99 periods.
- Derivative of Sum: Shows the derivative (rate of change) of the sum curve.
Note:
- The Binance API has limitations on the amount of data you can fetch per request and rate limits. This code handles the data fetching in chunks of 1000 data points to comply with the API limitations.
- Ensure you have a stable internet connection when using this page, as it needs to fetch data from the Binance API.
- Depending on your browser and security settings, you might run into CORS issues when making cross-origin requests to the Binance API. If that's the case, you may need to run the page through a local server or adjust your browser settings.
Example Preview:
[image: BTCUSDC Price and MA99] open [image: Sum between Price and MA99] open [image: Derivative of Sum] open
(Images are for illustrative purposes and may not reflect real data.)
This code should fulfill your requirements to fetch BTCUSDC data, perform the necessary calculations, and display the results all within a single HTML page.
-