"<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>BTCUSDC Moving…
- User
"
code - Assistant
"
<script>
// Function to initialize the default behavior on page load
window.onload = function() {
main();
};
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);
if (klines.length === 0) {
alert('No data available for the selected date range.');
return;
}
// 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 priceData = closePrices.slice(98); // Align data
const ma99Data = ma99.slice(98);
const derivativeData = derivative.slice(98);
const secondDerivativeData = secondDerivative.slice(98);
// Plot the data
plotData(labels, priceData, 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, priceData, ma99Data, derivativeData, secondDerivativeData) {
const ctx = document.getElementById('chart').getContext('2d');
// Create an array of zeros for the zero line
const zeroData = labels.map(() => 0);
// Clear existing chart if any
if (window.myChart instanceof Chart) {
window.myChart.destroy();
}
// Register the zoom plugin (necessary in Chart.js v4)
Chart.register(ChartZoom);
window.myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: 'Actual Price',
data: priceData,
borderColor: 'black',
fill: false,
yAxisID: 'y',
},
{
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',
},
// Add the zero line for derivative axis
{
label: 'Derivative Zero Line',
data: zeroData,
borderColor: 'gray',
borderDash: [5, 5],
pointRadius: 0,
borderWidth: 1,
fill: false,
yAxisID: 'y1',
}
]
},
options: {
responsive: true,
interaction: {
mode: 'index',
intersect: false,
},
stacked: false,
plugins: {
zoom: {
pan: {
enabled: true,
mode: 'x',
modifierKey: null, // Allows panning without modifier key
},
zoom: {
wheel: {
enabled: true,
},
pinch: {
enabled: true,
},
mode: 'x',
},
},
},
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'
}
}
}
}
});
// Add double-click event listener to reset zoom
const canvas = document.getElementById('chart');
canvas.addEventListener('dblclick', function(){
window.myChart.resetZoom();
});
}
// Automatically fetch data on page load
// (Already called inside window.onload)
</script>
To add a dot on the actual price point when the derivative is smaller than -5 and the second derivative is greater than 0, you'll need to modify your existing code slightly. Specifically, you'll create a new dataset that highlights these special points on your chart. Here's how you can do it:
Calculate Special Points: After preparing your data arrays, create a new array (specialPointsData) to identify and store the price points where the derivative and second derivative meet your specified conditions.
Add a New Dataset: Introduce a new dataset in your chart configuration that uses the specialPointsData array. This dataset will plot dots on your chart at the specified points.
Here's the step-by-step modification:
1. Update the plotData Function
In your plotData() function, after you prepare your data arrays (labels, priceData, ma99Data, derivativeData, secondDerivativeData), add the following code to calculate specialPointsData:
// Create specialPointsData where derivative < -5 and secondDerivative > 0
let specialPointsData = [];
for (let i = 0; i < priceData.length; i++) {
if (
derivativeData[i] !== null &&
secondDerivativeData[i] !== null &&
derivativeData[i] < -5 &&
secondDerivativeData[i] > 0
) {
specialPointsData.push(priceData[i]); // Include the price at this index
} else {
specialPointsData.push(null); // No data point at this index
}
}
This loop goes through each index of your data arrays and checks if the conditions are met. If they are, it adds the corresponding price to specialPointsData; otherwise, it adds null.
2. Modify the Chart Configuration
In the datasets array within your new Chart(...) configuration, add a new dataset for the special points. Also, you might want to set pointRadius: 0 for your existing line datasets to prevent default points from showing up.
Here's the modified datasets array:
datasets: [
{
label: 'Actual Price',
data: priceData,
borderColor: 'black',
fill: false,
yAxisID: 'y',
pointRadius: 0, // Prevent default points
},
{
label: 'Moving Average (99)',
data: ma99Data,
borderColor: 'blue',
fill: false,
yAxisID: 'y',
pointRadius: 0,
},
{
label: 'First Derivative',
data: derivativeData,
borderColor: 'green',
fill: false,
yAxisID: 'y1',
pointRadius: 0,
},
{
label: 'Second Derivative',
data: secondDerivativeData,
borderColor: 'red',
fill: false,
yAxisID: 'y1',
pointRadius: 0,
},
// Add the zero line for derivative axis
{
label: 'Derivative Zero Line',
data: zeroData,
borderColor: 'gray',
borderDash: [5, 5],
pointRadius: 0,
borderWidth: 1,
fill: false,
yAxisID: 'y1',
},
// New dataset for special points
{
label: 'Special Points',
data: specialPointsData,
borderColor: 'purple',
backgroundColor: 'purple',
pointRadius: 5, // Size of the dot
pointHoverRadius: 7,
showLine: false,
yAxisID: 'y',
type: 'line', // Ensure it aligns with the chart type
},
]
Explanation of the New Dataset Configurations:
specialPointsData - Uses the array you created to plot points where conditions are met.3. Result
With these changes, your chart will now display purple dots on the actual price line wherever the derivative is less than -5 and the second derivative is greater than 0. These visual markers will help you quickly identify points of interest on your chart.
Complete Modified plotData Function:
Here's how the entire plotData function should look after your modifications:
4. Test Your Chart
After making these changes, save your HTML file and refresh the page. Input your desired start and end dates, and click "Fetch Data". Your chart should now display the special points as purple dots where the conditions are met.
By following these steps, you've enhanced your chart to visually indicate significant points based on the derivative conditions, making it a more powerful tool for analysis.
Not yet included in a published release.
function plotData(labels, priceData, ma99Data, derivativeData, secondDerivativeData) {
const ctx = document.getElementById('chart').getContext('2d');
// Create an array of zeros for the zero line
const zeroData = labels.map(() => 0);
// Create specialPointsData where derivative < -5 and secondDerivative > 0
let specialPointsData = [];
for (let i = 0; i < priceData.length; i++) {
if (
derivativeData[i] !== null &&
secondDerivativeData[i] !== null &&
derivativeData[i] < -5 &&
secondDerivativeData[i] > 0
) {
specialPointsData.push(priceData[i]);
} else {
specialPointsData.push(null);
}
}
// Clear existing chart if any
if (window.myChart instanceof Chart) {
window.myChart.destroy();
}
// Register the zoom plugin (necessary in Chart.js v4)
Chart.register(ChartZoom);
window.myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: 'Actual Price',
data: priceData,
borderColor: 'black',
fill: false,
yAxisID: 'y',
pointRadius: 0,
},
{
label: 'Moving Average (99)',
data: ma99Data,
borderColor: 'blue',
fill: false,
yAxisID: 'y',
pointRadius: 0,
},
{
label: 'First Derivative',
data: derivativeData,
borderColor: 'green',
fill: false,
yAxisID: 'y1',
pointRadius: 0,
},
{
label: 'Second Derivative',
data: secondDerivativeData,
borderColor: 'red',
fill: false,
yAxisID: 'y1',
pointRadius: 0,
},
// Add the zero line for derivative axis
{
label: 'Derivative Zero Line',
data: zeroData,
borderColor: 'gray',
borderDash: [5, 5],
pointRadius: 0,
borderWidth: 1,
fill: false,
yAxisID: 'y1',
},
// New dataset for special points
{
label: 'Special Points',
data: specialPointsData,
borderColor: 'purple',
backgroundColor: 'purple',
pointRadius: 5,
pointHoverRadius: 7,
showLine: false,
yAxisID: 'y',
type: 'line',
},
]
},
options: {
responsive: true,
interaction: {
mode: 'index',
intersect: false,
},
stacked: false,
plugins: {
zoom: {
pan: {
enabled: true,
mode: 'x',
modifierKey: null, // Allows panning without modifier key
},
zoom: {
wheel: {
enabled: true,
},
pinch: {
enabled: true,
},
mode: 'x',
},
},
},
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'
}
}
}
}
});
// Add double-click event listener to reset zoom
const canvas = document.getElementById('chart');
canvas.addEventListener('dblclick', function(){
window.myChart.resetZoom();
});
}