From f618bb8271590a8a7c74b890c16bed302502c020 Mon Sep 17 00:00:00 2001 From: MuslemRahimi Date: Wed, 5 Mar 2025 00:27:13 +0100 Subject: [PATCH] update chart --- src/lib/components/Chart.svelte | 239 ++++++-- src/routes/stocks/[tickerID]/+page.svelte | 663 +++++++--------------- 2 files changed, 389 insertions(+), 513 deletions(-) diff --git a/src/lib/components/Chart.svelte b/src/lib/components/Chart.svelte index bfaf345b..50c3918b 100644 --- a/src/lib/components/Chart.svelte +++ b/src/lib/components/Chart.svelte @@ -1,65 +1,178 @@ - - - - -
- - \ No newline at end of file + let chart: any = null; + let selectedInterval = "1D"; + const intervals = ["1D", "1W", "1M", "6M", "1Y", "MAX"]; + let historicalData: { [key: string]: any[] } = {}; + let loading = false; + + const chartConfig = { + chart: { + type: "area", + backgroundColor: "#09090B", + height: "400px", + }, + title: { text: null }, + xAxis: { + type: "datetime", + labels: { + format: "{value:%b %Y}", + style: { color: "#FFF" }, + }, + }, + yAxis: { + title: { text: null }, + opposite: true, + labels: { style: { color: "#FFF" } }, + }, + tooltip: { + shared: true, + formatter: function () { + return `${Highcharts.dateFormat("%b %e, %Y", this.x)}
+ Price: $${Highcharts.numberFormat(this.points[0].y, 2)}`; + }, + }, + series: [ + { + name: "Price", + data: [], + color: "#00FC50", + fillColor: { + linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, + stops: [ + [0, "rgba(0, 252, 80, 0.2)"], + [1, "rgba(0, 252, 80, 0.01)"], + ], + }, + }, + ], + }; + + async function fetchHistoricalData(timePeriod: string) { + if (historicalData[timePeriod]) return; + + loading = true; + try { + const response = await fetch(`/api/historical-price`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ ticker, timePeriod }), + }); + + const data = await response.json(); + historicalData[timePeriod] = data.map((point: any) => ({ + x: new Date(point.date).getTime(), + y: point.close, + })); + } catch (error) { + console.error("Failed to fetch historical data:", error); + } + loading = false; + } + + function updateChart(timePeriod: string) { + if (!chart || !historicalData[timePeriod]) return; + + chart.update( + { + series: [ + { + data: historicalData[timePeriod], + type: timePeriod === "1D" ? "line" : "area", + }, + ], + }, + true, + ); + } + + async function handleIntervalChange(timePeriod: string) { + selectedInterval = timePeriod; + await fetchHistoricalData(timePeriod); + updateChart(timePeriod); + } + + +
+
+ +
+ {#each intervals as interval} + + {/each} +
+ + {#if loading} +
+ Loading... +
+ {/if} +
+ + diff --git a/src/routes/stocks/[tickerID]/+page.svelte b/src/routes/stocks/[tickerID]/+page.svelte index 31b053e8..01b0c1ea 100644 --- a/src/routes/stocks/[tickerID]/+page.svelte +++ b/src/routes/stocks/[tickerID]/+page.svelte @@ -1,6 +1,6 @@