1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
import type { SourceModule } from "../registry";
import {
MarketsConfig,
MarketsPayload,
type MarketsConfig as Config,
type MarketsPayload as Payload,
} from "@/lib/schemas/sources/markets";
const CHART = "https://query1.finance.yahoo.com/v8/finance/chart";
// Yahoo's chart endpoint carries everything we need in `meta` and works for both
// equities and crypto pairs (BTC-USD). One request per symbol; failures are
// skipped rather than failing the whole card.
async function quote(symbol: string, signal?: AbortSignal): Promise<Payload["quotes"][number] | null> {
try {
const res = await fetch(`${CHART}/${encodeURIComponent(symbol)}?range=5d&interval=1d`, {
headers: { "User-Agent": "Mozilla/5.0 (PersonalDashboard)" },
signal,
});
if (!res.ok) return null;
const j = (await res.json()) as {
chart?: { result?: Array<{ meta?: Record<string, unknown> }> };
};
const meta = j.chart?.result?.[0]?.meta as
| {
regularMarketPrice?: number;
chartPreviousClose?: number;
previousClose?: number;
currency?: string;
shortName?: string;
symbol?: string;
}
| undefined;
if (!meta || typeof meta.regularMarketPrice !== "number") return null;
const price = meta.regularMarketPrice;
const prev = meta.chartPreviousClose ?? meta.previousClose;
const changePct = typeof prev === "number" && prev !== 0 ? ((price - prev) / prev) * 100 : null;
return {
symbol: meta.symbol ?? symbol,
name: meta.shortName ?? symbol,
price,
changePct: changePct == null ? null : Math.round(changePct * 100) / 100,
currency: meta.currency ?? "USD",
};
} catch {
return null;
}
}
export const marketsModule: SourceModule<Config, Payload> = {
kind: "markets",
label: "Markets",
keyless: true,
defaultRefreshSeconds: 900,
configSchema: MarketsConfig,
payloadSchema: MarketsPayload,
isConfigured: (config) => config.symbols.length > 0,
async fetch({ config, signal }) {
const results = await Promise.all(config.symbols.map((s) => quote(s.trim().toUpperCase(), signal)));
return { quotes: results.filter((q): q is NonNullable<typeof q> => q !== null) };
},
};
|