Certainly! Below is an HTML file that implements your trading strategy using JavaScript. The code fetches BTCUSDC 1-minute data between selected dates from Binance's public API, calculates the 99-period moving average, computes the slope and angle of the moving average, normalizes the angle, determines trading signals based on your rules, and finally, simulates trading to produce a profit and loss chart.
<!DOCTYPE html>
<html>
<head>
<title>BTCUSDC Trading Strategy Backtest</title>
<!-- Include Chart.js library for plotting the chart -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4"></script>
</head>
<body>
<h1>BTCUSDC Trading Strategy Backtest</h1>
<label for="startDate">Start Date (YYYY-MM-DD HH:MM):</label>
<input type="datetime-local" id="startDate" name="startDate">
<br><br>
<label for="endDate">End Date (YYYY-MM-DD HH:MM):</label>
<input type="datetime-local" id="endDate" name="endDate">
<br><br>
<button onclick="runBacktest()">Run Backtest</button>
<br><br>
<canvas id="profitChart" width="800" height="400"></canvas>
<script>
// Function to fetch kline data from Binance API
async function fetchKlines(symbol, interval, startTime, endTime) {
let klines = [];
let limit = 1000; // Maximum data points per request
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.length === 0) break;
klines = klines.concat(data);
fetchTime = data[data.length - 1][0] + 60000; // Increment by 1 minute
if (data.length < limit) break; // All data fetched
}
return klines;
}
// Function to calculate the moving average
function calculateMA(data, period) {
let ma = [];
for (let i = 0; i < data.length; i++) {
if (i < period - 1) {
ma.push(null); // Not enough data to calculate MA
} else {
let sum = 0;
for (let j = i - period + 1; j <= i; j++) {
sum += parseFloat(data[j][4]); // Closing price
}
ma.push(sum / period);
}
}
return ma;
}
// Function to calculate the slope of the moving average
function calculateSlope(ma) {
let slopes = [];
for (let i = 1; i < ma.length; i++) {
if (ma[i - 1] === null || ma[i] === null) {
slopes.push(0);
} else {
slopes.push(ma[i] - ma[i - 1]);
}
}
slopes.unshift(0); // Align with data array
return slopes;
}
// Function to calculate the angle of the slope
function calculateAngle(slopes) {
let angles = slopes.map(slope => Math.atan(slope) * (180 / Math.PI)); // Convert to degrees
return angles;
}
// Function to normalize the angle between -1 and 1
function normalizeAngle(angles) {
let normalizedAngles = angles.map(angle => angle / 90); // Divide by 90 degrees
return normalizedAngles;
}
// Function to calculate the absolute difference between price and moving average
function calculateAbsoluteDifference(data, ma) {
let absDiff = [];
for (let i = 0; i < data.length; i++) {
if (ma[i] === null) {
absDiff.push(0);
} else {
let price = parseFloat(data[i][4]); // Closing price
absDiff.push(Math.abs(price - ma[i]));
}
}
return absDiff;
}
// Main function to run the backtest
async function runBacktest() {
let startDateInput = document.getElementById('startDate').value;
let endDateInput = document.getElementById('endDate').value;
if (!startDateInput || !endDateInput) {
alert('Please select start and end dates.');
return;
}
let startTime = new Date(startDateInput).getTime();
let endTime = new Date(endDateInput).getTime();
// Fetch data from Binance API
console.log('Fetching data...');
let data = await fetchKlines('BTCUSDC', '1m', startTime, endTime);
console.log(`Data fetched: ${data.length} data points`);
if (data.length === 0) {
alert('No data fetched. Please check the date range and try again.');
return;
}
// Calculate moving average, slopes, angles, normalized angles, and absolute differences
let ma = calculateMA(data, 99);
let slopes = calculateSlope(ma);
let angles = calculateAngle(slopes);
let normalizedAngles = normalizeAngle(angles);
let absDiff = calculateAbsoluteDifference(data, ma);
// Initialize balances and trading history
let usdcBalance = 500;
let btcBalance = 0;
let profitHistory = [];
let buySignals = [];
let sellSignals = [];
// Simulate trading
for (let i = 0; i < data.length; i++) {
let price = parseFloat(data[i][4]); // Closing price
let angle = normalizedAngles[i];
let diff = absDiff[i];
// Trading condition for buying
if (angle >= -1 && angle <= -0.3 && diff > 100) {
let amountToBuy = -1 * angle * diff; // USDC amount to spend
if (usdcBalance >= amountToBuy && amountToBuy > 0) {
let btcToBuy = amountToBuy / price;
usdcBalance -= amountToBuy;
btcBalance += btcToBuy;
buySignals.push({ x: new Date(data[i][0]), y: price });
console.log(`Bought BTC worth ${amountToBuy.toFixed(2)} USDC at price ${price.toFixed(2)} on ${new Date(data[i][0])}`);
}
}
// Trading condition for selling
if (ma[i] !== null && price > ma[i] && btcBalance > 0) {
let usdcFromSell = btcBalance * price;
usdcBalance += usdcFromSell;
btcBalance = 0;
sellSignals.push({ x: new Date(data[i][0]), y: price });
console.log(`Sold BTC for ${usdcFromSell.toFixed(2)} USDC at price ${price.toFixed(2)} on ${new Date(data[i][0])}`);
}
// Record total account value
let totalValue = usdcBalance + btcBalance * price;
profitHistory.push({ x: new Date(data[i][0]), y: totalValue });
}
// Plot the profit and loss chart
let ctx = document.getElementById('profitChart').getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: 'Total Account Value (USDC)',
data: profitHistory,
borderColor: 'blue',
fill: false,
},
{
label: 'Buy Signals',
data: buySignals,
borderColor: 'green',
backgroundColor: 'green',
pointRadius: 5,
type: 'scatter',
showLine: false,
},
{
label: 'Sell Signals',
data: sellSignals,
borderColor: 'red',
backgroundColor: 'red',
pointRadius: 5,
type: 'scatter',
showLine: false,
},
]
},
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'linear',
ticks: {
source: 'auto',
},
time: {
displayFormats: {
minute: 'MMM D, HH:mm'
},
tooltipFormat: 'll HH:mm'
}
}],
yAxes: [{
ticks: {
beginAtZero: false,
},
scaleLabel: {
display: true,
labelString: 'USDC'
}
}]
},
tooltips: {
mode: 'index',
intersect: false,
},
elements: {
point: {
radius: 0
}
}
}
});
alert(`Backtest completed.\nFinal USDC balance: ${usdcBalance.toFixed(2)}\nFinal BTC balance: ${btcBalance.toFixed(8)} BTC`);
}
</script>
</body>
</html>
Instructions:
-
Save the Code: Copy the entire code above and save it in a file with an .html extension, for example, backtest.html.
-
Open in Browser: Open the HTML file in a modern web browser (e.g., Chrome, Firefox).
-
Select Dates: Use the date and time pickers to select the start and end dates for your backtest. Please ensure your date range does not exceed the Binance API limits. It's advisable to select a shorter date range (a few days) to avoid hitting the API rate limits and to ensure the data loads promptly.
-
Run Backtest: Click the "Run Backtest" button. The script will fetch the required data, perform the calculations, and simulate the trading strategy.
-
View Results: After the backtest completes, you will see a profit and loss chart displaying the total account value over time. Green dots represent buy signals, and red dots represent sell signals.
Explanation of Key Components:
-
Data Fetching: The fetchKlines function retrieves BTCUSDC 1-minute candlestick data from Binance's API between the selected start and end times. It handles pagination to fetch all available data within the specified range.
-
Calculations:
- Moving Average (MA): The
calculateMA function computes the 99-period moving average of the closing prices.
- Slope: The
calculateSlope function calculates the slope by finding the difference between consecutive MA values.
- Angle: The
calculateAngle function calculates the angle of the slope using the arctangent function (in degrees). An angle of zero corresponds to a flat slope.
- Normalization: The
normalizeAngle function normalizes the angle between -1 and 1 by dividing by 90 degrees (since the maximum possible angle from arctangent is ±90 degrees).
- Absolute Difference: The
calculateAbsoluteDifference function computes the absolute difference between the price and the moving average.
-
Trading Logic:
- Buy Condition: If the normalized angle is between -1 and -0.3 (indicating a downward slope) and the absolute difference is greater than 100, the script buys BTC using the formula:
Amount to Buy (USDC) = -1 × Normalized Angle × Absolute Difference.
- Sell Condition: If the price crosses above the moving average and there is a BTC holding, the script sells all BTC holdings.
-
Simulation:
- Balances: The simulation keeps track of the USDC and BTC balances, starting with 500 USDC and 0 BTC.
- Profit History: The total account value (USDC + BTC value in USDC) is recorded over time for plotting.
- Trade Signals: Buy and sell points are recorded for plotting on the chart.
-
Charting: The profit and loss chart is generated using Chart.js, displaying the total account value over time, along with markers for buy and sell signals.
Considerations:
-
API Limits: Binance API has rate limits and maximum data per request (up to 1000 data points). The code handles multiple requests to fetch all data within the date range, but be mindful of large date ranges which may cause the API to throttle or may take a long time to load.
-
CORS Policy: Some browsers may block cross-origin requests due to CORS policies. If you encounter issues fetching data, you may need to run a local server or adjust browser settings.
-
Data Accuracy: The simulation assumes perfect execution at the closing price of each minute, without accounting for slippage, fees, or market impact.
Example Usage:
-
Select Dates: Suppose you select a start date of 2021-09-01 00:00 and an end date of 2021-09-03 00:00.
-
Run Backtest: Click "Run Backtest".
-
Interpret Results:
- The chart will display how your total account value changes over the selected period.
- Buy signals (green dots) indicate points where the strategy bought BTC.
- Sell signals (red dots) indicate points where the strategy sold BTC.
- The final USDC and BTC balances are displayed in an alert box.
Final Note:
This script provides a basic simulation of your trading strategy for educational purposes. For a more robust backtesting environment, consider handling additional factors such as trading fees, slippage, and more sophisticated data handling.
Feel free to adjust the code to fine-tune the strategy or to add additional features like detailed trade logs, performance metrics, or different visualization options.