Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions src/app/api/finance/sparklines/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/**
* GET /api/finance/sparklines?symbols=NVDA,AAPL,…
*
* Returns last-week close samples per symbol for the tiny watchlist sparklines.
* Paid-gated; uses the per-profile market-data provider (connected Alpaca →
* Yahoo fallback) and read-through caches each symbol's samples.
*/

import { NextRequest, NextResponse } from 'next/server';
import { requireActiveSubscription } from '@/lib/subscription/guard';
import { getActiveProfileId } from '@/lib/profiles/profile-utils';
import { getFallbackMarketDataProvider, type MarketDataProvider } from '@/lib/finance/market-data';
import { getMarketDataProviderForProfile } from '@/lib/finance/market-data/for-profile';
import { readThrough, CANDLES_TTL_SECONDS } from '@/lib/finance/market-data/cache';
import { parseSymbolList } from '@/lib/finance/watchlist';

export const dynamic = 'force-dynamic';

const MAX_SYMBOLS = 60;
const MAX_POINTS = 24;

/** Downsample an array to at most `max` evenly-spaced points (keeps last). */
function downsample(values: number[], max: number): number[] {
if (values.length <= max) return values;
const step = values.length / max;
const out: number[] = [];
for (let i = 0; i < max; i++) out.push(values[Math.min(values.length - 1, Math.floor(i * step))]);
out[out.length - 1] = values[values.length - 1];
return out;
}

async function samplesFor(provider: MarketDataProvider, symbol: string): Promise<number[]> {
return readThrough<number[]>(symbol, `sparkline:${provider.id}`, CANDLES_TTL_SECONDS, async () => {
const candles = await provider.getCandles(symbol, '5D');
return downsample(candles.map((c) => c.close), MAX_POINTS);
});
}

export async function GET(request: NextRequest): Promise<NextResponse> {
const gate = await requireActiveSubscription(request);
if (gate) return gate;

const { valid } = parseSymbolList(request.nextUrl.searchParams.get('symbols') ?? '');
if (valid.length === 0) return NextResponse.json({ samples: {} });

const profileId = await getActiveProfileId();
const provider = await getMarketDataProviderForProfile(profileId);
const fallback = getFallbackMarketDataProvider();

const symbols = valid.slice(0, MAX_SYMBOLS);
const entries = await Promise.all(
symbols.map(async (symbol): Promise<[string, number[]]> => {
try {
return [symbol, await samplesFor(provider, symbol)];
} catch {
try {
return [symbol, await samplesFor(fallback, symbol)];
} catch {
return [symbol, []];
}
}
}),
);

return NextResponse.json({ samples: Object.fromEntries(entries) });
}
26 changes: 25 additions & 1 deletion src/app/finance/finance-hub.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { normalizeSymbol } from '@/lib/finance/market-data/stooq';
import { BrokerConnect } from './broker-connect';
import { Sparkline } from '@/components/finance/sparkline';

const RECENT_KEY = 'finance:recent';

Expand All @@ -26,6 +27,7 @@ export function FinanceHub(): React.ReactElement {
const [bulk, setBulk] = useState('');
const [bulkBusy, setBulkBusy] = useState(false);
const [bulkMsg, setBulkMsg] = useState<string | null>(null);
const [sparklines, setSparklines] = useState<Record<string, number[]>>({});

useEffect(() => {
try {
Expand All @@ -47,6 +49,25 @@ export function FinanceHub(): React.ReactElement {
loadWatchlist();
}, [loadWatchlist]);

// Fetch last-week sparkline samples for the watchlist symbols (one batch call).
const watchlistKey = watchlist.map((w) => w.symbol).join(',');
useEffect(() => {
if (!watchlistKey) {
setSparklines({});
return;
}
let cancelled = false;
fetch(`/api/finance/sparklines?symbols=${encodeURIComponent(watchlistKey)}`, { cache: 'no-store' })
.then((res) => (res.ok ? res.json() : { samples: {} }))
.then((body: { samples?: Record<string, number[]> }) => {
if (!cancelled) setSparklines(body.samples ?? {});
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, [watchlistKey]);

const addBulk = useCallback(
async (e: React.FormEvent) => {
e.preventDefault();
Expand Down Expand Up @@ -164,7 +185,10 @@ export function FinanceHub(): React.ReactElement {
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
{watchlist.map((row) => (
<Link key={row.id} href={`/finance/ticker/${row.symbol}`} className="card p-4 hover:bg-bg-tertiary">
<div className="text-lg font-semibold text-text-primary">{row.symbol}</div>
<div className="flex items-center justify-between gap-2">
<div className="text-lg font-semibold text-text-primary">{row.symbol}</div>
<Sparkline samples={sparklines[row.symbol]} width={56} />
</div>
{row.exchange ? <div className="text-xs text-text-muted">{row.exchange}</div> : null}
</Link>
))}
Expand Down
Binary file added src/app/fonts/Datatype.woff2
Binary file not shown.
44 changes: 44 additions & 0 deletions src/components/finance/sparkline.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { datatypeFont } from '@/lib/datatype-font';

/**
* Inline price sparkline rendered via the Datatype variable font (ported from
* b1dz.com). Syntax: `{l:v1,v2,…}` where each v is 0–100; the font's ligatures
* substitute that text with a chart glyph. Color reflects last-vs-first
* direction (green up / red down).
*/
export function Sparkline({
samples,
width = 60,
}: {
samples?: number[];
width?: number;
}): React.ReactElement {
if (!samples || samples.length < 2) {
return <span className="text-text-muted">—</span>;
}

const min = Math.min(...samples);
const max = Math.max(...samples);
const range = max - min;
const normalized =
range === 0 ? samples.map(() => 50) : samples.map((v) => Math.round(((v - min) / range) * 100));

const isUp = samples[samples.length - 1] >= samples[0];
const colorClass = isUp ? 'text-green-400' : 'text-red-400';

return (
<span
className={`${datatypeFont.className} ${colorClass} inline-block`}
style={{
minWidth: width,
fontSize: '1.4em',
lineHeight: 1,
fontVariationSettings: "'wdth' 75, 'wght' 500",
fontFeatureSettings: "'calt' 1, 'liga' 1, 'dlig' 1",
WebkitFontFeatureSettings: "'calt' 1, 'liga' 1, 'dlig' 1",
}}
>
{`{l:${normalized.join(',')}}`}
</span>
);
}
15 changes: 15 additions & 0 deletions src/lib/datatype-font.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import localFont from 'next/font/local';

/**
* Datatype variable font — OpenType ligatures render the literal text
* `{l:v1,v2,…}` (each v 0–100) as an inline sparkline glyph at draw time.
* Loaded once at module scope so it's preloaded and shares one hash.
* (Ported from b1dz.com.)
*/
export const datatypeFont = localFont({
src: '../app/fonts/Datatype.woff2',
display: 'swap',
weight: '100 900',
preload: true,
variable: '--font-datatype',
});
Loading