Here's an HTML code that fetches BTC/USDC 8-hour prices from the Binance API between selected dates, calculates the 39-period moving average, implements the specified DCA strategy, and plots the total asset value alongside the savings graph. Both graphs are displayed on the same chart using Chart.js.
Please note: For the code to work correctly, you may need to run it on a local server due to CORS restrictions when fetching data from Binance API.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BTC DCA Strategy vs Savings</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<h1>BTC DCA Strategy vs Savings</h1>
<label for="start">Start Date:</label>
<input type="date" id="start" name="start" required>
<label for="end">End Date:</label>
<input type="date" id="end" name="end" required>
<button onclick="runStrategy()">Run Strategy</button>
<canvas id="myChart" width="800" height="400"></canvas>
<script>
async function runStrategy() {
const startDateInput = document.getElementById('start').value;
const endDateInput = document.getElementById('end').value;
if (!startDateInput || !endDateInput) {
alert('Please select both start and end dates.');
return;
}
const startTime = new Date(startDateInput).getTime();
const endTime = new Date(endDateInput).getTime();
// Fetch BTCUSDC 8h prices from Binance API
const klines = await fetchKlines('BTCUSDC', '8h', startTime, endTime);
const prices = klines.map(k => parseFloat(k[4])); // Close prices
const times = klines.map(k => new Date(k[0]));
// Calculate 39-period moving average
const ma = calculateMovingAverage(prices, 39);
// Implement DCA strategy
const strategyResults = simulateStrategy(times, prices, ma);
// Plot the results
plotResults(times, strategyResults);
}
async function fetchKlines(symbol, interval, startTime, endTime) {
const limit = 1000; // Maximum limit per request
let klines = [];
let fetchStartTime = startTime;
while (fetchStartTime < endTime) {
const fetchEndTime = Math.min(fetchStartTime + limit * 8 * 60 * 60 * 1000, endTime);
const url = `https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=${interval}&startTime=${fetchStartTime}&endTime=${fetchEndTime}&limit=${limit}`;
const response = await fetch(url);
const data = await response.json();
klines = klines.concat(data);
if (data.length < limit) break;
fetchStartTime = data[data.length - 1][0] + 1;
}
return klines;
}
function calculateMovingAverage(prices, period) {
const ma = [];
for (let i = 0; i < prices.length; i++) {
if (i < period - 1) {
ma.push(null); // Not enough data to calculate MA
} else {
const sum = prices.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
ma.push(sum / period);
}
}
return ma;
}
function simulateStrategy(times, prices, ma) {
let usdcBalance = 0;
let btcBalance = 0;
let totalAssetValues = [];
let savings = [];
let savedUSDC = 0;
for (let i = 0; i < prices.length; i++) {
const price = prices[i];
const movingAvg = ma[i];
// Skip if moving average is not available yet
if (movingAvg === null) {
totalAssetValues.push(usdcBalance + btcBalance * price);
savings.push(savedUSDC);
continue;
}
// Buy $50 worth of BTC if price is lower than MA
if (price < movingAvg) {
const usdcSpent = 50;
const btcBought = usdcSpent / price;
usdcBalance -= usdcSpent;
btcBalance += btcBought;
savedUSDC += 50; // For savings graph
}
// Sell $50 worth of BTC if price is greater than MA * 1.02
else if (price > movingAvg * 1.02 && btcBalance > 0) {
const usdcGained = Math.min(50, btcBalance * price);
const btcSold = usdcGained / price;
btcBalance -= btcSold;
usdcBalance += usdcGained;
}
totalAssetValues.push(usdcBalance + btcBalance * price);
savings.push(savedUSDC);
}
return { totalAssetValues, savings };
}
function plotResults(times, strategyResults) {
const ctx = document.getElementById('myChart').getContext('2d');
const labels = times.map(time => time.toLocaleDateString());
const data = {
labels: labels,
datasets: [
{
label: 'Total Asset Value (USDC)',
data: strategyResults.totalAssetValues,
borderColor: 'blue',
fill: false,
yAxisID: 'y',
},
{
label: 'Savings (USDC)',
data: strategyResults.savings,
borderColor: 'green',
fill: false,
yAxisID: 'y',
},
],
};
const config = {
type: 'line',
data: data,
options: {
scales: {
y: {
type: 'linear',
position: 'left',
},
},
},
};
new Chart(ctx, config);
}
</script>
</body>
</html>
Instructions:
-
Copy the above code into a text editor and save it as index.html.
-
Open the file in a web browser. Due to CORS policy, you might need to run a local server.
- Using Python 3:
- Open a terminal in the directory containing
index.html.
- Run
python -m http.server 8000.
- Open
http://localhost:8000 in your web browser.
-
Select the start and end dates using the date pickers.
-
Click the "Run Strategy" button to execute the simulation and display the graph.
Explanation:
-
The Binance API is used to fetch historical BTC/USDC price data with 8-hour intervals between the selected dates.
-
A 39-period moving average is calculated using the closing prices.
-
The DCA strategy is simulated:
- Buy $50 worth of BTC when the price is lower than the moving average.
- Sell $50 worth of BTC when the price is greater than the moving average multiplied by 1.02.
-
Total asset value is calculated over time by summing the USDC balance and the BTC balance converted to USDC.
-
A savings graph is also generated, which represents the amount of USDC saved over time by investing $50 whenever a buy action would have occurred.
-
Both datasets are plotted on the same chart using Chart.js for easy comparison.
Notes:
- The code assumes no transaction fees for simplicity.
- The Binance API might have rate limits, so if you encounter issues fetching data, consider adding delays or modifying the request parameters.
- The script handles cases where there isn't enough data to calculate the moving average by inserting
null values.
- Ensure you have an internet connection when running the script, as it needs to fetch data from the Binance API and load Chart.js.
Customization:
- You can adjust the DCA amount by changing the value assigned to
usdcSpent and savedUSDC in the simulateStrategy function.
- Modify the moving average period by changing the
39 in the calculateMovingAverage(prices, 39) call.
- Adjust the sell threshold by changing
1.02 to your desired multiplier in the sell condition.
Feel free to explore and modify the code to suit your specific needs.