Click the button below to view and copy the JavaScript source code:
async function convert(date, fromCurrency = "USD", toCurrency = "CNY") {
const url = `https://api.frankfurter.dev/v1/${date}?base=${fromCurrency}&symbols=${toCurrency}`;
try {
const response = await fetch(url);
const data = await response.json();
if (data.rates && data.rates[toCurrency]) {
return data.rates[toCurrency];
} else {
console.log(`Conversion rate for ${toCurrency} not found.`);
return null;
}
} catch (error) {
console.error('Error fetching currency data:', error);
return null;
}
}
async function getBtcMidPrice(dateStr) {
const dateObj = new Date(dateStr + 'T00:00:00Z');
const startTime = dateObj.getTime();
const endTime = startTime + 24 * 60 * 60 * 1000;
const url = "https://api.binance.com/api/v3/klines";
const params = new URLSearchParams({
symbol: "BTCUSDT",
interval: "1d",
startTime: startTime,
endTime: endTime,
limit: 1
});
try {
const response = await fetch(`${url}?${params}`);
const data = await response.json();
if (data && data.length > 0) {
// Kline data: [timestamp, open, high, low, close, volume, ...]
const openPrice = parseFloat(data[0][1]);
const highPrice = parseFloat(data[0][2]);
const lowPrice = parseFloat(data[0][3]);
const closePrice = parseFloat(data[0][4]);
// Calculate mid price (average of high and low)
const midPrice = (highPrice + lowPrice) / 2;
return {
date: dateStr,
open: openPrice,
high: highPrice,
low: lowPrice,
close: closePrice,
mid_price: midPrice
};
}
return null;
} catch (error) {
console.error('Error fetching BTC data:', error);
return null;
}
}
function displayResults(date, btcResult, currencyData, rate) {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = `
📅 Date: ${date}
â‚¿ Bitcoin Data from Binance:
${JSON.stringify(btcResult, null, 2)}
💱 Currency Exchange Rate:
1 USD = ${currencyData} CNY
🎯 Final Result:
1 BTC = ${Math.round(rate * 100) / 100} CNY
`;
resultsDiv.className = 'results';
resultsDiv.style.display = 'block';
}
function displayError(message) {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = `Error: ${message}
`;
resultsDiv.className = 'results error';
resultsDiv.style.display = 'block';
}
function displayLoading() {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = 'Loading data... Please wait.
';
resultsDiv.className = 'results loading';
resultsDiv.style.display = 'block';
}
async function convertCurrency() {
const dateInput = document.getElementById('dateInput');
const convertBtn = document.getElementById('convertBtn');
const date = dateInput.value;
if (!date) {
displayError('Please select a date.');
return;
}
// Disable button and show loading
convertBtn.disabled = true;
convertBtn.textContent = 'Converting...';
displayLoading();
try {
const btcResult = await getBtcMidPrice(date);
const currencyData = await convert(date);
if (btcResult && currencyData) {
const rate = btcResult.mid_price * currencyData;
displayResults(date, btcResult, currencyData, rate);
} else {
displayError('Could not fetch required data. Please check if the date is valid and try again.');
}
} catch (error) {
console.error('Error in conversion:', error);
displayError('An error occurred while fetching data. Please try again.');
} finally {
// Re-enable button
convertBtn.disabled = false;
convertBtn.textContent = 'Convert';
}
}
// Allow Enter key to trigger conversion
document.getElementById('dateInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
convertCurrency();
}
});
// Complete JavaScript code for BTC to CNY converter
async function convert(date, fromCurrency = "USD", toCurrency = "CNY") {
const url = `https://api.frankfurter.dev/v1/${date}?base=${fromCurrency}&symbols=${toCurrency}`;
try {
const response = await fetch(url);
const data = await response.json();
if (data.rates && data.rates[toCurrency]) {
return data.rates[toCurrency];
} else {
console.log(`Conversion rate for ${toCurrency} not found.`);
return null;
}
} catch (error) {
console.error('Error fetching currency data:', error);
return null;
}
}
async function getBtcMidPrice(dateStr) {
const dateObj = new Date(dateStr + 'T00:00:00Z');
const startTime = dateObj.getTime();
const endTime = startTime + 24 * 60 * 60 * 1000;
const url = "https://api.binance.com/api/v3/klines";
const params = new URLSearchParams({
symbol: "BTCUSDT",
interval: "1d",
startTime: startTime,
endTime: endTime,
limit: 1
});
try {
const response = await fetch(`${url}?${params}`);
const data = await response.json();
if (data && data.length > 0) {
// Kline data: [timestamp, open, high, low, close, volume, ...]
const openPrice = parseFloat(data[0][1]);
const highPrice = parseFloat(data[0][2]);
const lowPrice = parseFloat(data[0][3]);
const closePrice = parseFloat(data[0][4]);
// Calculate mid price (average of high and low)
const midPrice = (highPrice + lowPrice) / 2;
return {
date: dateStr,
open: openPrice,
high: highPrice,
low: lowPrice,
close: closePrice,
mid_price: midPrice
};
}
return null;
} catch (error) {
console.error('Error fetching BTC data:', error);
return null;
}
}
function displayResults(date, btcResult, currencyData, rate) {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = `
📅 Date: ${date}
â‚¿ Bitcoin Data from Binance:
${JSON.stringify(btcResult, null, 2)}
💱 Currency Exchange Rate:
1 USD = ${currencyData} CNY
🎯 Final Result:
1 BTC = ${Math.round(rate * 100) / 100} CNY
`;
resultsDiv.className = 'results';
resultsDiv.style.display = 'block';
}
function displayError(message) {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = `Error: ${message}
`;
resultsDiv.className = 'results error';
resultsDiv.style.display = 'block';
}
function displayLoading() {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = 'Loading data... Please wait.
';
resultsDiv.className = 'results loading';
resultsDiv.style.display = 'block';
}
async function convertCurrency() {
const dateInput = document.getElementById('dateInput');
const convertBtn = document.getElementById('convertBtn');
const date = dateInput.value;
if (!date) {
displayError('Please select a date.');
return;
}
// Disable button and show loading
convertBtn.disabled = true;
convertBtn.textContent = 'Converting...';
displayLoading();
try {
const btcResult = await getBtcMidPrice(date);
const currencyData = await convert(date);
if (btcResult && currencyData) {
const rate = btcResult.mid_price * currencyData;
displayResults(date, btcResult, currencyData, rate);
} else {
displayError('Could not fetch required data. Please check if the date is valid and try again.');
}
} catch (error) {
console.error('Error in conversion:', error);
displayError('An error occurred while fetching data. Please try again.');
} finally {
// Re-enable button
convertBtn.disabled = false;
convertBtn.textContent = 'Convert';
}
}
// Allow Enter key to trigger conversion
document.getElementById('dateInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
convertCurrency();
}
});
// For console usage - main function
async function main() {
const date = "2025-07-01"; // Change this date as needed
try {
const btcResult = await getBtcMidPrice(date);
const currencyData = await convert(date);
if (btcResult && currencyData) {
const rate = btcResult.mid_price * currencyData;
console.log(`Date: ${date}`);
console.log("Binance Data:");
console.log(JSON.stringify(btcResult, null, 2));
console.log("Currency Data:");
console.log(`1 USD = ${currencyData} CNY`);
console.log("Calculated Rate:");
console.log(`1 BTC = ${Math.round(rate * 100) / 100} CNY`);
} else {
console.log("Error: Could not fetch required data");
}
} catch (error) {
console.error('Error in main execution:', error);
}
}
// Uncomment the line below to run main function automatically
// main();