/**
* EXAMPLE ADAPTER — not used by the component, which makes no network calls of its own. Read it, adapt it, and check
* your data provider's documentation and terms before you use a feed in production.
*
* Many exchanges publish a public "24h mini-ticker" websocket stream: every second or so, an array of objects like
*
* { "e": "24hrMiniTicker", "s": "BTCUSDT", "c": "98420.50", "o": "96104.10", "h": "…", "l": "…", "v": "…" }
*
* (c = last price, o = price 24 hours ago). This turns such a stream into what <LightfallHero ticker={…}> reads:
* an AsyncIterable<MarketTick[]>, at most one snapshot per `throttleMs`, reconnecting with back-off if the socket drops.
*
* const feed = useMemo(() => createMiniTickerAdapter({
* url: "wss://<your provider>/<mini-ticker stream>",
* symbols: { BTCUSDT: "BTC", ETHUSDT: "ETH", SOLUSDT: "SOL" },
* }), []);
*/
import type { MarketTick } from "../types";
export type MiniTicker = { s: string; c: string; o: string };
export type MiniTickerAdapterOptions = {
url: string;
/** Provider symbol → the label to show, e.g. { BTCUSDT: "BTC" }. Only these are kept, in this order. */
symbols: Record<string, string>;
names?: Record<string, string>;
throttleMs?: number;
/** Turns one websocket message into mini-tickers. Default: JSON, an array or a single object (or { data: … }). */
parse?: (data: string) => MiniTicker[];
};
const defaultParse = (data: string): MiniTicker[] => {
const json = JSON.parse(data);
const body = json && typeof json === "object" && "data" in json ? json.data : json;
return Array.isArray(body) ? body : [body];
};
export function createMiniTickerAdapter({ url, symbols, names = {}, throttleMs = 1000, parse = defaultParse }: MiniTickerAdapterOptions): AsyncIterable<MarketTick[]> {
const order = Object.keys(symbols);
return {
// One socket per iterator: each mount gets its own, and return() closes it.
[Symbol.asyncIterator]() {
const latest = new Map<string, MarketTick>();
const history = new Map<string, number[]>();
let ws: WebSocket | null = null;
let closed = false;
let dirty = false;
let last = 0;
let retry = 500;
let waiting: ((r: IteratorResult<MarketTick[]>) => void) | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;
const snapshot = () => order.flatMap((k) => (latest.has(k) ? [latest.get(k)!] : []));
const flush = () => {
if (!waiting || !dirty) return;
const wait = last + throttleMs - Date.now();
if (wait > 0) {
clearTimeout(timer);
timer = setTimeout(flush, wait);
return;
}
dirty = false;
last = Date.now();
const resolve = waiting;
waiting = null;
resolve({ done: false, value: snapshot() });
};
const connect = () => {
if (closed) return;
ws = new WebSocket(url);
ws.onopen = () => (retry = 500);
ws.onmessage = (e) => {
let list: MiniTicker[];
try {
list = parse(String(e.data));
} catch {
return;
}
for (const t of list) {
const label = symbols[t.s];
const price = Number(t.c);
const open = Number(t.o);
if (!label || !Number.isFinite(price)) continue;
const h = [...(history.get(t.s) ?? []), price].slice(-24);
history.set(t.s, h);
latest.set(t.s, { symbol: label, name: names[t.s], price, change24h: open ? ((price - open) / open) * 100 : 0, sparkline: h });
dirty = true;
}
flush();
};
ws.onclose = () => {
if (closed) return;
setTimeout(connect, retry);
retry = Math.min(retry * 2, 15000);
};
};
connect();
return {
next() {
if (closed) return Promise.resolve({ done: true, value: undefined });
return new Promise<IteratorResult<MarketTick[]>>((resolve) => {
waiting = resolve;
flush();
});
},
return() {
closed = true;
clearTimeout(timer);
ws?.close();
waiting?.({ done: true, value: undefined });
waiting = null;
return Promise.resolve({ done: true, value: undefined });
},
};
},
};
}