|
@@ -0,0 +1,88 @@
|
|
|
|
|
+<script>
|
|
|
|
|
+ import { onMount } from 'svelte';
|
|
|
|
|
+ import { Chart, registerables } from 'chart.js';
|
|
|
|
|
+ import { getRequest } from '../utils/api.js';
|
|
|
|
|
+
|
|
|
|
|
+ Chart.register(...registerables);
|
|
|
|
|
+
|
|
|
|
|
+ export let code;
|
|
|
|
|
+
|
|
|
|
|
+ let chartCanvas;
|
|
|
|
|
+ let chartInstance;
|
|
|
|
|
+
|
|
|
|
|
+ const endpoint = `https://stocks-be.lhamacorp.com/api/stocks/${code}/history`;
|
|
|
|
|
+
|
|
|
|
|
+ async function fetchData() {
|
|
|
|
|
+ try {
|
|
|
|
|
+ const res = await getRequest(endpoint, {}, null);
|
|
|
|
|
+ if (!res.ok) {
|
|
|
|
|
+ console.error(`Failed to fetch price history: ${res.status}`);
|
|
|
|
|
+ return [];
|
|
|
|
|
+ }
|
|
|
|
|
+ return await res.json();
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ console.error('Error fetching stock history:', err);
|
|
|
|
|
+ return [];
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function renderChart(data) {
|
|
|
|
|
+ const labels = data.map(item => new Date(item.createdAt).toLocaleDateString());
|
|
|
|
|
+ const prices = data.map(item => item.price);
|
|
|
|
|
+
|
|
|
|
|
+ if (chartInstance) {
|
|
|
|
|
+ chartInstance.destroy();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ chartInstance = new Chart(chartCanvas, {
|
|
|
|
|
+ type: 'line',
|
|
|
|
|
+ data: {
|
|
|
|
|
+ labels,
|
|
|
|
|
+ datasets: [
|
|
|
|
|
+ {
|
|
|
|
|
+ label: `Price (${data[0]?.currency || ''})`,
|
|
|
|
|
+ data: prices,
|
|
|
|
|
+ fill: false,
|
|
|
|
|
+ borderWidth: 2
|
|
|
|
|
+ }
|
|
|
|
|
+ ]
|
|
|
|
|
+ },
|
|
|
|
|
+ options: {
|
|
|
|
|
+ responsive: true,
|
|
|
|
|
+ scales: {
|
|
|
|
|
+ x: {
|
|
|
|
|
+ title: {
|
|
|
|
|
+ display: true,
|
|
|
|
|
+ text: 'Date'
|
|
|
|
|
+ }
|
|
|
|
|
+ },
|
|
|
|
|
+ y: {
|
|
|
|
|
+ title: {
|
|
|
|
|
+ display: true,
|
|
|
|
|
+ text: 'Price'
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ },
|
|
|
|
|
+ plugins: {
|
|
|
|
|
+ legend: {
|
|
|
|
|
+ display: true
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ onMount(async () => {
|
|
|
|
|
+ if (!code) return;
|
|
|
|
|
+
|
|
|
|
|
+ const history = await fetchData();
|
|
|
|
|
+ if (history.length > 0) {
|
|
|
|
|
+ renderChart(history);
|
|
|
|
|
+ }
|
|
|
|
|
+ });
|
|
|
|
|
+</script>
|
|
|
|
|
+
|
|
|
|
|
+<div class="w-full mt-10 max-w-6xl mx-auto bg-white dark:bg-gray-900 p-6 rounded-xl shadow-md">
|
|
|
|
|
+ <h3 class="text-xl font-semibold text-gray-800 dark:text-gray-100 mb-4">Price History</h3>
|
|
|
|
|
+ <canvas bind:this={chartCanvas}></canvas>
|
|
|
|
|
+</div>
|