Certainly! I'll help you build an HTML page with JavaScript that fetches BTCUSDC 1-minute futures prices from Binance's public API between selected dates, calculates a 99-period moving average, and creates a grid visualization as per your specifications.
Below is a step-by-step guide along with code snippets to achieve this:
Overview
-
Fetch Historical Data: Use Binance API to get 1-minute candlestick data for BTCUSDC futures between selected dates.
-
Calculate Moving Average: Compute the 99-period moving average of the closing prices.
-
Prepare Grid Data: Create data points that only register when the grid position changes based on the moving average and grid spacing.
-
Visualization: Draw the grid with the moving average as the zero point and a grid spacing of 200 units, canceling out the time variable.
1. Fetch Historical Data from Binance API
Binance provides a RESTful API to access historical Kline (candlestick) data.
API Endpoint
- Endpoint:
https://fapi.binance.com/fapi/v1/klines
Parameters
symbol: Trading pair symbol (e.g., BTCUSDC)
interval: Data interval (e.g., 1m for 1-minute data)
startTime: Start time in milliseconds
endTime: End time in milliseconds
limit: Number of data points (max 1500 per request)
Example Function to Fetch Data
async function fetchHistoricalData(symbol, interval, startTime, endTime) {
const url = `https://fapi.binance.com/fapi/v1/klines?symbol=${symbol}&interval=${interval}&startTime=${startTime}&endTime=${endTime}&limit=1500`;
const response = await fetch(url);
const data = await response.json();
return data;
}
2. Calculate the 99-Period Moving Average
We'll calculate the simple moving average (SMA) over 99 periods of the closing prices.
Function to Calculate SMA
function calculateSMA(data, period) {
let sma = [];
for (let i = 0; i < data.length; i++) {
if (i >= period - 1) {
const slice = data.slice(i - period + 1, i + 1);
const sum = slice.reduce((acc, val) => acc + parseFloat(val[4]), 0); // Close price is at index 4
sma.push(sum / period);
} else {
sma.push(null); // Not enough data to calculate SMA
}
}
return sma;
}
3. Prepare Grid Data
We need to track when the grid position changes based on the moving average and grid spacing. Only add a new data point when the grid position changes.
Function to Prepare Grid Data
function prepareGridData(data, sma, gridSpacing) {
let gridData = [];
let lastGridPosition = null;
for (let i = 0; i < data.length; i++) {
if (sma[i] !== null) {
// Calculate grid position
let gridPosition = Math.floor(sma[i] / gridSpacing);
if (gridPosition !== lastGridPosition) {
// Grid position has changed
gridData.push({
gridPosition: gridPosition,
price: parseFloat(data[i][4]), // Close price
sma: sma[i],
// Optionally store other data
});
lastGridPosition = gridPosition;
}
// If grid position doesn't change, do not add new data point
}
}
return gridData;
}
4. Visualization
We will use HTML Canvas for the visualization. Alternatively, you can use a library like Chart.js or D3.js for more complex visualizations.
Drawing the Grid
- The y-axis represents the price deviations from the moving average.
- The x-axis represents the sequence of grid position changes.
- Since time is canceled out, we're focusing on the grid movement.
Sample Visualization Code
<!DOCTYPE html>
<html>
<head>
<title>BTCUSDC Grid Visualization</title>
<style>
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="gridCanvas" width="800" height="600"></canvas>
<script>
// Place the JavaScript code here
</script>
</body>
</html>
Complete JavaScript Code
(async function() {
// Parameters
const symbol = 'BTCUSDC';
const interval = '1m';
const period = 99; // Moving average period
const gridSpacing = 200; // Grid spacing
const startTime = new Date('2023-09-01T00:00:00Z').getTime();
const endTime = new Date('2023-09-02T00:00:00Z').getTime();
// Fetch data
const rawData = await fetchHistoricalData(symbol, interval, startTime, endTime);
// Calculate SMA
const sma = calculateSMA(rawData, period);
// Prepare grid data
const gridData = prepareGridData(rawData, sma, gridSpacing);
// Visualization
const canvas = document.getElementById('gridCanvas');
const ctx = canvas.getContext('2d');
// Define scales
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
const maxDeviation = gridSpacing * 5; // Adjust as needed
const yScale = canvasHeight / (2 * maxDeviation);
const xScale = canvasWidth / gridData.length;
// Draw grid lines
function drawGrid() {
ctx.strokeStyle = '#e0e0e0';
ctx.lineWidth = 1;
// Horizontal grid lines
for (let i = -maxDeviation; i <= maxDeviation; i += gridSpacing) {
let y = canvasHeight / 2 - i * yScale;
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(canvasWidth, y);
ctx.stroke();
}
}
// Draw data points
function drawData() {
ctx.strokeStyle = '#ff0000';
ctx.lineWidth = 2;
ctx.beginPath();
for (let i = 0; i < gridData.length; i++) {
let deviation = gridData[i].price - gridData[i].sma;
let x = i * xScale;
let y = canvasHeight / 2 - deviation * yScale;
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
}
// Draw zero line (Moving Average)
function drawZeroLine() {
ctx.strokeStyle = '#000000';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0, canvasHeight / 2);
ctx.lineTo(canvasWidth, canvasHeight / 2);
ctx.stroke();
}
// Execute drawing functions
drawGrid();
drawZeroLine();
drawData();
// Optional: Add labels, axes, etc.
// Function Definitions
async function fetchHistoricalData(symbol, interval, startTime, endTime) {
let allData = [];
let limit = 1500; // Max limit per request
let fetchTime = startTime;
while (fetchTime < endTime) {
const url = `https://fapi.binance.com/fapi/v1/klines?symbol=${symbol}&interval=${interval}&startTime=${fetchTime}&endTime=${endTime}&limit=${limit}`;
const response = await fetch(url);
const data = await response.json();
if (data.length === 0) break;
allData = allData.concat(data);
fetchTime = data[data.length - 1][6] + 1; // data[i][6] is the close time
if (data.length < limit) break;
}
return allData;
}
function calculateSMA(data, period) {
let sma = [];
let sum = 0;
for (let i = 0; i < data.length; i++) {
const closePrice = parseFloat(data[i][4]);
if (i < period) {
sum += closePrice;
sma.push(null); // Not enough data yet
} else {
sum += closePrice - parseFloat(data[i - period][4]);
sma.push(sum / period);
}
}
return sma;
}
function prepareGridData(data, sma, gridSpacing) {
let gridData = [];
let lastGridPosition = null;
for (let i = 0; i < data.length; i++) {
if (sma[i] !== null) {
let gridPosition = Math.floor(sma[i] / gridSpacing);
if (gridPosition !== lastGridPosition) {
gridData.push({
gridPosition: gridPosition,
price: parseFloat(data[i][4]),
sma: sma[i],
});
lastGridPosition = gridPosition;
}
}
}
return gridData;
}
})();
Explanation
-
Data Fetching: The script fetches data in a loop to overcome the 1500 data point limit per request.
-
Moving Average Calculation: The SMA is calculated efficiently by updating the sum as we move through the data.
-
Grid Data Preparation: We only add a new point to gridData when the grid position changes (i.e., when the SMA crosses a multiple of the grid spacing).
-
Visualization:
Additional Notes
-
Time Variable Cancellation: By focusing on grid position changes and plotting deviations from the moving average, we're effectively removing the time variable from our visualization.
-
Grid Movement: The grid moves when the moving average crosses a multiple of the grid spacing (every 200 units). By plotting only when this happens, we can visualize the grid movement.
-
Styling and Enhancements:
-
You can enhance the visualization by adding axis labels, titles, and tooltips.
-
Consider adding interactivity or using a charting library if you need more advanced features.
-
Error Handling: For production code, include error handling for the API requests and data processing.
Conclusion
By following the steps above and using the provided code, you should be able to create the desired grid visualization where the center is always the moving average, and the grid spacing is 200 units. This visualization focuses on the grid movement and effectively cancels out the time variable from the price-time series.
If you have any questions or need further assistance with customizing the code or understanding any part of the implementation, feel free to ask!