add DarkPool Component

This commit is contained in:
MuslemRahimi 2024-06-20 07:30:45 +02:00
parent 2d712844ce
commit 6506a730e8
4 changed files with 338 additions and 7 deletions

View File

@ -0,0 +1,321 @@
<script lang ='ts'>
import { darkPoolComponent, displayCompanyName, stockTicker, assetType, etfTicker, screenWidth, userRegion, getCache, setCache} from '$lib/store';
import InfoModal from '$lib/components/InfoModal.svelte';
import { Chart } from 'svelte-echarts'
import { abbreviateNumber } from "$lib/utils";
import Lazy from 'svelte-lazy';
export let data;
let isLoaded = false;
const usRegion = ['cle1','iad1','pdx1','sfo1'];
let apiURL;
userRegion.subscribe(value => {
if (usRegion.includes(value)) {
apiURL = import.meta.env.VITE_USEAST_API_URL;
} else {
apiURL = import.meta.env.VITE_EU_API_URL;
}
});
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
let rawData = [];
let optionsData;
let avgVolume;
let avgShortVolume;
function normalizer(value) {
if (Math?.abs(value) >= 1e18) {
return { unit: 'Q', denominator: 1e18 };
} else if (Math?.abs(value) >= 1e12) {
return { unit: 'T', denominator: 1e12 };
} else if (Math?.abs(value) >= 1e9) {
return { unit: 'B', denominator: 1e9 };
} else if (Math?.abs(value) >= 1e6) {
return { unit: 'M', denominator: 1e6 };
} else if (Math?.abs(value) >= 1e5) {
return { unit: 'K', denominator: 1e5 };
} else {
return { unit: '', denominator: 1 };
}
}
function getPlotOptions() {
let dates = [];
let totalVolumeList = [];
let shortVolumeList = [];
// Iterate over the data and extract required information
rawData?.forEach(item => {
dates?.push(item?.date);
totalVolumeList?.push(item?.totalVolume);
shortVolumeList?.push(item?.shortVolume)
});
// Compute the average of item?.traded
const totalTraded = totalVolumeList?.reduce((acc, traded) => acc + traded, 0);
avgVolume = totalTraded / totalVolumeList?.length;
const totalShort = shortVolumeList?.reduce((acc, sentiment) => acc + sentiment, 0);
avgShortVolume = totalShort / shortVolumeList?.length;
const {unit, denominator } = normalizer(Math.max(...totalVolumeList) ?? 0)
const option = {
silent: true,
animation: $screenWidth < 640 ? false: true,
grid: {
left: '2%',
right: '2%',
bottom: '2%',
top: '5%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: dates,
},
yAxis: [
{
type: 'value',
splitLine: {
show: false, // Disable x-axis grid lines
},
axisLabel: {
color: '#6E7079', // Change label color to white
formatter: function (value, index) {
// Display every second tick
if (index % 2 === 0) {
value = Math.max(value, 0);
return (value / denominator)?.toFixed(1) + unit; // Format value in millions
} else {
return ''; // Hide this tick
}
}
},
},
],
series: [
{
data: totalVolumeList,
type: 'line',
itemStyle: {
color: '#fff' // Change bar color to white
},
showSymbol: false
},
{
data: shortVolumeList,
type: 'line',
itemStyle: {
color: '#536FC5' // Change bar color to white
},
showSymbol: false
},
]
};
return option;
}
const getDarkPool = async (ticker) => {
// Get cached data for the specific tickerID
const cachedData = getCache(ticker, 'getDarkPool');
if (cachedData) {
rawData = cachedData;
} else {
const postData = {'ticker': ticker};
// make the POST request to the endpoint
const response = await fetch(apiURL + '/dark-pool', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData)
});
rawData = await response.json();
// Cache the data for this specific tickerID with a specific name 'getDarkPool'
setCache(ticker, rawData, 'getDarkPool');
}
if(rawData?.length !== 0) {
$darkPoolComponent = true;
} else {
$darkPoolComponent = false;
}
};
$: {
if($assetType === 'stock' ? $stockTicker :$etfTicker && typeof window !== 'undefined') {
isLoaded=false;
const ticker = $assetType === 'stock' ? $stockTicker :$etfTicker
const asyncFunctions = [
getDarkPool(ticker)
];
Promise.all(asyncFunctions)
.then((results) => {
optionsData = getPlotOptions()
})
.catch((error) => {
console.error('An error occurred:', error);
});
isLoaded = true;
}
}
</script>
<section class="overflow-hidden text-white h-full pb-8">
<main class="overflow-hidden ">
<div class="flex flex-row items-center">
<label for="darkPoolInfo" class="mr-1 cursor-pointer flex flex-row items-center text-white text-xl sm:text-3xl font-bold">
Dark Pool
</label>
<InfoModal
title={"Retail Trader Volume"}
content={"Gain insights into Retail Trader activity with the following visualization: The green bar illustrates the daily volume trend, signifying a bullish sentiment if it ranges from 0 to 100, or bearish if it spans from -100 to just below 0. The white line depicts the daily trading volume of retail investors."}
id={"darkPoolInfo"}
/>
</div>
{#if data?.user?.tier === 'Pro'}
{#if isLoaded}
{#if rawData?.length !== 0}
<div class="w-full flex flex-col items-start">
<div class="text-white text-sm sm:text-[1rem] mt-2 mb-2 w-full">
Over the past 12 months, {$displayCompanyName} has experienced an average dark pool trading volume of
<span class="font-semibold">{abbreviateNumber(avgVolume)}</span> shares.
Out of this total, an average of <span class="font-semibold">{abbreviateNumber(avgShortVolume)}</span> shares,
constituting approximately <span class="font-semibold">{((avgShortVolume/avgVolume)*100)?.toFixed(2)}%</span>, were short volume.
</div>
</div>
<div class="pb-2 sm:pb-2 rounded-lg bg-[#0F0F0F]">
<Lazy height={300} fadeOption={{delay: 100, duration: 500}} keep={true}>
<div class="app w-full h-[300px] mt-5">
<Chart options={optionsData} class="chart" />
</div>
</Lazy>
</div>
<div class="flex flex-row items-center justify-between mx-auto mt-5 w-full sm:w-11/12">
<div class="mt-3.5 sm:mt-0 flex flex-col sm:flex-row items-center ml-3 sm:ml-0 w-1/2 justify-center">
<div class="h-full transform -translate-x-1/2 " aria-hidden="true"></div>
<div class="w-3 h-3 bg-[#fff] border-4 box-content border-[#202020] rounded-full transform sm:-translate-x-1/2" aria-hidden="true"></div>
<span class="mt-2 sm:mt-0 text-white text-center sm:text-start text-xs sm:text-md inline-block">
Total Volume
</span>
</div>
<div class="flex flex-col sm:flex-row items-center ml-3 sm:ml-0 w-1/2 justify-center">
<div class="h-full transform -translate-x-1/2 " aria-hidden="true"></div>
<div class="w-3 h-3 bg-[#536FC5] border-4 box-content border-[#202020] rounded-full transform sm:-translate-x-1/2" aria-hidden="true"></div>
<span class="mt-2 sm:mt-0 text-white text-xs sm:text-md sm:font-medium inline-block">
Short Volume
</span>
</div>
</div>
<h2 class="mt-10 mr-1 flex flex-row items-center text-white text-xl sm:text-2xl font-bold mb-3">
Latest Information
</h2>
<div class="flex justify-start items-center w-full m-auto ">
<table class="w-full" data-test="statistics-table">
<tbody>
<tr class="border-y border-gray-800 odd:bg-[#202020]">
<td class="px-[5px] py-1.5 xs:px-2.5 xs:py-2">
<span>Date</span>
</td>
<td class="px-[5px] py-1.5 text-right font-medium xs:px-2.5 xs:py-2">
{new Date(rawData?.slice(-1)?.at(0)?.date)?.toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', daySuffix: '2-digit' })}
</td>
</tr>
<tr class="border-y border-gray-800 odd:bg-[#202020]">
<td class="px-[5px] py-1.5 xs:px-2.5 xs:py-2">
<span>Total Volume</span>
</td>
<td class="px-[5px] py-1.5 text-right font-medium xs:px-2.5 xs:py-2">
{abbreviateNumber(rawData?.slice(-1)?.at(0)?.totalVolume)}
</td>
</tr>
<tr class="border-y border-gray-800 odd:bg-[#202020]">
<td class="px-[5px] py-1.5 xs:px-2.5 xs:py-2">
<span>Short % of Volume</span>
</td>
<td class="px-[5px] py-1.5 text-right font-medium xs:px-2.5 xs:py-2">
{rawData?.slice(-1)?.at(0)?.shortPercent}%
</td>
</tr>
</tbody>
</table>
</div>
{/if}
{:else}
<div class="flex justify-center items-center h-80">
<div class="relative">
<label class="bg-[#202020] rounded-xl h-14 w-14 flex justify-center items-center absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
<span class="loading loading-spinner loading-md"></span>
</label>
</div>
</div>
{/if}
{:else}
<div class="shadow-lg shadow-bg-[#000] bg-[#202020] sm:bg-opacity-[0.5] text-sm sm:text-[1rem] rounded-md w-full p-4 min-h-24 mt-4 text-white m-auto flex justify-center items-center text-center font-semibold">
<svg class="mr-1.5 w-5 h-5 inline-block"xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="#A3A3A3" d="M17 9V7c0-2.8-2.2-5-5-5S7 4.2 7 7v2c-1.7 0-3 1.3-3 3v7c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3v-7c0-1.7-1.3-3-3-3M9 7c0-1.7 1.3-3 3-3s3 1.3 3 3v2H9z"/></svg>
Unlock content with <a class="inline-block ml-2 text-blue-400 hover:sm:text-white" href="/pricing">Pro Subscription</a>
</div>
{/if}
</main>
</section>
<style>
.app {
height: 300px;
max-width: 100%; /* Ensure chart width doesn't exceed the container */
}
@media (max-width: 640px) {
.app {
height: 210px;
}
}
.chart {
width: 100%;
}
</style>

View File

@ -72,9 +72,9 @@ function getPlotOptions() {
silent: true,
animation: $screenWidth < 640 ? false: true,
grid: {
left: $screenWidth < 640 ? '0%' : '2%',
right: $screenWidth < 640 ? '0%' : '2%',
bottom: $screenWidth < 640 ? '0%' : '2%',
left: '2%',
right: '2%',
bottom: '0%',
containLabel: true
},
xAxis: {
@ -255,7 +255,7 @@ $: {
</div>
</div>
<div class="p-3 sm:p-0 pb-8 sm:pb-2 rounded-lg bg-[#202020] sm:bg-[#0F0F0F]">
<div class="pb-8 sm:pb-2 rounded-lg bg-[#0F0F0F]">
<Lazy height={300} fadeOption={{delay: 100, duration: 500}} keep={true}>
@ -339,7 +339,7 @@ $: {
@media (max-width: 640px) {
.app {
height: 230px;
height: 210px;
}
}

View File

@ -64,6 +64,7 @@ export const revenueSegmentationComponent = writable(<boolean>(false));
export const trendAnalysisComponent = writable(<boolean>(false));
export const shareholderComponent = writable(<boolean>(false));
export const retailVolumeComponent = writable(<boolean>(false));
export const darkPoolComponent = writable(<boolean>(false));
export const strategyId = writable(<string> (""));

View File

@ -3,7 +3,7 @@
import {AreaSeries, Chart, PriceLine, CandlestickSeries} from 'svelte-lightweight-charts';
import { TrackingModeExitMode } from 'lightweight-charts';
import {getCache, setCache, screenWidth, displayCompanyName, numberOfUnreadNotification, globalForm, retailVolumeComponent, 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, darkPoolComponent, retailVolumeComponent, shareholderComponent, trendAnalysisComponent, revenueSegmentationComponent, priceAnalysisComponent, fundamentalAnalysisComponent, userRegion, isCrosshairMoveActive, realtimePrice, priceIncrease, currentPortfolioPrice, currentPrice, stockTicker, isOpen, isBeforeMarketOpen, isWeekend} from '$lib/store';
import { onDestroy, onMount } from 'svelte';
import StockKeyInformation from '$lib/components/StockKeyInformation.svelte';
import BullBearSay from '$lib/components/BullBearSay.svelte';
@ -1338,7 +1338,16 @@ function changeChartType() {
</Lazy>
<!--End RevenueSegmentation-->
<Lazy>
<div class="w-full mt-10 sm:mt-5 m-auto sm:pl-6 sm:pb-6 sm:pt-6 {!$darkPoolComponent ? 'hidden' : ''}">
{#await import('$lib/components/DarkPool.svelte') then {default: Comp}}
<svelte:component this={Comp} data={data} />
{/await}
</div>
</Lazy>
<Lazy>
<div class="w-full mt-10 sm:mt-5 m-auto sm:pl-6 sm:pb-6 sm:pt-6 {!$retailVolumeComponent ? 'hidden' : ''}">
{#await import('$lib/components/RetailVolume.svelte') then {default: Comp}}