Certainly! Below is an HTML and JavaScript code example that fulfills your requirements:
- Fetch BTCUSDC futures 1-minute prices from Binance API.
- Calculate the 19-minute moving average.
- Simulate the trading strategy as per your instructions.
- Calculate the total value of all opened positions at each time point.
- Compare it with simply collecting $10 USDC per minute.
- Plot both data series on a graph.
Here is the complete code:
<!DOCTYPE html>
<html>
<head>
<title>BTCUSDC Futures Trading Simulation</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<h1>BTCUSDC Futures Trading Simulation</h1>
<canvas id="myChart" width="1000" height="400"></canvas>
<script>
async function fetchData() {
const symbol = 'BTCUSDC';
const interval = '1m';
const limit = 1000; // You can adjust this limit as needed
// Fetch klines data from Binance Futures API
const response = await fetch(`https://fapi.binance.com/fapi/v1/klines?symbol=${symbol}&interval=${interval}&limit=${limit}`);
const data = await response.json();
// Extract closing prices and timestamps
const prices = data.map(item => parseFloat(item[4])); // Close price is at index 4
const timestamps = data.map(item => new Date(item[0]).toLocaleString()); // Open time is at index 0
return { prices, timestamps };
}
function calculateMovingAverage(prices, windowSize) {
let movingAverages = [];
for (let i = 0; i < prices.length; i++) {
if (i < windowSize - 1) {
movingAverages.push(null); // Not enough data to calculate MA
} else {
const window = prices.slice(i - windowSize + 1, i + 1);
const sum = window.reduce((acc, val) => acc + val, 0);
movingAverages.push(sum / windowSize);
}
}
return movingAverages;
}
async function simulateTrading() {
const { prices, timestamps } = await fetchData();
const maWindowSize = 19;
const movingAverage = calculateMovingAverage(prices, maWindowSize);
// Initialize variables for positions and total value
let longPositions = [];
let shortPositions = [];
let totalValues = [];
let usdcCollected = [];
let accumulatedUSDC = 0;
let accumulatedValue = 0;
for (let i = 0; i < prices.length; i++) {
const price = prices[i];
const ma = movingAverage[i];
// Collect $10 USDC per minute
accumulatedUSDC += 10;
usdcCollected.push(accumulatedUSDC);
// Skip until moving average is available
if (ma === null) {
totalValues.push(accumulatedValue);
continue;
}
// Simulate trading strategy
if (price < ma) {
// Price is below MA, open $10 short position
const quantity = 10 / price;
shortPositions.push({ quantity: quantity, entryPrice: price });
} else if (price > ma) {
// Price is above MA, open $10 long position
const quantity = 10 / price;
longPositions.push({ quantity: quantity, entryPrice: price });
}
// Calculate total value of positions
let longValue = longPositions.reduce((acc, pos) => acc + pos.quantity * price, 0);
let shortValue = shortPositions.reduce((acc, pos) => acc + pos.quantity * (2 * pos.entryPrice - price), 0);
accumulatedValue = longValue + shortValue;
totalValues.push(accumulatedValue);
}
// Plot the results
const ctx = document.getElementById('myChart').getContext('2d');
const chartData = {
labels: timestamps,
datasets: [{
label: 'Total Value of Positions',
data: totalValues,
borderColor: 'blue',
fill: false,
}, {
label: 'Accumulated USDC ($10/min)',
data: usdcCollected,
borderColor: 'green',
fill: false,
}]
};
const chartOptions = {
scales: {
x: {
display: false, // Hide X-axis labels if too crowded
},
y: {
title: {
display: true,
text: 'Value in USDC'
}
}
},
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Trading Simulation vs. Accumulated USDC'
}
},
};
new Chart(ctx, {
type: 'line',
data: chartData,
options: chartOptions
});
}
simulateTrading();
</script>
</body>
</html>
Explanation:
Notes:
-
Assumptions:
- Positions are Permanent: Once opened, positions are never closed.
- No Leverage or Fees: The simulation does not account for leverage ratios or trading fees.
- Simplified Short Position Value: Calculating the value of short positions can be complex; the provided formula is a simplification.
- Market Conditions: The simulation assumes perfect market conditions without slippage.
-
Adjustments:
- You may need to adjust the API endpoint or parameters based on the latest Binance API documentation.
- Make sure you handle CORS if you encounter any cross-origin issues. You might need to run this code on a server or use a CORS proxy.
-
Data Limitations:
- The
limit parameter is set to 1000, which means we're simulating over approximately 16.6 hours of data (1000 minutes). Increase this limit if needed, but be aware of the API rate limits.
-
Running the Code:
- Save the code in an
.html file and open it in a modern web browser (e.g., Chrome, Firefox).
- Ensure you have an internet connection to fetch the data and load Chart.js from the CDN.
Disclaimer:
- Financial Risk: This simulation is for educational purposes only. Trading futures involves significant risk of loss and is not suitable for all investors.
- Accuracy: The simulation simplifies many aspects of trading and may not accurately reflect real-world trading results.
Feel free to adjust the code and parameters to better suit your needs!