Here's an HTML file with embedded JavaScript that performs the requested simulation. It fetches BTCUSDC futures 1-minute prices from Binance API between selected dates, calculates the 39-period moving average, simulates trading positions based on the moving average crossover strategy, and plots the total asset value over time alongside a comparison line representing the cumulative collection of 10 USDC per minute.
<!DOCTYPE html>
<html>
<head>
<title>BTCUSDC Moving Average Strategy Simulation</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<h1>BTCUSDC Moving Average Strategy Simulation</h1>
<p>Select the date range for the simulation:</p>
<label for="startDate">Start Date (UTC):</label>
<input type="datetime-local" id="startDate" value="2023-09-01T00:00">
<label for="endDate">End Date (UTC):</label>
<input type="datetime-local" id="endDate" value="2023-09-02T00:00">
<button onclick="runSimulation()">Run Simulation</button>
<canvas id="assetChart" width="1000" height="500"></canvas>
<script>
async function runSimulation() {
const startDateInput = document.getElementById('startDate').value;
const endDateInput = document.getElementById('endDate').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();
if (startTime >= endTime) {
alert('Start date must be before end date.');
return;
}
// Fetch data from Binance API
const klines = await fetchKlines('BTCUSDC', '1m', startTime, endTime);
if (!klines || klines.length === 0) {
alert('No data retrieved. Please adjust the date range.');
return;
}
// Extract closing prices and times
const prices = klines.map(k => parseFloat(k[4]));
const times = klines.map(k => k[0]); // Open time
// Calculate 39-period moving average
const movingAverage = calculateMovingAverage(prices, 39);
// Simulate trading strategy
const results = simulateStrategy(prices, movingAverage);
// Simulate cumulative 10 USDC collection
const cumulativeUSDC = [];
for (let i = 0; i < results.totalAssetValue.length; i++) {
cumulativeUSDC.push((i + 1) * 10);
}
// Prepare data for plotting
const plotTimes = times.slice(38); // Adjust for moving average offset
const timeLabels = plotTimes.map(t => new Date(t).toLocaleString());
// Plot the results
plotResults(timeLabels, results.totalAssetValue, cumulativeUSDC);
}
async function fetchKlines(symbol, interval, startTime, endTime) {
let klines = [];
let fetchTime = startTime;
const limit = 1000; // Max limit per request
try {
while (fetchTime < endTime) {
const url = `https://fapi.binance.com/fapi/v1/klines?symbol=${symbol}&interval=${interval}&startTime=${fetchTime}&limit=${limit}&endTime=${endTime}`;
const response = await fetch(url);
const data = await response.json();
if (data && data.length > 0) {
klines = klines.concat(data);
fetchTime = data[data.length - 1][0] + 60000; // Next minute
} else {
break;
}
}
} catch (error) {
console.error('Error fetching klines:', error);
}
return klines;
}
function calculateMovingAverage(prices, period) {
const movingAvg = [];
for (let i = 0; i < prices.length; i++) {
if (i < period - 1) {
movingAvg.push(null); // Not enough data yet
} else {
const sum = prices.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
movingAvg.push(sum / period);
}
}
return movingAvg;
}
function simulateStrategy(prices, movingAverage) {
let totalAssetValue = [];
let positionSizes = []; // In BTC
let entryPrices = []; // Entry prices for each position
let cumulativePnL = 0;
for (let i = 38; i < prices.length; i++) { // Start from index 38 due to moving average period
const price = prices[i];
const ma = movingAverage[i];
if (ma === null) {
totalAssetValue.push(0);
continue;
}
// Determine position
let positionValueUSDC = 10; // Fixed position value per minute
let positionSizeBTC = positionValueUSDC / price; // Position size in BTC
if (price < ma) {
// Short position
positionSizes.push(-positionSizeBTC);
} else {
// Long position
positionSizes.push(positionSizeBTC);
}
entryPrices.push(price);
// Calculate PnL for all open positions
cumulativePnL = 0;
for (let j = 0; j < positionSizes.length; j++) {
const posSize = positionSizes[j];
const entryPrice = entryPrices[j];
const pnl = posSize * (price - entryPrice) * (posSize > 0 ? 1 : -1);
cumulativePnL += pnl * price; // Convert BTC PnL to USDC
}
// Total asset value is cumulative position value plus cumulative PnL
const totalInvested = positionSizes.length * 10; // 10 USDC per position
const assetValue = totalInvested + cumulativePnL;
totalAssetValue.push(assetValue);
}
return {
totalAssetValue
};
}
function plotResults(labels, strategyValues, cumulativeUSDC) {
const ctx = document.getElementById('assetChart').getContext('2d');
const chartData = {
labels: labels,
datasets: [
{
label: 'Strategy Total Asset Value (USDC)',
data: strategyValues,
borderColor: 'blue',
fill: false
},
{
label: 'Cumulative USDC Collected',
data: cumulativeUSDC,
borderColor: 'red',
fill: false
}
]
};
const config = {
type: 'line',
data: chartData,
options: {
responsive: true,
scales: {
x: {
display: false // Hide x-axis labels if too crowded
}
},
plugins: {
tooltip: {
callbacks: {
label: function(context) {
return `${context.dataset.label}: ${context.formattedValue} USDC`;
}
}
}
}
}
};
new Chart(ctx, config);
}
</script>
</body>
</html>
Instructions:
- Save the above code into a file named
simulation.html.
- Open
simulation.html in a modern web browser (e.g., Chrome, Firefox).
- Adjust the start and end dates as desired. The default is set from
2023-09-01 00:00 to 2023-09-02 00:00 UTC.
- Click the "Run Simulation" button to start the process.
- Wait for the data to load and the simulation to complete. The graph will display the total asset value over time.
Notes:
- The code uses Binance's public API to fetch historical klines (candlestick data) for the BTCUSDC trading pair on the futures market.
- The simulation starts after calculating the 39-period moving average, so the first 38 data points are skipped.
- Positions are accumulated every minute based on the strategy rules, and their PnL is calculated against the current market price.
- The red line represents simply collecting 10 USDC every minute without trading, serving as a benchmark.
- The blue line represents the total asset value when following the moving average crossover strategy.
Disclaimer:
- This simulation is simplified and assumes no trading fees, slippage, or funding rates.
- Real-world trading involves significant risks, and past performance is not indicative of future results.
- Ensure that you understand the code and the trading strategy before using it for any real analysis.