import {z} from 'zod' export type GetApiQuoteArgs = {symbol?: string | undefined, figi?: string | undefined, isin?: string | undefined, cusip?: string | undefined, interval?: ('1min' | '5min' | '15min' | '30min' | '45min' | '1h' | '2h' | '4h' | '8h' | '1day' | '1week' | '1month') | undefined, exchange?: string | undefined, mic_code?: string | undefined, country?: string | undefined, volume_time_period?: number | undefined, type?: ('American Depositary Receipt' | 'Bond' | 'Bond Fund' | 'Closed-end Fund' | 'Common Stock' | 'Depositary Receipt' | 'Digital Currency' | 'ETF' | 'Exchange-Traded Note' | 'Global Depositary Receipt' | 'Limited Partnership' | 'Mutual Fund' | 'Physical Currency' | 'Preferred Stock' | 'REIT' | 'Right' | 'Structured Product' | 'Trust' | 'Unit' | 'Warrant') | undefined, format?: ('JSON' | 'CSV') | undefined, delimiter?: string | undefined, prepost?: boolean | undefined, eod?: boolean | undefined, rolling_period?: number | undefined, dp?: number | undefined, timezone?: string | undefined}; export type GetApiQuoteOptions = {baseUrl?: string | undefined, authorizationHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiQuoteResponse = z.object({symbol: z.string(), name: z.string(), exchange: z.string().optional(), mic_code: z.string().optional(), currency: z.string().optional(), datetime: z.string(), timestamp: z.number().int(), last_quote_at: z.number().int().optional(), open: z.string(), high: z.string(), low: z.string(), close: z.string(), volume: z.string().optional(), previous_close: z.string(), change: z.string(), percent_change: z.string(), average_volume: z.string().optional(), rolling_1d_change: z.string().optional(), rolling_7d_change: z.string().optional(), rolling_change: z.string().optional(), is_market_open: z.boolean(), fifty_two_week: z.object({low: z.string().optional(), high: z.string().optional(), low_change: z.string().optional(), high_change: z.string().optional(), low_change_percent: z.string().optional(), high_change_percent: z.string().optional(), range: z.string().optional()}), extended_change: z.string().optional(), extended_percent_change: z.string().optional(), extended_price: z.string().optional(), extended_timestamp: z.number().int().optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Quote * * GET /quote * * Also accepts auth: queryParameter */ export const getApiQuote = async (args: GetApiQuoteArgs, options?: GetApiQuoteOptions) => { const {baseUrl = "https://api.twelvedata.com", fetch: fetchFn = fetch, authorizationHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.symbol != null) query.append("symbol", String(args.symbol)) if (args.figi != null) query.append("figi", String(args.figi)) if (args.isin != null) query.append("isin", String(args.isin)) if (args.cusip != null) query.append("cusip", String(args.cusip)) if (args.interval != null) query.append("interval", String(args.interval)) if (args.exchange != null) query.append("exchange", String(args.exchange)) if (args.mic_code != null) query.append("mic_code", String(args.mic_code)) if (args.country != null) query.append("country", String(args.country)) if (args.volume_time_period != null) query.append("volume_time_period", String(args.volume_time_period)) if (args.type != null) query.append("type", String(args.type)) if (args.format != null) query.append("format", String(args.format)) if (args.delimiter != null) query.append("delimiter", String(args.delimiter)) if (args.prepost != null) query.append("prepost", String(args.prepost)) if (args.eod != null) query.append("eod", String(args.eod)) if (args.rolling_period != null) query.append("rolling_period", String(args.rolling_period)) if (args.dp != null) query.append("dp", String(args.dp)) if (args.timezone != null) query.append("timezone", String(args.timezone)) if (authorizationHeader !== undefined) headers.set("Authorization", authorizationHeader) const url = `${baseUrl.replace(/\/+$/, '')}/quote${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiQuoteResponse, await res.json()) };