forked from admin/family_budget
43 lines
2.1 KiB
TypeScript
43 lines
2.1 KiB
TypeScript
type IssBlock = { columns?: string[]; data?: unknown[][] };
|
|
|
|
export type MarketQuote = { price: number; at: string | null };
|
|
|
|
const BASE_URL = 'https://iss.moex.com/iss';
|
|
const timeoutMs = 5000;
|
|
|
|
function rows(block: IssBlock | undefined): Record<string, unknown>[] {
|
|
if (!block?.columns || !block.data) return [];
|
|
return block.data.map((row) => Object.fromEntries(block.columns!.map((column, index) => [column.toLowerCase(), row[index]])));
|
|
}
|
|
|
|
async function getJson(url: string): Promise<Record<string, IssBlock>> {
|
|
const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), headers: { accept: 'application/json' } });
|
|
if (!response.ok) throw new Error(`MOEX HTTP ${response.status}`);
|
|
return await response.json() as Record<string, IssBlock>;
|
|
}
|
|
|
|
function numberValue(value: unknown): number | null {
|
|
const number = typeof value === 'number' ? value : Number(value);
|
|
return Number.isFinite(number) && number > 0 ? number : null;
|
|
}
|
|
|
|
export async function getMoexQuote(isin: string): Promise<MarketQuote | null> {
|
|
if (!/^RU[A-Z0-9]{10}$/.test(isin)) return null;
|
|
try {
|
|
const info = await getJson(`${BASE_URL}/securities/${encodeURIComponent(isin)}.json?iss.meta=off&iss.only=boards&boards.columns=engine,market,boardid,secid`);
|
|
const boards = rows(info.boards).filter((item) => typeof item.engine === 'string' && typeof item.market === 'string' && typeof item.boardid === 'string' && typeof item.secid === 'string');
|
|
for (const board of boards) {
|
|
try {
|
|
const quote = await getJson(`${BASE_URL}/engines/${board.engine}/markets/${board.market}/boards/${board.boardid}/securities/${encodeURIComponent(String(board.secid))}.json?iss.meta=off&iss.only=marketdata&marketdata.columns=LAST,LCURRENTPRICE,WAPRICE,UPDATETIME`);
|
|
const market = rows(quote.marketdata)[0];
|
|
if (!market) continue;
|
|
const price = numberValue(market.last) ?? numberValue(market.lcurrentprice) ?? numberValue(market.waprice);
|
|
if (price !== null) return { price, at: typeof market.updatetime === 'string' ? market.updatetime : null };
|
|
} catch { /* try the next trading board */ }
|
|
}
|
|
return null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|