update stock layout

This commit is contained in:
MuslemRahimi 2024-11-22 01:33:47 +01:00
parent 3c2d7f3747
commit b5f1fcc6db
4 changed files with 154 additions and 308 deletions

View File

@ -43,6 +43,9 @@ export const clearCache = () => {
clientSideCache.set({});
};
export const displayLegend = writable(<Array<any>>{});
export const showCookieConsent = writable(<boolean>false);
export const shouldUpdatePriceChart = writable(<boolean>false);
export const coolMode = writable(<boolean>false);

View File

@ -42,7 +42,7 @@ const fetchWatchlist = async (pb, userId) => {
return output;
};
export const load = async ({ params, locals }) => {
export const load = async ({ params, locals, setHeaders }) => {
const { apiURL, apiKey, pb, user } = locals;
const { tickerID } = params;
@ -50,6 +50,7 @@ export const load = async ({ params, locals }) => {
"/stockdeck",
"/analyst-summary-rating",
"/stock-quote",
"/pre-post-quote",
"/bull-bear-say",
"/wiim",
"/one-day-price",
@ -70,6 +71,7 @@ export const load = async ({ params, locals }) => {
getStockDeck,
getAnalystRating,
getStockQuote,
getPrePostQuote,
getBullBearSay,
getWhyPriceMoved,
getOneDayPrice,
@ -80,10 +82,14 @@ export const load = async ({ params, locals }) => {
getUserWatchlist,
] = await Promise.all(promises);
setHeaders({ "cache-control": "public, max-age=60" });
return {
getStockDeck,
getAnalystRating,
getStockQuote,
getPrePostQuote,
getBullBearSay,
getWhyPriceMoved,
getOneDayPrice,

View File

@ -13,7 +13,10 @@
priceIncrease,
stockTicker,
displayCompanyName,
displayLegend,
isOpen,
isBeforeMarketOpen,
isWeekend,
shouldUpdatePriceChart,
priceChartData,
} from "$lib/store";
@ -23,8 +26,10 @@
import toast from "svelte-french-toast";
import Markethour from "$lib/components/Markethour.svelte";
import AIScore from "$lib/components/AIScore.svelte";
import { convertTimestamp } from "$lib/utils";
export let data;
let prePostData = data?.getPrePostQuote || {};
$: $realtimePrice = data?.getStockQuote?.price?.toFixed(2);
let previousRealtimePrice = null;
@ -277,6 +282,7 @@ function handleTypeOfTrade(state:string)
// add a check to see if running on client-side
$currentPortfolioPrice = data?.getStockQuote?.price;
prePostData = data?.getPrePostQuote || {};
}
}
@ -285,7 +291,7 @@ function handleTypeOfTrade(state:string)
item.user === data?.user?.id && item.ticker?.includes($stockTicker),
);
$: charNumber = $screenWidth < 640 ? 15 : 25;
$: charNumber = $screenWidth < 640 ? 25 : 40;
$: {
if (
@ -326,7 +332,7 @@ function handleTypeOfTrade(state:string)
class="bg-[#09090B] w-full max-w-screen sm:max-w-7xl min-h-screen xl:max-w-screen-2xl overflow-hidden"
>
<!-- Page wrapper -->
<div class="flex flex-col w-full mt-5 relative w-full">
<div class="mt-5 flex flex-col w-full relative w-full">
<main class="grow w-full">
<section class="w-full">
<div class="w-full">
@ -361,9 +367,7 @@ function handleTypeOfTrade(state:string)
? "hidden"
: "flex flex-col items-center ml-6 transition-transform ease-in"}
>
<span
class="text-white text-[0.70rem] font-medium text-opacity-[0.6]"
>
<span class="text-white text-xs font-semibold">
{$stockTicker}
</span>
<span class="text-white font-medium text-sm">
@ -673,29 +677,106 @@ function handleTypeOfTrade(state:string)
<div
class="flex flex-row justify-start w-full items-center"
>
<div class="flex flex-col items-start ml-2 sm:ml-3">
<span class="text-md sm:text-lg text-blue-400">
{$stockTicker?.toUpperCase()}
</span>
<span
class="text-xl sm:text-2xl font-semibold sm:font-bold text-white"
>
{$displayCompanyName?.length > charNumber
? $displayCompanyName?.slice(0, charNumber) +
"..."
: $displayCompanyName}
</span>
</div>
<div
class="ml-auto {$scoreComponent === false
? 'invisible'
: ''}"
class="flex flex-col items-start ml-2 sm:ml-3 w-full"
>
<AIScore
score={data?.getStockDeck?.score}
tier={data?.user?.tier}
/>
<div
class="flex flex-row justify-between items-center w-full"
>
<span
class="text-2xl lg:text-3xl font-bold text-white"
>
{$displayCompanyName?.length > charNumber
? $displayCompanyName?.slice(0, charNumber) +
"..."
: $displayCompanyName}
({$stockTicker?.toUpperCase()})
</span>
<div
class="items-end justify-end {$scoreComponent ===
false
? '-mt-8 invisible'
: ''}"
>
<AIScore
score={data?.getStockDeck?.score}
tier={data?.user?.tier}
/>
</div>
</div>
<div
class="sm:-mt-8 mb-5 flex flex-row items-end space-x-2 xs:space-x-3 sm:space-x-5 text-white"
>
<div class="max-w-[50%]">
<div
class="text-3xl sm:text-4xl font-bold block sm:inline"
>
{$displayLegend?.close}
</div>
<div
class="font-semibold block text-lg xs:text-xl sm:inline sm:text-2xl {$displayLegend?.change >=
0
? "before:content-['+'] text-[#00FC50]"
: 'text-[#FF2F1F]'}"
>
{$displayLegend?.change}%
</div>
<div class="mt-0.5 text-sm bp:text-sm">
<span class="block font-semibold sm:inline"
>At close:</span
>
{$displayLegend?.date}
</div>
</div>
{#if Object?.keys(prePostData)?.length !== 0}
<div
class="border-l border-default pl-3 bp:pl-5"
>
<div
class="block text-2xl sm:text-[1.7rem] font-semibold leading-5 text-faded sm:inline"
>
{prePostData?.price?.toFixed(2)}
</div>
<div
class="mt-1.5 block text-sm xs:text-base sm:mt-0 sm:inline sm:text-lg {prePostData?.changesPercentage >=
0
? "before:content-['+'] text-[#00FC50]"
: 'text-[#FF2F1F]'}"
>
{prePostData?.changesPercentage?.toFixed(
2,
)}%
</div>
<div class="mt-1 text-sm sm:flex">
<span class="flex items-center"
><svg
class="h-4 w-4 inline text-blue-400"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
style="max-width:40px"
><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"
></path></svg
>
<span
class="ml-0.5 whitespace-nowrap font-semibold md:ml-1"
>After-hours:</span
></span
>
<span class="sm:ml-1"
>{convertTimestamp(
prePostData?.time / 1000,
)}</span
>
</div>
</div>
{/if}
</div>
</div>
</div>
</div>
@ -818,103 +899,11 @@ function handleTypeOfTrade(state:string)
{/if}
<!--End Login Modal-->
<!--
{#if BuyTrade}
<BuyTrade
data = {data}
holdingShares={holdingShares}
availableCash = {availableCash}
/>
{/if}
{#if SellTrade}
<SellTrade
data = {data}
holdingShares={holdingShares}
availableCash = {availableCash}
/>
{/if}
{#if AddPortfolio}
<AddPortfolio data={data}/>
{/if}
-->
<!--Start SellTrade Modal-->
{#if PriceAlert}
<PriceAlert {data} />
{/if}
<!--End SellTrade Modal-->
<!--Start Type of Trade-->
<!--
<input type="checkbox" id="typeOfTrade" class="modal-toggle" />
<dialog id="typeOfTrade" class="modal modal-bottom sm:modal-middle overflow-hidden">
<label for="typeOfTrade" class="cursor-pointer modal-backdrop bg-[#fff] bg-opacity-[0.08]"></label>
<div class="modal-box w-full bg-[#000] border border-slate-600 pb-10">
<div class= "flex flex-col">
<div class="text-white text-md flex flex-col flex-shrink-0">
<div class="rounded-full w-10 h-10 relative bg-gray-900 mb-2">
<img class="rounded-full w-6 h-6 absolute inset-1/2 transform -translate-x-1/2 -translate-y-1/2" src={`https://financialmodelingprep.com/image-stock/${$stockTicker}.png`} />
</div>
<span class="mb-1">
{$displayCompanyName?.length > 30 ? $displayCompanyName?.slice(0, 30) + "..." : $displayCompanyName}
</span>
<div class="flex flex-row items-center mb-10">
<span class="mb-1 text-sm font-medium">
Current Price: ${$currentPortfolioPrice}
</span>
<span class="text-blue-400 text-sm font-medium ml-auto">
Holding Shares: {holdingShares}
</span>
</div>
</div>
</div>
<div class="text-white">
<h3 class="font-bold text-2xl mb-5">
Type of Trade
</h3>
<ul class="menu dropdown-content text-white bg-[#000] rounded -ml-6">
<li class="mb-3">
<label for="typeOfTrade" on:click={() => handleTypeOfTrade('buy')} class="cursor-pointer flex flex-row justify-start items-center">
<div class="rounded-full w-10 h-10 relative bg-gray-800">
<svg class="h-5 w-5 absolute inset-1/2 transform -translate-x-1/2 -translate-y-1/2" viewBox="0 0 16 16" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="green"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <rect width="16" height="16" id="icon-bound" fill="none"></rect> <path d="M0,11h11.2l-2.6,2.6L10,15l6-6H0V11z M4.8,5l2.6-2.6L6,1L0,7h16V5H4.8z"></path> </g></svg>
</div>
<span class="ml-1 text-white text-lg font-medium">Buy {$stockTicker} Shares</span>
</label>
</li>
<li class="mb-3">
<label for="typeOfTrade" on:click={() => handleTypeOfTrade('sell')} class="cursor-pointer flex flex-row justify-start items-center">
<div class="rounded-full w-10 h-10 relative bg-gray-800">
<svg class="h-5 w-5 absolute inset-1/2 transform -translate-x-1/2 -translate-y-1/2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="red" d="M14.25 21.4q-.575.575-1.425.575T11.4 21.4l-8.8-8.8q-.275-.275-.438-.65T2 11.15V4q0-.825.588-1.413T4 2h7.15q.425 0 .8.163t.65.437l8.8 8.825q.575.575.575 1.413T21.4 14.25l-7.15 7.15ZM6.5 8q.625 0 1.063-.438T8 6.5q0-.625-.438-1.063T6.5 5q-.625 0-1.063.438T5 6.5q0 .625.438 1.063T6.5 8Z"/></svg>
</div>
<span class="ml-1 text-white text-lg font-medium">
Sell {$stockTicker} Shares
</span>
</label>
</li>
</ul>
</div>
</div>
</dialog>
-->
<!--End Type of Trade-->
<!--Start Add Watchlist Modal-->
<input type="checkbox" id="addWatchListModal" class="modal-toggle" />

View File

@ -6,17 +6,14 @@
setCache,
numberOfUnreadNotification,
globalForm,
isCrosshairMoveActive,
realtimePrice,
priceIncrease,
wsBidPrice,
wsAskPrice,
displayLegend,
currentPortfolioPrice,
stockTicker,
displayCompanyName,
isOpen,
isBeforeMarketOpen,
isWeekend,
shouldUpdatePriceChart,
priceChartData,
} from "$lib/store";
@ -38,7 +35,6 @@
export let data;
export let form;
let prePostData = {};
let stockDeck = {};
$: previousClose = data?.getStockQuote?.previousClose;
@ -60,52 +56,55 @@
$: {
if (output !== null) {
let change;
let graphChange;
let currentDataRow;
let baseClose;
let currentDataRowOneDay;
let baseClose = previousClose;
let graphBaseClose;
const length = oneDayPrice?.length;
for (let i = length - 1; i >= 0; i--) {
if (!isNaN(oneDayPrice[i]?.close)) {
currentDataRowOneDay = oneDayPrice[i];
break;
}
}
// Determine current data row and base close price based on displayData
switch (displayData) {
case "1D":
const length = oneDayPrice?.length;
for (let i = length - 1; i >= 0; i--) {
if (!isNaN(oneDayPrice[i]?.close)) {
currentDataRow = oneDayPrice[i];
break;
}
}
baseClose = previousClose;
break;
case "1W":
currentDataRow = oneWeekPrice?.at(-1); // Latest entry for 1 week
baseClose = oneWeekPrice?.[0]?.close;
graphBaseClose = oneWeekPrice?.at(0)?.close;
break;
case "1M":
currentDataRow = oneMonthPrice?.at(-1); // Latest entry for 1 month
baseClose = oneMonthPrice?.[0]?.close;
graphBaseClose = oneMonthPrice?.at(0)?.close;
break;
case "6M":
currentDataRow = sixMonthPrice?.at(-1); // Latest entry for 6 months
baseClose = sixMonthPrice?.[0]?.close;
graphBaseClose = sixMonthPrice?.at(0)?.close;
break;
case "1Y":
currentDataRow = oneYearPrice?.at(-1); // Latest entry for 1 year
baseClose = oneYearPrice?.[0]?.close;
graphBaseClose = oneYearPrice?.at(0)?.close;
break;
case "MAX":
currentDataRow = maxPrice?.at(-1); // Latest entry for MAX range
baseClose = maxPrice?.[0]?.close;
graphBaseClose = maxPrice?.at(0)?.close;
break;
}
// Calculate percentage change if baseClose and currentDataRow are valid
const closeValue =
displayData === "1D" &&
!$isCrosshairMoveActive &&
$realtimePrice !== null
? $realtimePrice
: (currentDataRowOneDay?.close ?? currentDataRowOneDay?.value);
const graphCloseValue =
$realtimePrice !== null
? $realtimePrice
: (currentDataRow?.close ?? currentDataRow?.value);
@ -114,8 +113,12 @@
change = ((closeValue / baseClose - 1) * 100).toFixed(2);
}
if (graphCloseValue && graphBaseClose) {
graphChange = ((graphCloseValue / graphBaseClose - 1) * 100).toFixed(2);
}
// Format date
const date = new Date(currentDataRow?.time * 1000);
const date = new Date(currentDataRowOneDay?.time * 1000);
const options = {
day: "2-digit",
@ -127,14 +130,7 @@
};
//const formattedDate = (displayData === '1D' || displayData === '1W' || displayData === '1M') ? date.toLocaleString('en-GB', options).replace(/\//g, '.') : date.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' }).replace(/\//g, '.');
const formattedDate =
displayData === "1D" || displayData === "1W" || displayData === "1M"
? date.toLocaleString("en-US", options)
: new Date(currentDataRow?.time)?.toLocaleDateString("en-US", {
day: "2-digit",
month: "short",
year: "numeric",
});
const formattedDate = date?.toLocaleString("en-US", options);
const safeFormattedDate =
formattedDate === "Invalid Date"
@ -142,13 +138,13 @@
: formattedDate;
// Set display legend
displayLegend = {
$displayLegend = {
close:
currentDataRow?.value ??
currentDataRow?.close ??
data?.getStockQuote?.price,
currentDataRowOneDay?.close?.toFixed(2) ??
data?.getStockQuote?.price?.toFixed(2),
date: safeFormattedDate,
change,
graphChange: displayData === "1D" ? change : graphChange,
};
}
}
@ -422,33 +418,7 @@
}
}
async function getPrePostQuote() {
if (!$isOpen) {
const postData = { ticker: $stockTicker, path: "pre-post-quote" };
const response = await fetch("/api/ticker-data", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(postData),
});
prePostData = await response.json();
}
}
let currentDataRow = { value: "-", date: "-" };
let lineLegend = null;
let displayLegend = { close: "-", date: "-" };
function handleSeriesReference(ref) {
try {
lineLegend = ref;
} catch (error) {
console.log(error);
}
}
$displayLegend = { close: "-", date: "-" };
let displayLastLogicalRangeValue;
@ -747,20 +717,11 @@
oneMonthPrice = [];
oneYearPrice = [];
maxPrice = [];
prePostData = {};
output = null;
stockDeck = data?.getStockDeck; // Essential otherwise chart will not be updated since we wait until #layout.server.ts server response is finished
const asyncFunctions = [getPrePostQuote()];
Promise.all(asyncFunctions)
.then((results) => {
initializePrice();
})
.catch((error) => {
console.error("An error occurred:", error);
});
initializePrice();
}
}
</script>
@ -812,99 +773,6 @@
<!-- Main content -->
<div class="pb-12 md:pb-20 w-full sm:pr-6 xl:pr-0">
<div class="xl:pr-10">
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-label-has-associated-control -->
<div class="flex flex-row items-start w-full sm:pl-6 mt-4">
<div class="flex flex-col items-start justify-start w-full">
<div
class="text-2xl md:text-3xl font-bold text-white flex flex-row items-center w-full"
>
{$realtimePrice ?? displayLegend?.close}
{#if $priceIncrease === true}
<div
style="background-color: green;"
class="inline-block pulse rounded-full w-3 h-3 ml-2"
></div>
{:else if $priceIncrease === false}
<div
style="background-color: red;"
class="inline-block pulse rounded-full w-3 h-3 ml-2"
></div>
{/if}
</div>
<div class="flex flex-row items-center w-full">
<span
class="items-center justify-start {displayLegend?.change > 0
? "before:content-['+'] text-[#00FC50]"
: 'text-[#FF2F1F]'} font-medium text-xs sm:text-sm"
>{displayLegend?.change ?? "-"}%</span
>
<span class="ml-3 text-white text-xs sm:text-sm"
>{displayLegend?.date}</span
>
</div>
</div>
<div class="ml-auto">
{#if Object?.keys(prePostData)?.length !== 0 && prePostData?.price !== 0}
<div class="flex flex-col justify-end items-end">
<div class="flex flex-row items-center justify-end">
<span class="text-white text-lg sm:text-2xl font-bold">
{prePostData?.price}
</span>
{#if prePostData?.changesPercentage >= 0}
<span
class="ml-1 items-center justify-start text-[#00FC50] font-medium text-xs sm:text-sm"
>({prePostData?.changesPercentage}%)</span
>
{:else if prePostData?.changesPercentage < 0}
<span
class="ml-1 items-center justify-start text-[#FF2F1F] font-medium text-xs sm:text-sm"
>({prePostData?.changesPercentage}%)</span
>
{/if}
</div>
{#if $isBeforeMarketOpen && !$isOpen && !$isWeekend}
<div
class="flex flex-row items-center justify-end text-white text-xs sm:text-sm font-normal text-end w-24"
>
<span>Pre-market:</span>
<svg
class="ml-1 w-4 h-4 inline-block"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 256 256"
><path
fill="#EA9703"
d="M120 40V16a8 8 0 0 1 16 0v24a8 8 0 0 1-16 0m72 88a64 64 0 1 1-64-64a64.07 64.07 0 0 1 64 64m-16 0a48 48 0 1 0-48 48a48.05 48.05 0 0 0 48-48M58.34 69.66a8 8 0 0 0 11.32-11.32l-16-16a8 8 0 0 0-11.32 11.32Zm0 116.68l-16 16a8 8 0 0 0 11.32 11.32l16-16a8 8 0 0 0-11.32-11.32M192 72a8 8 0 0 0 5.66-2.34l16-16a8 8 0 0 0-11.32-11.32l-16 16A8 8 0 0 0 192 72m5.66 114.34a8 8 0 0 0-11.32 11.32l16 16a8 8 0 0 0 11.32-11.32ZM48 128a8 8 0 0 0-8-8H16a8 8 0 0 0 0 16h24a8 8 0 0 0 8-8m80 80a8 8 0 0 0-8 8v24a8 8 0 0 0 16 0v-24a8 8 0 0 0-8-8m112-88h-24a8 8 0 0 0 0 16h24a8 8 0 0 0 0-16"
/></svg
>
</div>
{:else}
<div
class="flex flex-row items-center justify-end text-white text-xs sm:text-sm font-normal text-end w-28"
>
<span>After-hours:</span>
<svg
class="ml-1 w-4 h-4 inline-block"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 256 256"
><path
fill="#70A1EF"
d="M232.13 143.64a6 6 0 0 0-6-1.49a90.07 90.07 0 0 1-112.27-112.3a6 6 0 0 0-7.49-7.48a102.88 102.88 0 0 0-51.89 36.31a102 102 0 0 0 142.84 142.84a102.88 102.88 0 0 0 36.31-51.89a6 6 0 0 0-1.5-5.99m-42 48.29a90 90 0 0 1-126-126a90.9 90.9 0 0 1 35.52-28.27a102.06 102.06 0 0 0 118.69 118.69a90.9 90.9 0 0 1-28.24 35.58Z"
/></svg
>
</div>
{/if}
</div>
{/if}
</div>
</div>
<!-----End-Header-CandleChart-Indicators------>
<!--Start Time Interval-->
<div
class="hidden sm:flex flex-row items-center pl-1 sm:pl-6 w-full mt-4"
>
@ -1046,20 +914,6 @@
{/each}
</ul>
</div>
<div
class="flex shrink flex-row space-x-1 pr-1 text-sm sm:text-[1rem]"
>
<span
class={displayLegend?.change >= 0
? "before:content-['+'] text-[#00FC50]"
: "text-[#FF2F1F]"}
>
{displayLegend?.change ?? "-"}%
</span>
<span class="hidden text-gray-200 sm:block"
>({displayData})</span
>
</div>
</div>
<div class="h-[250px] sm:h-[350px]">
<div
@ -1107,11 +961,11 @@
class="flex shrink flex-row space-x-1 pr-1 text-sm sm:text-[1rem]"
>
<span
class={displayLegend?.change >= 0
class={$displayLegend?.graphChange >= 0
? "before:content-['+'] text-[#00FC50]"
: "text-[#FF2F1F]"}
>
{displayLegend?.change}%
{$displayLegend?.graphChange}%
</span>
<span class="hidden text-gray-200 sm:block"
>({displayData})</span
@ -1137,7 +991,6 @@
lineColor={colorChange}
topColor={topColorChange}
bottomColor={bottomColorChange}
ref={handleSeriesReference}
priceLineVisible={false}
>
<PriceLine
@ -1157,7 +1010,6 @@
lineColor={colorChange}
topColor={topColorChange}
bottomColor={bottomColorChange}
ref={handleSeriesReference}
priceLineVisible={false}
>
<PriceLine
@ -1177,7 +1029,6 @@
lineColor={colorChange}
topColor={topColorChange}
bottomColor={bottomColorChange}
ref={handleSeriesReference}
priceLineVisible={false}
>
<PriceLine
@ -1197,7 +1048,6 @@
lineColor={colorChange}
topColor={topColorChange}
bottomColor={bottomColorChange}
ref={handleSeriesReference}
priceLineVisible={false}
>
<PriceLine
@ -1217,7 +1067,6 @@
lineColor={colorChange}
topColor={topColorChange}
bottomColor={bottomColorChange}
ref={handleSeriesReference}
priceLineVisible={false}
>
<PriceLine
@ -1237,7 +1086,6 @@
lineColor={colorChange}
topColor={topColorChange}
bottomColor={bottomColorChange}
ref={handleSeriesReference}
priceLineVisible={false}
>
<PriceLine