Feature: stock market service and info widget (#3617)
--------- Co-authored-by: shamoon <4887959+shamoon@users.noreply.github.com>pull/3706/head
parent
810c321881
commit
231e2408c3
After Width: | Height: | Size: 9.2 KiB |
@ -0,0 +1,48 @@
|
||||
---
|
||||
title: Stocks
|
||||
description: Stocks Information Widget Configuration
|
||||
---
|
||||
|
||||
_(Find the Stocks service widget [here](../services/stocks.md))_
|
||||
|
||||
The Stocks Information Widget allows you to include basic stock market data in
|
||||
your Homepage header. The widget includes the current price of a stock, and the
|
||||
change in price for the day.
|
||||
|
||||
Finnhub.io is currently the only supported provider for the stocks widget.
|
||||
You can sign up for a free api key at [finnhub.io](https://finnhub.io).
|
||||
You are encouraged to read finnhub.io's
|
||||
[terms of service/privacy policy](https://finnhub.io/terms-of-service) before
|
||||
signing up. The documentation for the endpoint that is utilized can be viewed
|
||||
[here](https://finnhub.io/docs/api/quote).
|
||||
|
||||
You must set `finnhub` as a provider in your `settings.yaml` like below:
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
finnhub: yourfinnhubapikeyhere
|
||||
```
|
||||
|
||||
Next, configure the stocks widget in your `widgets.yaml`:
|
||||
|
||||
The information widget allows for up to 8 items in the watchlist.
|
||||
|
||||
```yaml
|
||||
- stocks:
|
||||
provider: finnhub
|
||||
color: true # optional, defaults to true
|
||||
cache: 1 # optional, default caches results for 1 minute
|
||||
watchlist:
|
||||
- GME
|
||||
- AMC
|
||||
- NVDA
|
||||
- AMD
|
||||
- TSM
|
||||
- MSFT
|
||||
- AAPL
|
||||
- BRK.A
|
||||
```
|
||||
|
||||
The above configuration would result in something like this:
|
||||
|
||||
![Example of Stocks Widget](../../assets/widget_stocks_demo.png)
|
@ -0,0 +1,50 @@
|
||||
---
|
||||
title: Stocks
|
||||
description: Stocks Service Widget Configuration
|
||||
---
|
||||
|
||||
_(Find the Stocks information widget [here](../info/stocks.md))_
|
||||
|
||||
The widget includes:
|
||||
|
||||
- US stock market status
|
||||
- Current price of provided stock symbol
|
||||
- Change in price of stock symbol for the day.
|
||||
|
||||
Finnhub.io is currently the only supported provider for the stocks widget.
|
||||
You can sign up for a free api key at [finnhub.io](https://finnhub.io).
|
||||
You are encouraged to read finnhub.io's
|
||||
[terms of service/privacy policy](https://finnhub.io/terms-of-service) before
|
||||
signing up.
|
||||
|
||||
Allowed fields: no configurable fields for this widget.
|
||||
|
||||
You must set `finnhub` as a provider in your `settings.yaml`:
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
finnhub: yourfinnhubapikeyhere
|
||||
```
|
||||
|
||||
Next, configure the stocks widget in your `services.yaml`:
|
||||
|
||||
The service widget allows for up to 28 items in the watchlist. You may get rate
|
||||
limited if using the information and service widgets together.
|
||||
|
||||
```yaml
|
||||
widget:
|
||||
type: stocks
|
||||
provider: finnhub
|
||||
showUSMarketStatus: true # optional, defaults to true
|
||||
watchlist:
|
||||
- GME
|
||||
- AMC
|
||||
- NVDA
|
||||
- TSM
|
||||
- BRK.A
|
||||
- TSLA
|
||||
- AAPL
|
||||
- MSFT
|
||||
- AMZN
|
||||
- BRK.B
|
||||
```
|
@ -0,0 +1,91 @@
|
||||
import useSWR from "swr";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "next-i18next";
|
||||
import { FaChartLine } from "react-icons/fa6";
|
||||
|
||||
import Error from "../widget/error";
|
||||
import Container from "../widget/container";
|
||||
import PrimaryText from "../widget/primary_text";
|
||||
import WidgetIcon from "../widget/widget_icon";
|
||||
import Raw from "../widget/raw";
|
||||
|
||||
export default function Widget({ options }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
const [viewingPercentChange, setViewingPercentChange] = useState(false);
|
||||
|
||||
const { color } = options;
|
||||
|
||||
const { data, error } = useSWR(
|
||||
`/api/widgets/stocks?${new URLSearchParams({ lang: i18n.language, ...options }).toString()}`,
|
||||
);
|
||||
|
||||
if (error || data?.error) {
|
||||
return <Error options={options} />;
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return (
|
||||
<Container>
|
||||
<WidgetIcon icon={FaChartLine} />
|
||||
<PrimaryText>{t("stocks.loading")}...</PrimaryText>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
if (data) {
|
||||
return (
|
||||
<Container options={options} additionalClassNames="information-widget-stocks">
|
||||
<Raw>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setViewingPercentChange(!viewingPercentChange)}
|
||||
className="flex items-center w-full h-full hover:outline-none focus:outline-none"
|
||||
>
|
||||
<FaChartLine className="flex-none w-5 h-5 text-theme-800 dark:text-theme-200 mr-2" />
|
||||
<div className="flex flex-wrap items-center gap-0.5">
|
||||
{data.stocks.map(
|
||||
(stock) =>
|
||||
stock && (
|
||||
<div
|
||||
key={stock.ticker}
|
||||
className="rounded h-full text-xs px-1 w-[4.75rem] flex flex-col items-center justify-center"
|
||||
>
|
||||
<span className="text-theme-800 dark:text-theme-200 text-xs">{stock.ticker}</span>
|
||||
{!viewingPercentChange ? (
|
||||
<span
|
||||
className={
|
||||
color !== false
|
||||
? `text-xs ${stock.percentChange < 0 ? "text-rose-300/70" : "text-emerald-300/70"}`
|
||||
: "text-theme-800/70 dark:text-theme-200/50 text-xs"
|
||||
}
|
||||
>
|
||||
{stock.currentPrice !== null
|
||||
? t("common.number", {
|
||||
value: stock.currentPrice,
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
})
|
||||
: t("widget.api_error")}
|
||||
</span>
|
||||
) : (
|
||||
<span
|
||||
className={
|
||||
color !== false
|
||||
? `text-xs ${stock.percentChange < 0 ? "text-rose-300/70" : "text-emerald-300/70"}`
|
||||
: "text-theme-800/70 dark:text-theme-200/70 text-xs"
|
||||
}
|
||||
>
|
||||
{stock.percentChange !== null ? `${stock.percentChange}%` : t("widget.api_error")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
</Raw>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
import cachedFetch from "utils/proxy/cached-fetch";
|
||||
import { getSettings } from "utils/config/config";
|
||||
|
||||
export default async function handler(req, res) {
|
||||
const { watchlist, provider, cache } = req.query;
|
||||
|
||||
if (!watchlist) {
|
||||
return res.status(400).json({ error: "Missing watchlist" });
|
||||
}
|
||||
|
||||
const watchlistArr = watchlist.split(",") || [watchlist];
|
||||
|
||||
if (!watchlistArr.length || watchlistArr[0] === "null" || !watchlistArr[0]) {
|
||||
return res.status(400).json({ error: "Missing watchlist" });
|
||||
}
|
||||
|
||||
if (watchlistArr.length > 8) {
|
||||
return res.status(400).json({ error: "Max items in watchlist is 8" });
|
||||
}
|
||||
|
||||
const hasDuplicates = new Set(watchlistArr).size !== watchlistArr.length;
|
||||
|
||||
if (hasDuplicates) {
|
||||
return res.status(400).json({ error: "Watchlist contains duplicates" });
|
||||
}
|
||||
|
||||
if (!provider) {
|
||||
return res.status(400).json({ error: "Missing provider" });
|
||||
}
|
||||
|
||||
if (provider !== "finnhub") {
|
||||
return res.status(400).json({ error: "Invalid provider" });
|
||||
}
|
||||
|
||||
const providersInConfig = getSettings()?.providers;
|
||||
|
||||
let apiKey;
|
||||
Object.entries(providersInConfig).forEach(([key, val]) => {
|
||||
if (key === provider) apiKey = val;
|
||||
});
|
||||
|
||||
if (typeof apiKey === "undefined") {
|
||||
return res.status(400).json({ error: "Missing or invalid API Key for provider" });
|
||||
}
|
||||
|
||||
if (provider === "finnhub") {
|
||||
// Finnhub allows up to 30 calls/second
|
||||
// https://finnhub.io/docs/api/rate-limit
|
||||
const results = await Promise.all(
|
||||
watchlistArr.map(async (ticker) => {
|
||||
if (!ticker) {
|
||||
return { ticker: null, currentPrice: null, percentChange: null };
|
||||
}
|
||||
// https://finnhub.io/docs/api/quote
|
||||
const apiUrl = `https://finnhub.io/api/v1/quote?symbol=${ticker}&token=${apiKey}`;
|
||||
// Finnhub free accounts allow up to 60 calls/minute
|
||||
// https://finnhub.io/pricing
|
||||
const { c, dp } = await cachedFetch(apiUrl, cache || 1);
|
||||
|
||||
// API sometimes returns 200, but values returned are `null`
|
||||
if (c === null || dp === null) {
|
||||
return { ticker, currentPrice: null, percentChange: null };
|
||||
}
|
||||
|
||||
// Rounding percentage, but we want it back to a number for comparison
|
||||
return { ticker, currentPrice: c.toFixed(2), percentChange: parseFloat(dp.toFixed(2)) };
|
||||
}),
|
||||
);
|
||||
|
||||
return res.send({
|
||||
stocks: results,
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(400).json({ error: "Invalid configuration" });
|
||||
}
|
@ -0,0 +1,110 @@
|
||||
import { useTranslation } from "next-i18next";
|
||||
import classNames from "classnames";
|
||||
|
||||
import Container from "components/services/widget/container";
|
||||
import Block from "components/services/widget/block";
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
|
||||
function MarketStatus({ service }) {
|
||||
const { t } = useTranslation();
|
||||
const { widget } = service;
|
||||
|
||||
const { data, error } = useWidgetAPI(widget, "status", {
|
||||
exchange: "US",
|
||||
});
|
||||
|
||||
if (error || data?.error) {
|
||||
return <Container service={service} error={error} />;
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return (
|
||||
<Container service={service}>
|
||||
<Block value={t("stocks.loading")} />
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
const { isOpen } = data;
|
||||
|
||||
if (isOpen) {
|
||||
return (
|
||||
<span className="inline-flex items-center rounded-md bg-green-500/10 px-2 py-1 text-xs font-medium text-green-400/90 ring-1 ring-inset ring-green-500/20">
|
||||
{t("stocks.open")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="inline-flex items-center rounded-md bg-red-400/10 px-2 py-1 text-xs font-medium text-red-400/60 ring-1 ring-inset ring-red-400/10">
|
||||
{t("stocks.closed")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function StockItem({ service, ticker }) {
|
||||
const { t } = useTranslation();
|
||||
const { widget } = service;
|
||||
|
||||
const { data, error } = useWidgetAPI(widget, "quote", { symbol: ticker });
|
||||
|
||||
if (error || data?.error) {
|
||||
return <Container service={service} error={error} />;
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return (
|
||||
<Container service={service}>
|
||||
<Block value={t("stocks.loading")} />
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-theme-200/50 dark:bg-theme-900/20 rounded flex flex-1 items-center justify-between m-1 p-1 text-xs">
|
||||
<span className="font-thin ml-2 flex-none">{ticker}</span>
|
||||
<div className="flex items-center flex-row-reverse mr-2 text-right">
|
||||
<span className={`font-bold ml-2 w-10 ${data.dp > 0 ? "text-emerald-300" : "text-rose-300"}`}>
|
||||
{data.dp?.toFixed(2) ? `${data.dp?.toFixed(2)}%` : t("widget.api_error")}
|
||||
</span>
|
||||
<span className="font-bold">
|
||||
{data.c
|
||||
? t("common.number", {
|
||||
value: data?.c,
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
})
|
||||
: t("widget.api_error")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Component({ service }) {
|
||||
const { t } = useTranslation();
|
||||
const { widget } = service;
|
||||
const { watchlist, showUSMarketStatus } = widget;
|
||||
|
||||
if (!watchlist || !watchlist.length || watchlist.length > 28 || new Set(watchlist).size !== watchlist.length) {
|
||||
return (
|
||||
<Container service={service}>
|
||||
<Block value={t("stocks.invalidConfiguration")} />
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Container service={service}>
|
||||
<div className={classNames(service.description ? "-top-10" : "-top-8", "absolute right-1 z-20")}>
|
||||
{showUSMarketStatus === true && <MarketStatus service={service} />}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col w-full">
|
||||
{watchlist.map((ticker) => (
|
||||
<StockItem key={ticker} service={service} ticker={ticker} />
|
||||
))}
|
||||
</div>
|
||||
</Container>
|
||||
);
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
import credentialedProxyHandler from "utils/proxy/handlers/credentialed";
|
||||
|
||||
const widget = {
|
||||
api: `https://finnhub.io/api/{endpoint}`,
|
||||
proxyHandler: credentialedProxyHandler,
|
||||
|
||||
mappings: {
|
||||
quote: {
|
||||
// https://finnhub.io/docs/api/quote
|
||||
endpoint: "v1/quote",
|
||||
params: ["symbol"],
|
||||
},
|
||||
status: {
|
||||
// https://finnhub.io/docs/api/market-status
|
||||
endpoint: "v1/stock/market-status",
|
||||
params: ["exchange"],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default widget;
|
Loading…
Reference in new issue