#chartContainer { min-height: 350px; /* Минимальная высота контейнера */ width: 100%; } #copperChart { height: 350px !important; /* Фиксированная высота для canvas */ width: 100% !important; } // copper_chart.js document.addEventListener('DOMContentLoaded', function() { const apiKey = 'RLJ6VOKAPQVT6633'; const symbol = 'HG'; // Медь // Форматируем URL для запроса const url = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${symbol}&apikey=${apiKey}&outputsize=compact`; fetch(url) .then(response => response.json()) .then(data => { if (data['Error Message']) { console.error('Ошибка API:', data['Error Message']); return; } const timeSeries = data['Time Series (Daily)']; const labels = []; // Даты в полном формате для данных const prices = []; // Цены закрытия // Определяем дату одного месяца назад const today = new Date(); const oneMonthAgo = new Date(today.getTime() - (30 * 24 * 60 * 60 * 1000)); const cutoffDate = oneMonthAgo.toISOString().split('T')[0]; // Проходим по ключам (датам), отсортированным обратным порядком Object.keys(timeSeries).reverse().forEach(date => { if (date >= cutoffDate) { labels.push(date); const closePrice = parseFloat(timeSeries[date]['4. close']); prices.push(closePrice); } }); // Подготавливаем контекст для графика const ctx = document.getElementById('copperChart').getContext('2d'); // Уничтожаем предыдущий график, если он есть if (window.copperChartInstance) { window.copperChartInstance.destroy(); } // Создаем новый график window.copperChartInstance = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: 'Котировка меди (USD/фунт)', data: prices, borderColor: 'rgb(0, 68, 158)', backgroundColor: 'rgba(75, 192, 192, 0.2)', tension: 0.1, // Плавная линия pointHoverRadius: 6 // Радиус точки при наведении }] }, options: { responsive: true, maintainAspectRatio: false, aspectRatio: 1.5, interaction: { intersect: false, mode: 'index' }, scales: { y: { beginAtZero: false, title: { display: true, text: 'Цена (USD)' } }, x: { title: { display: true, text: 'Дата' }, ticks: { callback: function(value, index, values) { // Форматируем дату в короткий вид: 25 нояб. const date = new Date(labels[index]); const day = date.getDate(); const monthNames = ['янв.', 'фев.', 'мар.', 'апр.', 'мая', 'июн.', 'июл.', 'авг.', 'сен.', 'окт.', 'нояб.', 'дек.']; const month = monthNames[date.getMonth()]; return `${day} ${month}`; } } } }, plugins: { title: { display: true, text: 'Котировки меди (LME/COMEX) за последний месяц' }, legend: { display: true }, tooltip: { enabled: true, backgroundColor: 'rgba(0, 0, 0, 0.8)', // Темный фон titleColor: '#fff', bodyColor: '#fff', callbacks: { title: function(tooltipItems) { // Форматируем дату в подсказке: 25 нояб. 2023 const date = new Date(tooltipItems[0].label); const day = date.getDate(); const monthNames = ['янв.', 'фев.', 'мар.', 'апр.', 'мая', 'июн.', 'июл.', 'авг.', 'сен.', 'окт.', 'нояб.', 'дек.']; const month = monthNames[date.getMonth()]; const year = date.getFullYear(); return `${day} ${month} ${year}`; }, label: function(tooltipItem) { // Цена с двумя знаками return `Цена: ${tooltipItem.raw.toFixed(2)} USD`; } } } } } }); }) .catch(error => { console.error('Ошибка fetch:', error); document.getElementById('chartContainer').innerHTML = 'Ошибка загрузки данных. Проверьте API ключ.'; }); });