reduce loading time for historical price

This commit is contained in:
MuslemRahimi 2024-06-13 15:37:16 +02:00
parent 8310803118
commit 6437786421
7 changed files with 580 additions and 486 deletions

View File

@ -232,13 +232,17 @@ function handleKeyDown(event) {
const handleControlF = (event) => { const handleControlF = async (event) => {
if (event.ctrlKey && event.key === 'k') { if (event.ctrlKey && event.key === 'k') {
// Ctrl+F is pressed, open the modal // Ctrl+F is pressed, open the modal
const keyboardSearch = document.getElementById('searchBarModal'); const keyboardSearch = document.getElementById('searchBarModal');
keyboardSearch?.dispatchEvent(new MouseEvent('click')) keyboardSearch?.dispatchEvent(new MouseEvent('click'))
event.preventDefault() event.preventDefault()
await loadSearchData();
} }
}; };

View File

@ -85,7 +85,6 @@ export const load = async ({ params, locals, setHeaders}) => {
fetchData(apiURL,'/stock-quote',params.tickerID), fetchData(apiURL,'/stock-quote',params.tickerID),
fetchData(apiURL,'/stock-rating',params.tickerID), fetchData(apiURL,'/stock-rating',params.tickerID),
fetchData(apiURL,'/value-at-risk',params.tickerID), fetchData(apiURL,'/value-at-risk',params.tickerID),
fetchData(apiURL,'/historical-price',params.tickerID),
fetchData(apiURL,'/one-day-price',params.tickerID), fetchData(apiURL,'/one-day-price',params.tickerID),
fetchWatchlist(fastifyURL, locals?.user?.id), fetchWatchlist(fastifyURL, locals?.user?.id),
fetchPortfolio(fastifyURL, locals?.user?.id) fetchPortfolio(fastifyURL, locals?.user?.id)
@ -96,7 +95,6 @@ export const load = async ({ params, locals, setHeaders}) => {
getStockQuote, getStockQuote,
getStockTARating, getStockTARating,
getVaR, getVaR,
getHistoricalPrice,
getOneDayPrice, getOneDayPrice,
getUserWatchlist, getUserWatchlist,
getUserPortfolio, getUserPortfolio,
@ -113,7 +111,6 @@ export const load = async ({ params, locals, setHeaders}) => {
getStockQuote, getStockQuote,
getStockTARating, getStockTARating,
getVaR, getVaR,
getHistoricalPrice,
getOneDayPrice, getOneDayPrice,
getUserWatchlist, getUserWatchlist,
getUserPortfolio, getUserPortfolio,

View File

@ -3,8 +3,8 @@
import {AreaSeries, Chart, PriceLine, CandlestickSeries} from 'svelte-lightweight-charts'; import {AreaSeries, Chart, PriceLine, CandlestickSeries} from 'svelte-lightweight-charts';
import { TrackingModeExitMode } from 'lightweight-charts'; import { TrackingModeExitMode } from 'lightweight-charts';
import {screenWidth, displayCompanyName, numberOfUnreadNotification, globalForm, userRegion, isCrosshairMoveActive, realtimePrice, priceIncrease, currentPortfolioPrice, currentPrice, clientSideCache, cryptoTicker} from '$lib/store'; import {setCache, getCache, screenWidth, displayCompanyName, numberOfUnreadNotification, globalForm, userRegion, isCrosshairMoveActive, realtimePrice, priceIncrease, currentPortfolioPrice, currentPrice, clientSideCache, cryptoTicker} from '$lib/store';
import { onDestroy, onMount, afterUpdate } from 'svelte'; import { onDestroy, onMount } from 'svelte';
import CryptoKeyInformation from '$lib/components/CryptoKeyInformation.svelte'; import CryptoKeyInformation from '$lib/components/CryptoKeyInformation.svelte';
import Lazy from '$lib/components/Lazy.svelte'; import Lazy from '$lib/components/Lazy.svelte';
@ -24,10 +24,8 @@
export let data; export let data;
export let form; export let form;
let isLoaded = false;
let displayChartType = 'line'; let displayChartType = 'line';
let pricePrediction = data?.getPricePrediction ?? [];
let cryptoProfile = data?.getStockDeck ?? []; let cryptoProfile = data?.getStockDeck ?? [];
let previousClose = data?.getStockQuote?.previousClose; let previousClose = data?.getStockQuote?.previousClose;
@ -188,6 +186,7 @@ $: {
break; break;
case '1W': case '1W':
displayData = '1W'; displayData = '1W';
await historicalPrice('one-week');
if(oneWeekPrice?.length !== 0) if(oneWeekPrice?.length !== 0)
{ {
displayLastLogicalRangeValue = oneWeekPrice?.at(0)?.close; displayLastLogicalRangeValue = oneWeekPrice?.at(0)?.close;
@ -204,6 +203,7 @@ $: {
break; break;
case '1M': case '1M':
displayData = '1M'; displayData = '1M';
await historicalPrice('one-month');
if(oneMonthPrice?.length !== 0) if(oneMonthPrice?.length !== 0)
{ {
displayLastLogicalRangeValue = oneMonthPrice?.at(0)?.close; displayLastLogicalRangeValue = oneMonthPrice?.at(0)?.close;
@ -219,6 +219,7 @@ $: {
case '6M': case '6M':
displayData = '6M'; displayData = '6M';
await historicalPrice('six-months');
if(sixMonthPrice?.length !== 0) if(sixMonthPrice?.length !== 0)
{ {
displayLastLogicalRangeValue = sixMonthPrice?.at(0)?.close; displayLastLogicalRangeValue = sixMonthPrice?.at(0)?.close;
@ -233,6 +234,7 @@ $: {
break; break;
case '1Y': case '1Y':
displayData = '1Y'; displayData = '1Y';
await historicalPrice('one-year');
if(oneYearPrice?.length !== 0) if(oneYearPrice?.length !== 0)
{ {
displayLastLogicalRangeValue = oneYearPrice?.at(0)?.close; displayLastLogicalRangeValue = oneYearPrice?.at(0)?.close;
@ -246,6 +248,7 @@ $: {
break; break;
case 'MAX': case 'MAX':
displayData = 'MAX'; displayData = 'MAX';
await historicalPrice('max');
if(threeYearPrice?.length !== 0) if(threeYearPrice?.length !== 0)
{ {
displayLastLogicalRangeValue = threeYearPrice?.at(0)?.close; displayLastLogicalRangeValue = threeYearPrice?.at(0)?.close;
@ -289,10 +292,88 @@ $: {
let oneYearPrice = []; let oneYearPrice = [];
let threeYearPrice = []; let threeYearPrice = [];
let pastPriceList = [];
async function historicalPrice(timePeriod:string) {
const cachedData = getCache($cryptoTicker, 'historicalPrice'+timePeriod);
if (cachedData) {
switch (timePeriod) {
case 'one-week':
oneWeekPrice = cachedData
break;
case 'one-month':
oneMonthPrice = cachedData
break;
case 'six-months':
sixMonthPrice = cachedData
break;
case 'one-year':
oneYearPrice = cachedData
break;
case 'max':
threeYearPrice = cachedData
break;
default:
console.log(`Unsupported time period: ${timePeriod}`);
}
} else {
output = null;
const postData = {
ticker: $cryptoTicker,
timePeriod: timePeriod,
};
const response = await fetch(apiURL+'/historical-price', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData)
});
output = await response?.json() ?? [];
const mapData = (data) => data?.map(({ time, open, high, low, close }) => ({
time: Date.parse(time),
open,
high,
low,
close
}));
const mappedData = mapData(output);
try {
switch (timePeriod) {
case 'one-week':
oneWeekPrice = mappedData
break;
case 'one-month':
oneMonthPrice = mappedData
break;
case 'six-months':
sixMonthPrice = mappedData
break;
case 'one-year':
oneYearPrice = mappedData
break;
case 'max':
threeYearPrice = mappedData
break;
default:
console.log(`Unsupported time period: ${timePeriod}`);
}
setCache($cryptoTicker, mappedData, 'historicalPrice'+timePeriod);
} catch (e) {
console.log(e);
}
}
}
async function initializePrice() { async function initializePrice() {
@ -304,18 +385,8 @@ $: {
try { try {
output = [...data?.getOneDayPrice] ?? []; output = [...data?.getOneDayPrice] ?? [];
oneDayPrice = data?.getOneDayPrice;
pastPriceList = data?.getHistoricalPrice;
oneDayPrice = output?.map(item => ({ time: Date.parse(item?.time), open: item?.open !== null ? item?.open : NaN, high: item?.high !== null ? item?.high : NaN, low: item?.low !== null ? item?.low : NaN, close: item?.close !== null ? item?.close : NaN})); oneDayPrice = output?.map(item => ({ time: Date.parse(item?.time), open: item?.open !== null ? item?.open : NaN, high: item?.high !== null ? item?.high : NaN, low: item?.low !== null ? item?.low : NaN, close: item?.close !== null ? item?.close : NaN}));
oneWeekPrice = pastPriceList['1W']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
oneMonthPrice = pastPriceList['1M']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
oneMonthPrice = Object?.values(oneMonthPrice?.reduce((acc, cur) => Object?.assign(acc, {[cur?.time]: cur}), {}));
sixMonthPrice = pastPriceList['6M']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
oneYearPrice = pastPriceList['1Y']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
threeYearPrice = pastPriceList['MAX']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
displayData = oneDayPrice?.length === 0 && sixMonthPrice?.length !== 0 ? '6M' : '1D'; displayData = oneDayPrice?.length === 0 && sixMonthPrice?.length !== 0 ? '6M' : '1D';
//lastValue = oneDayPrice[oneDayPrice?.length - 1]?.value; //lastValue = oneDayPrice[oneDayPrice?.length - 1]?.value;
@ -573,14 +644,12 @@ function changeChartType() {
if ($cryptoTicker && typeof window !== 'undefined') // add a check to see if running on client-side if ($cryptoTicker && typeof window !== 'undefined') // add a check to see if running on client-side
{ {
$realtimePrice = null; $realtimePrice = null;
isLoaded = false;
dowloadData = false; dowloadData = false;
oneDayPrice = []; oneDayPrice = [];
oneWeekPrice = []; oneWeekPrice = [];
oneMonthPrice = []; oneMonthPrice = [];
oneYearPrice = []; oneYearPrice = [];
threeYearPrice = []; threeYearPrice = [];
pastPriceList = [];
taRating = {}; taRating = {};
varDict={} varDict={}
output = null; output = null;
@ -594,17 +663,14 @@ function changeChartType() {
const asyncFunctions = []; const asyncFunctions = [];
Promise.all(asyncFunctions) Promise.all(asyncFunctions)
.then((results) => { .then((results) => {
initializePrice() initializePrice()
isLoaded = true;
}) })
.catch((error) => { .catch((error) => {
console.error('An error occurred:', error); console.error('An error occurred:', error);
}); });
isLoaded = true;
} }
@ -773,7 +839,7 @@ afterUpdate(async () => {
<!--End Ticker Section--> <!--End Ticker Section-->
<!-- Start Graph --> <!-- Start Graph -->
{#if output !== null && pastPriceList?.length !== 0} {#if output !== null}
<div class ="w-full sm:pl-7 ml-auto max-w-3xl mb-10"> <div class ="w-full sm:pl-7 ml-auto max-w-3xl mb-10">
{#if displayData === '1D' && oneDayPrice?.length === 0} {#if displayData === '1D' && oneDayPrice?.length === 0}
<h2 class=" mt-20 flex h-[240px] justify-center items-center text-3xl font-bold text-slate-700 mb-20 m-auto"> <h2 class=" mt-20 flex h-[240px] justify-center items-center text-3xl font-bold text-slate-700 mb-20 m-auto">

View File

@ -115,6 +115,7 @@ const promises = [
fetchData(apiURL,'/options-bubble',params.tickerID), fetchData(apiURL,'/options-bubble',params.tickerID),
fetchData(apiURL,'/wiim',params.tickerID), fetchData(apiURL,'/wiim',params.tickerID),
fetchData(apiURL,'/value-at-risk',params.tickerID), fetchData(apiURL,'/value-at-risk',params.tickerID),
fetchData(apiURL,'/one-day-price',params.tickerID),
fetchWatchlist(fastifyURL, locals?.user?.id), fetchWatchlist(fastifyURL, locals?.user?.id),
fetchPortfolio(fastifyURL, locals?.user?.id) fetchPortfolio(fastifyURL, locals?.user?.id)
]; ];
@ -131,6 +132,7 @@ const promises = [
getOptionsData, getOptionsData,
getWhyPriceMoved, getWhyPriceMoved,
getVaR, getVaR,
getOneDayPrice,
getUserWatchlist, getUserWatchlist,
getUserPortfolio, getUserPortfolio,
] = await Promise.all(promises); ] = await Promise.all(promises);
@ -153,6 +155,7 @@ const promises = [
getOptionsData, getOptionsData,
getWhyPriceMoved, getWhyPriceMoved,
getVaR, getVaR,
getOneDayPrice,
getUserWatchlist, getUserWatchlist,
getUserPortfolio, getUserPortfolio,
companyName, companyName,

View File

@ -3,7 +3,7 @@
import {AreaSeries, Chart, PriceLine, CandlestickSeries} from 'svelte-lightweight-charts'; import {AreaSeries, Chart, PriceLine, CandlestickSeries} from 'svelte-lightweight-charts';
import { TrackingModeExitMode } from 'lightweight-charts'; import { TrackingModeExitMode } from 'lightweight-charts';
import {trendAnalysisComponent, priceAnalysisComponent, assetType, screenWidth, globalForm, userRegion, numberOfUnreadNotification, displayCompanyName, isCrosshairMoveActive, realtimePrice, priceIncrease, currentPortfolioPrice, currentPrice, clientSideCache, etfTicker, isOpen, isBeforeMarketOpen, isWeekend} from '$lib/store'; import {getCache, setCache, trendAnalysisComponent, priceAnalysisComponent, assetType, screenWidth, globalForm, userRegion, numberOfUnreadNotification, displayCompanyName, isCrosshairMoveActive, realtimePrice, priceIncrease, currentPortfolioPrice, currentPrice, clientSideCache, etfTicker, isOpen, isBeforeMarketOpen, isWeekend} from '$lib/store';
import { onDestroy, onMount } from 'svelte'; import { onDestroy, onMount } from 'svelte';
import ETFKeyInformation from '$lib/components/ETFKeyInformation.svelte'; import ETFKeyInformation from '$lib/components/ETFKeyInformation.svelte';
import Lazy from '$lib/components/Lazy.svelte'; import Lazy from '$lib/components/Lazy.svelte';
@ -24,7 +24,23 @@
}); });
let isLoaded = false;
let output = null;
//====================================//
let intervalId = null;
let oneDayPrice = [];
let oneWeekPrice = [];
let oneMonthPrice = [];
let sixMonthPrice = [];
let oneYearPrice = [];
let threeYearPrice = [];
let geographicList = []; let geographicList = [];
let sectorList = []; let sectorList = [];
@ -179,252 +195,252 @@
let displayData; let displayData;
let colorChange; let colorChange;
let topColorChange; let topColorChange;
let bottomColorChange; let bottomColorChange;
let lastValue; let lastValue;
async function changeData(state) { async function changeData(state) {
switch (state) { switch (state) {
case '1D': case '1D':
displayData = '1D'; displayData = '1D';
if(oneDayPrice?.length !== 0) if(oneDayPrice?.length !== 0)
{
displayLastLogicalRangeValue = (oneDayPrice?.at(0)?.close ?? oneDayPrice?.at(0)?.value) //previousClose;
const length = oneDayPrice.length;
for (let i = length - 1; i >= 0; i--) {
if (!isNaN(oneDayPrice[i]?.close ?? oneDayPrice[i]?.value)) {
lastValue = oneDayPrice[i]?.close ?? oneDayPrice[i]?.value;
break;
}
}
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
}
break;
case '1W':
displayData = '1W';
if(oneWeekPrice?.length !== 0)
{
displayLastLogicalRangeValue = oneWeekPrice?.at(0)?.close ?? oneWeekPrice?.at(0)?.value;
lastValue = oneWeekPrice.slice(-1)?.at(0)?.close ?? oneWeekPrice.slice(-1)?.at(0)?.value;
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
}
break;
case '1M':
displayData = '1M';
if(oneMonthPrice?.length !== 0)
{
displayLastLogicalRangeValue = oneMonthPrice?.at(0)?.close ?? oneMonthPrice?.at(0)?.value;
lastValue = oneMonthPrice.slice(-1)?.at(0)?.close ?? oneMonthPrice.slice(-1)?.at(0)?.value;
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
}
break;
case '6M':
displayData = '6M';
if(sixMonthPrice?.length !== 0)
{
displayLastLogicalRangeValue = sixMonthPrice?.at(0)?.close ?? sixMonthPrice?.at(0)?.value;
lastValue = sixMonthPrice.slice(-1)?.at(0)?.close ?? sixMonthPrice.slice(-1)?.at(0)?.value;
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
}
break;
case '1Y':
displayData = '1Y';
if(oneYearPrice?.length !== 0)
{
displayLastLogicalRangeValue = oneYearPrice?.at(0)?.close ?? oneYearPrice?.at(0)?.value;
lastValue = oneYearPrice.slice(-1)?.at(0)?.close ?? oneYearPrice.slice(-1)?.at(0)?.value;
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
}
break;
case 'MAX':
displayData = 'MAX';
if(threeYearPrice?.length !== 0)
{
displayLastLogicalRangeValue = threeYearPrice?.at(0)?.close ?? threeYearPrice?.at(0)?.value;
lastValue = threeYearPrice.slice(-1)?.at(0)?.close ?? threeYearPrice.slice(-1)?.at(0)?.value;
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
}
break;
default:
return;
}
colorChange = lastValue < displayLastLogicalRangeValue ? "#FF2F1F" : "#10DB06";
topColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.2)" : "rgb(16, 219, 6, 0.2)";
bottomColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.001)" : "rgb(16, 219, 6, 0.001)";
fitContentChart();
//trackButtonClick('Time Period: '+ state)
}
let output = null;
//====================================//
let intervalId = null;
let oneDayPrice = [];
let oneWeekPrice = [];
let oneMonthPrice = [];
let sixMonthPrice = [];
let oneYearPrice = [];
let threeYearPrice = [];
let pastPriceList = [];
async function getHistoricalPrice() {
if($clientSideCache[$etfTicker]?.getHistoricalPrice)
{
pastPriceList = $clientSideCache[$etfTicker]?.getHistoricalPrice;
}
else {
const postData = { ticker: $etfTicker};
const response = await fetch(apiURL+'/historical-price', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData)
});
pastPriceList = await response.json();
$clientSideCache[$etfTicker].getHistoricalPrice = pastPriceList;
}
if(displayChartType === 'line') {
oneWeekPrice = pastPriceList['1W']?.map(({ time, close }) => ({ time: Date.parse(time), value: close }));
oneMonthPrice = pastPriceList['1M']?.map(({ time, close }) => ({ time: Date.parse(time), value: close }));
sixMonthPrice = pastPriceList['6M']?.map(({ time, close }) => ({ time: Date.parse(time), value: close }));
oneYearPrice = pastPriceList['1Y']?.map(({ time, close }) => ({ time: Date.parse(time), value: close }));
threeYearPrice = pastPriceList['MAX']?.map(({ time, close }) => ({ time: Date.parse(time), value: close }));
}
else if (displayChartType === 'candlestick') {
oneWeekPrice = pastPriceList['1W']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
oneMonthPrice = pastPriceList['1M']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
sixMonthPrice = pastPriceList['6M']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
oneYearPrice = pastPriceList['1Y']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
threeYearPrice = pastPriceList['MAX']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
}
};
async function getOneDayPrice() {
output = null;
if (intervalId) {
clearInterval(intervalId);
}
intervalId = setInterval(checkChart, 0);
if($clientSideCache[$etfTicker]?.getOneDayPrice)
{ {
output = $clientSideCache[$etfTicker]?.getOneDayPrice; displayLastLogicalRangeValue = oneDayPrice?.at(0)?.close; //previousClose
const length = oneDayPrice?.length;
for (let i = length - 1; i >= 0; i--) {
if (!isNaN(oneDayPrice[i]?.close)) {
lastValue = oneDayPrice[i]?.close;
break;
}
}
} }
else { else {
const postData = { ticker: $etfTicker}; displayLastLogicalRangeValue = null;
const response = await fetch(apiURL+'/one-day-price', { lastValue = null;
}
break;
case '1W':
displayData = '1W';
await historicalPrice('one-week');
if(oneWeekPrice?.length !== 0)
{
displayLastLogicalRangeValue = oneWeekPrice?.at(0)?.close;
lastValue = oneWeekPrice?.slice(-1)?.at(0)?.close;
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
}
break;
case '1M':
displayData = '1M';
await historicalPrice('one-month');
if(oneMonthPrice?.length !== 0)
{
displayLastLogicalRangeValue = oneMonthPrice?.at(0)?.close;
lastValue = oneMonthPrice.slice(-1)?.at(0)?.close;
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
}
break;
case '6M':
displayData = '6M';
await historicalPrice('six-months');
if(sixMonthPrice?.length !== 0)
{
displayLastLogicalRangeValue = sixMonthPrice?.at(0)?.close;
lastValue = sixMonthPrice?.slice(-1)?.at(0)?.close;
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
}
break;
case '1Y':
displayData = '1Y';
await historicalPrice('one-year');
if(oneYearPrice?.length !== 0)
{
displayLastLogicalRangeValue = oneYearPrice?.at(0)?.close;
lastValue = oneYearPrice.slice(-1)?.at(0)?.close;
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
}
break;
case 'MAX':
displayData = 'MAX';
await historicalPrice('max');
if(threeYearPrice?.length !== 0)
{
displayLastLogicalRangeValue = threeYearPrice?.at(0)?.close;
lastValue = threeYearPrice.slice(-1)?.at(0)?.close;
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
}
break;
default:
return;
}
colorChange = lastValue < displayLastLogicalRangeValue ? "#FF2F1F" : "#10DB06";
topColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.2)" : "rgb(16, 219, 6, 0.2)";
bottomColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.001)" : "rgb(16, 219, 6, 0.001)";
fitContentChart();
//trackButtonClick('Time Period: '+ state)
}
async function historicalPrice(timePeriod:string) {
const cachedData = getCache($etfTicker, 'historicalPrice'+timePeriod);
if (cachedData) {
switch (timePeriod) {
case 'one-week':
oneWeekPrice = cachedData
break;
case 'one-month':
oneMonthPrice = cachedData
break;
case 'six-months':
sixMonthPrice = cachedData
break;
case 'one-year':
oneYearPrice = cachedData
break;
case 'max':
threeYearPrice = cachedData
break;
default:
console.log(`Unsupported time period: ${timePeriod}`);
}
} else {
output = null;
const postData = {
ticker: $etfTicker,
timePeriod: timePeriod,
};
const response = await fetch(apiURL+'/historical-price', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify(postData) body: JSON.stringify(postData)
}); });
output = await response.json(); output = await response?.json() ?? [];
$clientSideCache[$etfTicker].getOneDayPrice = output;
}
if(displayChartType === 'line') { const mapData = (data) => data?.map(({ time, open, high, low, close }) => ({
oneDayPrice = output?.map(({ time, close }) => ({ time: Date.parse(time), value: close })); time: Date.parse(time),
oneDayPrice = oneDayPrice?.map(item => ({ time: item?.time, value: item?.value !== null ? item?.value : NaN })); open,
} high,
else if (displayChartType === 'candlestick') { low,
oneDayPrice = output?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close })); close
oneDayPrice = oneDayPrice?.map(item => ({ time: item?.time, open: item?.open !== null ? item?.open : NaN, high: item?.high !== null ? item?.high : NaN, low: item?.low !== null ? item?.low : NaN, close: item?.close !== null ? item?.close : NaN})); }));
}
const mappedData = mapData(output);
try {
displayData = oneDayPrice?.length === 0 && sixMonthPrice?.length !== 0 ? '6M' : '1D'; switch (timePeriod) {
//lastValue = oneDayPrice[oneDayPrice.length - 1]?.value; case 'one-week':
if (displayData === '1D') oneWeekPrice = mappedData
{
const length = oneDayPrice.length;
for (let i = length - 1; i >= 0; i--) {
if (!isNaN(oneDayPrice[i]?.close ?? oneDayPrice[i]?.value)) {
lastValue = oneDayPrice[i]?.close ?? oneDayPrice[i]?.value;
break; break;
} case 'one-month':
} oneMonthPrice = mappedData
} break;
else if (displayData === '6M') { case 'six-months':
lastValue = sixMonthPrice?.slice(-1)?.at(0)?.value; sixMonthPrice = mappedData
break;
case 'one-year':
oneYearPrice = mappedData
break;
case 'max':
threeYearPrice = mappedData
break;
default:
console.log(`Unsupported time period: ${timePeriod}`);
}
setCache($etfTicker, mappedData, 'historicalPrice'+timePeriod);
} catch (e) {
console.log(e);
}
}
}
async function initializePrice() {
output = null;
if (intervalId) {
clearInterval(intervalId);
}
intervalId = setInterval(checkChart, 0);
try {
output = [...data?.getOneDayPrice] ?? [];
oneDayPrice = output?.map(item => ({ time: Date.parse(item?.time), open: item?.open !== null ? item?.open : NaN, high: item?.high !== null ? item?.high : NaN, low: item?.low !== null ? item?.low : NaN, close: item?.close !== null ? item?.close : NaN}));
displayData = oneDayPrice?.length === 0 && sixMonthPrice?.length !== 0 ? '6M' : '1D';
//lastValue = oneDayPrice[oneDayPrice?.length - 1]?.value;
if (displayData === '1D')
{
const length = oneDayPrice?.length;
for (let i = length - 1; i >= 0; i--) {
if (!isNaN(oneDayPrice[i]?.close)) {
lastValue = oneDayPrice[i]?.close;
break;
} }
}
}
else if (displayData === '6M') {
lastValue = sixMonthPrice?.slice(-1)?.at(0)?.close
}
displayLastLogicalRangeValue = oneDayPrice?.length === 0 && sixMonthPrice?.length !== 0 ? (sixMonthPrice?.at(0)?.close ?? sixMonthPrice?.at(0)?.value) : (oneDayPrice?.at(0)?.close ?? oneDayPrice?.at(0)?.value) //previousClose; displayLastLogicalRangeValue = oneDayPrice?.length === 0 && sixMonthPrice?.length !== 0 ? sixMonthPrice?.at(0)?.close : oneDayPrice?.at(0)?.close //previousClose;
//colorChange = lastValue < displayLastLogicalRangeValue ? "#CC3636" : "#367E18";
colorChange = lastValue < displayLastLogicalRangeValue ? "#FF2F1F" : "#10DB06";
topColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.2)" : "rgb(16, 219, 6, 0.2)";
bottomColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.001)" : "rgb(16, 219, 6, 0.001)";
};
//colorChange = lastValue < displayLastLogicalRangeValue ? "#CC3636" : "#367E18";
colorChange = lastValue < displayLastLogicalRangeValue ? "#FF2F1F" : "#10DB06";
topColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.2)" : "rgb(16, 219, 6, 0.2)";
bottomColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.001)" : "rgb(16, 219, 6, 0.001)";
} catch(e) {
console.log(e)
}
};
@ -678,13 +694,11 @@
if ($etfTicker && typeof window !== 'undefined') // add a check to see if running on client-side if ($etfTicker && typeof window !== 'undefined') // add a check to see if running on client-side
{ {
isLoaded = false;
oneDayPrice = []; oneDayPrice = [];
oneWeekPrice = []; oneWeekPrice = [];
oneMonthPrice = []; oneMonthPrice = [];
oneYearPrice = []; oneYearPrice = [];
threeYearPrice = []; threeYearPrice = [];
pastPriceList = [];
geographicList = []; geographicList = [];
sectorList = []; sectorList = [];
@ -714,50 +728,27 @@
//stockDeck = data?.getStockDeckData; //stockDeck = data?.getStockDeckData;
const asyncFunctions = [
getHistoricalPrice(),
getOneDayPrice(),
getPrePostQuote(),
];
Promise.all(asyncFunctions) const asyncFunctions = [
.then((results) => { getPrePostQuote(),
];
isLoaded = true;
})
.catch((error) => {
console.error('An error occurred:', error);
});
Promise.all(asyncFunctions)
.then((results) => {
initializePrice()
})
.catch((error) => {
console.error('An error occurred:', error);
});
} }
} }
$: {
if($etfTicker && displayChartType && output !== null && pastPriceList?.length !== 0 && typeof window !== 'undefined')
{
if(displayChartType === 'line') {
oneDayPrice = output?.map(({ time, close }) => ({ time: Date.parse(time), value: close }));
oneDayPrice = oneDayPrice?.map(item => ({ time: item?.time, value: item?.value !== null ? item?.value : NaN }));
oneWeekPrice = pastPriceList['1W']?.map(({ time, close }) => ({ time: Date.parse(time), value: close }));
oneMonthPrice = pastPriceList['1M']?.map(({ time, close }) => ({ time: Date.parse(time), value: close }));
sixMonthPrice = pastPriceList['6M']?.map(({ time, close }) => ({ time: Date.parse(time), value: close }));
oneYearPrice = pastPriceList['1Y']?.map(({ time, close }) => ({ time: Date.parse(time), value: close }));
threeYearPrice = pastPriceList['MAX']?.map(({ time, close }) => ({ time: Date.parse(time), value: close }));
}
else if (displayChartType === 'candlestick') {
oneDayPrice = output?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
oneDayPrice = oneDayPrice?.map(item => ({ time: item?.time, open: item?.open !== null ? item?.open : NaN, high: item?.high !== null ? item?.high : NaN, low: item?.low !== null ? item?.low : NaN, close: item?.close !== null ? item?.close : NaN}));
oneWeekPrice = pastPriceList['1W']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
oneMonthPrice = pastPriceList['1M']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
sixMonthPrice = pastPriceList['6M']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
oneYearPrice = pastPriceList['1Y']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
threeYearPrice = pastPriceList['MAX']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
}
}
}
$: { $: {
if(form) if(form)
@ -939,7 +930,7 @@
<!--End Ticker Section--> <!--End Ticker Section-->
<!-- Start Graph --> <!-- Start Graph -->
{#if output !== null && pastPriceList?.length !== 0} {#if output !== null}
<div class ="w-full max-w-[540px] md:max-w-[620px] lg:max-w-[570px] xl:max-w-[540px] ml-auto mb-4"> <div class ="w-full max-w-[540px] md:max-w-[620px] lg:max-w-[570px] xl:max-w-[540px] ml-auto mb-4">
{#if displayData === '1D' && oneDayPrice?.length === 0} {#if displayData === '1D' && oneDayPrice?.length === 0}
<h2 class=" mt-20 flex h-[240px] justify-center items-center text-3xl font-bold text-slate-700 mb-20 m-auto"> <h2 class=" mt-20 flex h-[240px] justify-center items-center text-3xl font-bold text-slate-700 mb-20 m-auto">
@ -972,7 +963,7 @@
{#if displayData === '1D'} {#if displayData === '1D'}
{#if displayChartType === 'line'} {#if displayChartType === 'line'}
<AreaSeries <AreaSeries
data={oneDayPrice} data={oneDayPrice?.map(({ time, close }) => ({ time, value: close }))}
lineWidth={1.5} lineWidth={1.5}
priceScaleId="left" priceScaleId="left"
lineColor={colorChange} lineColor={colorChange}
@ -984,7 +975,7 @@
lastPriceAnimation={1} lastPriceAnimation={1}
> >
<PriceLine <PriceLine
price={(oneDayPrice?.at(0)?.close ?? oneDayPrice?.at(0)?.value)} price={oneDayPrice?.at(0)?.close}
lineWidth = {1} lineWidth = {1}
color="#fff" color="#fff"
/> />
@ -997,7 +988,7 @@
priceLineVisible= {false} priceLineVisible= {false}
> >
<PriceLine <PriceLine
price={(oneDayPrice?.at(0)?.close ?? oneDayPrice?.at(0)?.value)} price={oneDayPrice?.at(0)?.close}
lineWidth = {1} lineWidth = {1}
color="#fff" color="#fff"
/> />
@ -1006,7 +997,7 @@
{:else if displayData === '1W'} {:else if displayData === '1W'}
{#if displayChartType === 'line'} {#if displayChartType === 'line'}
<AreaSeries <AreaSeries
data={oneWeekPrice} data={oneWeekPrice?.map(({ time, close }) => ({ time, value: close }))}
lineWidth={1.5} lineWidth={1.5}
priceScaleId="left" priceScaleId="left"
lineColor={colorChange} lineColor={colorChange}
@ -1018,7 +1009,7 @@
lastPriceAnimation={1} lastPriceAnimation={1}
> >
<PriceLine <PriceLine
price={oneWeekPrice?.at(0)?.value} price={oneWeekPrice?.at(0)?.close}
lineWidth = {1} lineWidth = {1}
color="#fff" color="#fff"
/> />
@ -1041,7 +1032,7 @@
{:else if displayData === '1M'} {:else if displayData === '1M'}
{#if displayChartType === 'line'} {#if displayChartType === 'line'}
<AreaSeries <AreaSeries
data={oneMonthPrice} data={oneMonthPrice?.map(({ time, close }) => ({ time, value: close }))}
lineWidth={1.5} lineWidth={1.5}
priceScaleId="left" priceScaleId="left"
lineColor={colorChange} lineColor={colorChange}
@ -1053,7 +1044,7 @@
lastPriceAnimation={1} lastPriceAnimation={1}
> >
<PriceLine <PriceLine
price={oneMonthPrice?.at(0)?.value} price={oneMonthPrice?.at(0)?.close}
lineWidth = {1} lineWidth = {1}
color="#fff" color="#fff"
/> />
@ -1077,7 +1068,7 @@
{:else if displayData === '6M'} {:else if displayData === '6M'}
{#if displayChartType === 'line'} {#if displayChartType === 'line'}
<AreaSeries <AreaSeries
data={sixMonthPrice} data={sixMonthPrice?.map(({ time, close }) => ({ time, value: close }))}
lineWidth={1.5} lineWidth={1.5}
priceScaleId="left" priceScaleId="left"
lineColor={colorChange} lineColor={colorChange}
@ -1089,7 +1080,7 @@
lastPriceAnimation={1} lastPriceAnimation={1}
> >
<PriceLine <PriceLine
price={sixMonthPrice?.at(0)?.value} price={sixMonthPrice?.at(0)?.close}
lineWidth = {1} lineWidth = {1}
color="#fff" color="#fff"
/> />
@ -1114,7 +1105,7 @@
{:else if displayData === '1Y'} {:else if displayData === '1Y'}
{#if displayChartType === 'line'} {#if displayChartType === 'line'}
<AreaSeries <AreaSeries
data={oneYearPrice} data={oneYearPrice?.map(({ time, close }) => ({ time, value: close }))}
lineWidth={1.5} lineWidth={1.5}
priceScaleId="left" priceScaleId="left"
lineColor={colorChange} lineColor={colorChange}
@ -1126,7 +1117,7 @@
lastPriceAnimation={1} lastPriceAnimation={1}
> >
<PriceLine <PriceLine
price={oneYearPrice?.at(0)?.value} price={oneYearPrice?.at(0)?.close}
lineWidth = {1} lineWidth = {1}
color="#fff" color="#fff"
/> />
@ -1151,7 +1142,7 @@
{:else if displayData === 'MAX'} {:else if displayData === 'MAX'}
{#if displayChartType === 'line'} {#if displayChartType === 'line'}
<AreaSeries <AreaSeries
data={threeYearPrice} data={threeYearPrice?.map(({ time, close }) => ({ time, value: close }))}
lineWidth={1.5} lineWidth={1.5}
priceScaleId="left" priceScaleId="left"
lineColor={colorChange} lineColor={colorChange}
@ -1163,7 +1154,7 @@
lastPriceAnimation={1} lastPriceAnimation={1}
> >
<PriceLine <PriceLine
price={threeYearPrice?.at(0)?.value} price={threeYearPrice?.at(0)?.close}
lineWidth = {1} lineWidth = {1}
color="#fff" color="#fff"
/> />
@ -1185,7 +1176,7 @@
{/if} {/if}
</Chart> </Chart>
{/if} {/if}

View File

@ -147,7 +147,6 @@ export const load = async ({ params, locals, cookies, setHeaders}) => {
fetchData(apiURL,'/wiim',params.tickerID), fetchData(apiURL,'/wiim',params.tickerID),
fetchData(apiURL,'/top-etf-ticker-holder',params.tickerID), fetchData(apiURL,'/top-etf-ticker-holder',params.tickerID),
fetchData(apiURL,'/value-at-risk',params.tickerID), fetchData(apiURL,'/value-at-risk',params.tickerID),
fetchData(apiURL,'/historical-price',params.tickerID),
fetchData(apiURL,'/one-day-price',params.tickerID), fetchData(apiURL,'/one-day-price',params.tickerID),
fetchWatchlist(fastifyURL, locals?.user?.id), fetchWatchlist(fastifyURL, locals?.user?.id),
fetchPortfolio(fastifyURL, locals?.user?.id), fetchPortfolio(fastifyURL, locals?.user?.id),
@ -167,7 +166,6 @@ export const load = async ({ params, locals, cookies, setHeaders}) => {
getWhyPriceMoved, getWhyPriceMoved,
getTopETFHolder, getTopETFHolder,
getVaR, getVaR,
getHistoricalPrice,
getOneDayPrice, getOneDayPrice,
getUserWatchlist, getUserWatchlist,
getUserPortfolio, getUserPortfolio,
@ -193,7 +191,6 @@ export const load = async ({ params, locals, cookies, setHeaders}) => {
getWhyPriceMoved, getWhyPriceMoved,
getTopETFHolder, getTopETFHolder,
getVaR, getVaR,
getHistoricalPrice,
getOneDayPrice, getOneDayPrice,
getUserWatchlist, getUserWatchlist,
getUserPortfolio, getUserPortfolio,

View File

@ -3,7 +3,7 @@
import {AreaSeries, Chart, PriceLine, CandlestickSeries} from 'svelte-lightweight-charts'; import {AreaSeries, Chart, PriceLine, CandlestickSeries} from 'svelte-lightweight-charts';
import { TrackingModeExitMode } from 'lightweight-charts'; import { TrackingModeExitMode } from 'lightweight-charts';
import {screenWidth, displayCompanyName, numberOfUnreadNotification, globalForm, shareholderComponent, trendAnalysisComponent, revenueSegmentationComponent, priceAnalysisComponent, fundamentalAnalysisComponent, userRegion, isCrosshairMoveActive, realtimePrice, priceIncrease, currentPortfolioPrice, currentPrice, clientSideCache, stockTicker, isOpen, isBeforeMarketOpen, isWeekend} from '$lib/store'; import {getCache, setCache, screenWidth, displayCompanyName, numberOfUnreadNotification, globalForm, shareholderComponent, trendAnalysisComponent, revenueSegmentationComponent, priceAnalysisComponent, fundamentalAnalysisComponent, userRegion, isCrosshairMoveActive, realtimePrice, priceIncrease, currentPortfolioPrice, currentPrice, clientSideCache, stockTicker, isOpen, isBeforeMarketOpen, isWeekend} from '$lib/store';
import { onDestroy, onMount } from 'svelte'; import { onDestroy, onMount } from 'svelte';
import StockKeyInformation from '$lib/components/StockKeyInformation.svelte'; import StockKeyInformation from '$lib/components/StockKeyInformation.svelte';
import BullBearSay from '$lib/components/BullBearSay.svelte'; import BullBearSay from '$lib/components/BullBearSay.svelte';
@ -25,14 +25,11 @@
export let data; export let data;
export let form; export let form;
let isLoaded = false;
let displayChartType = 'line'; let displayChartType = 'line';
let pricePrediction = data?.getPricePrediction ?? [];
let stockDeck = data?.getStockDeck ?? []; let stockDeck = data?.getStockDeck ?? [];
let fairPrice = data?.getFairPrice ?? []; let fairPrice = data?.getFairPrice ?? [];
let correlationList = data?.getCorrelation?.correlation ?? []; let correlationList = data?.getCorrelation?.correlation ?? [];
let modelStats = data?.getTradingSignals ?? {};
let prePostData = {}; let prePostData = {};
let similarstock = []; let similarstock = [];
let topETFHolder = []; let topETFHolder = [];
@ -176,122 +173,125 @@ $: {
let displayData; let displayData;
let colorChange; let colorChange;
let topColorChange; let topColorChange;
let bottomColorChange; let bottomColorChange;
let lastValue; let lastValue;
async function changeData(state) { async function changeData(state) {
switch (state) { switch (state) {
case '1D': case '1D':
displayData = '1D'; displayData = '1D';
if(oneDayPrice?.length !== 0) if(oneDayPrice?.length !== 0)
{ {
displayLastLogicalRangeValue = oneDayPrice?.at(0)?.close; //previousClose displayLastLogicalRangeValue = oneDayPrice?.at(0)?.close; //previousClose
const length = oneDayPrice?.length; const length = oneDayPrice?.length;
for (let i = length - 1; i >= 0; i--) { for (let i = length - 1; i >= 0; i--) {
if (!isNaN(oneDayPrice[i]?.close)) { if (!isNaN(oneDayPrice[i]?.close)) {
lastValue = oneDayPrice[i]?.close; lastValue = oneDayPrice[i]?.close;
break; break;
}
} }
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
} }
}
else {
displayLastLogicalRangeValue = null;
lastValue = null;
break; }
case '1W': break;
displayData = '1W'; case '1W':
if(oneWeekPrice?.length !== 0) displayData = '1W';
{ await historicalPrice('one-week')
displayLastLogicalRangeValue = oneWeekPrice?.at(0)?.close; if(oneWeekPrice?.length !== 0)
lastValue = oneWeekPrice?.slice(-1)?.at(0)?.close; {
displayLastLogicalRangeValue = oneWeekPrice?.at(0)?.close;
lastValue = oneWeekPrice?.slice(-1)?.at(0)?.close;
} }
else { else {
displayLastLogicalRangeValue = null; displayLastLogicalRangeValue = null;
lastValue = null; lastValue = null;
} }
break; break;
case '1M': case '1M':
displayData = '1M'; displayData = '1M';
if(oneMonthPrice?.length !== 0) await historicalPrice('one-month')
{ if(oneMonthPrice?.length !== 0)
displayLastLogicalRangeValue = oneMonthPrice?.at(0)?.close; {
lastValue = oneMonthPrice.slice(-1)?.at(0)?.close; displayLastLogicalRangeValue = oneMonthPrice?.at(0)?.close;
lastValue = oneMonthPrice.slice(-1)?.at(0)?.close;
} }
else { else {
displayLastLogicalRangeValue = null; displayLastLogicalRangeValue = null;
lastValue = null; lastValue = null;
} }
break; break;
case '6M': case '6M':
displayData = '6M'; displayData = '6M';
if(sixMonthPrice?.length !== 0) await historicalPrice('six-months')
{ if(sixMonthPrice?.length !== 0)
displayLastLogicalRangeValue = sixMonthPrice?.at(0)?.close; {
lastValue = sixMonthPrice?.slice(-1)?.at(0)?.close; displayLastLogicalRangeValue = sixMonthPrice?.at(0)?.close;
lastValue = sixMonthPrice?.slice(-1)?.at(0)?.close;
} }
else { else {
displayLastLogicalRangeValue = null; displayLastLogicalRangeValue = null;
lastValue = null; lastValue = null;
} }
break; break;
case '1Y': case '1Y':
displayData = '1Y'; displayData = '1Y';
if(oneYearPrice?.length !== 0) await historicalPrice('one-year')
{ if(oneYearPrice?.length !== 0)
displayLastLogicalRangeValue = oneYearPrice?.at(0)?.close; {
lastValue = oneYearPrice.slice(-1)?.at(0)?.close; displayLastLogicalRangeValue = oneYearPrice?.at(0)?.close;
} lastValue = oneYearPrice.slice(-1)?.at(0)?.close;
else { }
displayLastLogicalRangeValue = null; else {
lastValue = null; displayLastLogicalRangeValue = null;
} lastValue = null;
}
break; break;
case 'MAX': case 'MAX':
displayData = 'MAX'; displayData = 'MAX';
if(threeYearPrice?.length !== 0) await historicalPrice('max')
{ if(threeYearPrice?.length !== 0)
displayLastLogicalRangeValue = threeYearPrice?.at(0)?.close; {
lastValue = threeYearPrice.slice(-1)?.at(0)?.close; displayLastLogicalRangeValue = threeYearPrice?.at(0)?.close;
lastValue = threeYearPrice.slice(-1)?.at(0)?.close;
} }
else { else {
displayLastLogicalRangeValue = null; displayLastLogicalRangeValue = null;
lastValue = null; lastValue = null;
} }
break; break;
default: default:
return; return;
}
colorChange = lastValue < displayLastLogicalRangeValue ? "#FF2F1F" : "#10DB06";
topColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.2)" : "rgb(16, 219, 6, 0.2)";
bottomColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.001)" : "rgb(16, 219, 6, 0.001)";
fitContentChart();
//trackButtonClick('Time Period: '+ state)
} }
colorChange = lastValue < displayLastLogicalRangeValue ? "#FF2F1F" : "#10DB06";
topColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.2)" : "rgb(16, 219, 6, 0.2)";
bottomColorChange = lastValue < displayLastLogicalRangeValue ? "rgb(255, 47, 31, 0.001)" : "rgb(16, 219, 6, 0.001)";
fitContentChart();
//trackButtonClick('Time Period: '+ state)
}
@ -310,10 +310,88 @@ $: {
let oneYearPrice = []; let oneYearPrice = [];
let threeYearPrice = []; let threeYearPrice = [];
let pastPriceList = [];
async function historicalPrice(timePeriod:string) {
const cachedData = getCache($stockTicker, 'historicalPrice'+timePeriod);
if (cachedData) {
switch (timePeriod) {
case 'one-week':
oneWeekPrice = cachedData
break;
case 'one-month':
oneMonthPrice = cachedData
break;
case 'six-months':
sixMonthPrice = cachedData
break;
case 'one-year':
oneYearPrice = cachedData
break;
case 'max':
threeYearPrice = cachedData
break;
default:
console.log(`Unsupported time period: ${timePeriod}`);
}
} else {
output = null;
const postData = {
ticker: $stockTicker,
timePeriod: timePeriod,
};
const response = await fetch(apiURL+'/historical-price', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData)
});
output = await response?.json() ?? [];
const mapData = (data) => data?.map(({ time, open, high, low, close }) => ({
time: Date.parse(time),
open,
high,
low,
close
}));
const mappedData = mapData(output);
try {
switch (timePeriod) {
case 'one-week':
oneWeekPrice = mappedData
break;
case 'one-month':
oneMonthPrice = mappedData
break;
case 'six-months':
sixMonthPrice = mappedData
break;
case 'one-year':
oneYearPrice = mappedData
break;
case 'max':
threeYearPrice = mappedData
break;
default:
console.log(`Unsupported time period: ${timePeriod}`);
}
setCache($stockTicker, mappedData, 'historicalPrice'+timePeriod);
} catch (e) {
console.log(e);
}
}
}
async function initializePrice() { async function initializePrice() {
@ -325,16 +403,9 @@ $: {
try { try {
output = [...data?.getOneDayPrice] ?? []; output = [...data?.getOneDayPrice] ?? [];
oneDayPrice = data?.getOneDayPrice;
pastPriceList = data?.getHistoricalPrice;
oneDayPrice = output?.map(item => ({ time: Date.parse(item?.time), open: item?.open !== null ? item?.open : NaN, high: item?.high !== null ? item?.high : NaN, low: item?.low !== null ? item?.low : NaN, close: item?.close !== null ? item?.close : NaN})); oneDayPrice = output?.map(item => ({ time: Date.parse(item?.time), open: item?.open !== null ? item?.open : NaN, high: item?.high !== null ? item?.high : NaN, low: item?.low !== null ? item?.low : NaN, close: item?.close !== null ? item?.close : NaN}));
oneWeekPrice = pastPriceList['1W']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
oneMonthPrice = pastPriceList['1M']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
sixMonthPrice = pastPriceList['6M']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
oneYearPrice = pastPriceList['1Y']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
threeYearPrice = pastPriceList['MAX']?.map(({ time, open,high,low,close }) => ({ time: Date.parse(time), open,high,low,close }));
displayData = oneDayPrice?.length === 0 && sixMonthPrice?.length !== 0 ? '6M' : '1D'; displayData = oneDayPrice?.length === 0 && sixMonthPrice?.length !== 0 ? '6M' : '1D';
//lastValue = oneDayPrice[oneDayPrice?.length - 1]?.value; //lastValue = oneDayPrice[oneDayPrice?.length - 1]?.value;
@ -609,13 +680,11 @@ function changeChartType() {
if ($stockTicker && typeof window !== 'undefined') // add a check to see if running on client-side if ($stockTicker && typeof window !== 'undefined') // add a check to see if running on client-side
{ {
isLoaded = false;
oneDayPrice = []; oneDayPrice = [];
oneWeekPrice = []; oneWeekPrice = [];
oneMonthPrice = []; oneMonthPrice = [];
oneYearPrice = []; oneYearPrice = [];
threeYearPrice = []; threeYearPrice = [];
pastPriceList = [];
optionsDict = {}; optionsDict = {};
prePostData = {}; prePostData = {};
marketMoods = {}; marketMoods = {};
@ -626,8 +695,6 @@ function changeChartType() {
fairPrice = data?.getFairPrice; fairPrice = data?.getFairPrice;
pricePrediction = data?.getPricePrediction;
modelStats = data?.getTradingSignals;
stockDeck = data?.getStockDeck; stockDeck = data?.getStockDeck;
correlationList = data?.getCorrelation?.correlation; correlationList = data?.getCorrelation?.correlation;
previousClose = data?.getStockQuote?.previousClose; previousClose = data?.getStockQuote?.previousClose;
@ -652,7 +719,6 @@ function changeChartType() {
Promise.all(asyncFunctions) Promise.all(asyncFunctions)
.then((results) => { .then((results) => {
initializePrice() initializePrice()
isLoaded = true;
}) })
.catch((error) => { .catch((error) => {
console.error('An error occurred:', error); console.error('An error occurred:', error);
@ -847,7 +913,7 @@ function changeChartType() {
<!--End Ticker Section--> <!--End Ticker Section-->
<!-- Start Graph --> <!-- Start Graph -->
{#if output !== null && pastPriceList?.length !== 0} {#if output !== null}
<div class ="w-full sm:pl-7 ml-auto max-w-3xl mb-10"> <div class ="w-full sm:pl-7 ml-auto max-w-3xl mb-10">
{#if displayData === '1D' && oneDayPrice?.length === 0} {#if displayData === '1D' && oneDayPrice?.length === 0}
<h2 class=" mt-20 flex h-[240px] justify-center items-center text-3xl font-bold text-slate-700 mb-20 m-auto"> <h2 class=" mt-20 flex h-[240px] justify-center items-center text-3xl font-bold text-slate-700 mb-20 m-auto">
@ -1295,36 +1361,6 @@ function changeChartType() {
<!--Start Price Prediction Model-->
<!--
<div class="w-full m-auto pt-10 sm:pl-6 sm:pb-6 sm:pt-6">
{#if PricePredictionCard}
<PricePredictionCard
pricePrediction={pricePrediction}
pastPriceList={pastPriceList}
lastPrice={data?.getStockQuote?.previousClose}
assetType = 'stock'
/>
{/if}
</div>
-->
<!--End Price Prediction Model-->
<!--Start Trading Model-->
<!--
<div class="w-full pt-10 m-auto sm:pl-6 sm:pb-6 sm:pt-6 mb-0 {Object?.keys(modelStats)?.length !== 0 ? '' : 'hidden'}">
{#if TradingModel }
<TradingModel modelStats={modelStats}/>
{/if}
</div>
-->
<!--End Trading Model-->
<div class="w-full pt-10 m-auto sm:pl-6 sm:pb-6 sm:pt-6 rounded-2xl {Object?.keys(taRating)?.length !== 0 ? '' : 'hidden'} "> <div class="w-full pt-10 m-auto sm:pl-6 sm:pb-6 sm:pt-6 rounded-2xl {Object?.keys(taRating)?.length !== 0 ? '' : 'hidden'} ">