import {z} from 'zod' export type GetApiV1LastMoversVenueArgs = {venue: 'stocks' | 'crypto' | 'forex' | 'commodities', limit?: number | undefined, direction?: ('all' | 'gainers' | 'losers') | undefined}; export type GetApiV1LastMoversVenueOptions = {baseUrl?: string | undefined, ApiKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const mover = z.object({symbol: z.string().optional(), price: z.string().optional(), prev_close: z.string().optional(), change: z.string().optional(), change_pct: z.number().optional(), day_volume: z.number().optional(), prev_day_volume: z.number().optional()}); export const moversResponse = z.object({data: z.object({gainers: z.array(mover).optional(), losers: z.array(mover).optional()}).optional(), meta: z.object({as_of: z.string().optional(), venue: z.string().optional(), limit: z.number().int().optional()}).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 }; /** * Market movers (top gainers and losers) * * GET /v1/last/movers/{venue} * * Also accepts auth: ApiKeyQuery */ export const getApiV1LastMoversVenue = async (args: GetApiV1LastMoversVenueArgs, options?: GetApiV1LastMoversVenueOptions) => { const {baseUrl = "https://api.sifting.io", fetch: fetchFn = fetch, ApiKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.direction != null) query.append("direction", String(args.direction)) if (ApiKeyHeader !== undefined) headers.set("X-API-Key", ApiKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/last/movers/${encodeURIComponent(String(args.venue))}${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(moversResponse, await res.json()) };