import {z} from 'zod' export type GetApiV1FlowTickerAggregateArgs = {ticker: string, start_time: string, end_time: string, option_type?: ('call' | 'put' | 'all') | undefined, min_premium?: number | undefined, exclude_multi_leg?: boolean | undefined, min_dte?: number | undefined, max_dte?: number | undefined, date?: string | undefined}; export type GetApiV1FlowTickerAggregateOptions = {baseUrl?: string | undefined, bearerApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const windowAggregateScores = z.object({vwf: z.number(), sdf: z.number(), fir: z.number(), composite: z.number()}); export const windowPremiumSplit = z.object({bullishPremium: z.number(), bearishPremium: z.number(), neutralPremium: z.number(), netPremium: z.number(), bullishCount: z.number().int().gte(0), bearishCount: z.number().int().gte(0), neutralCount: z.number().int().gte(0), sweepPremium: z.number()}); export const windowInterpretation = z.object({bias: z.enum(["bullish", "bearish", "neutral", "mixed"]), signalStrength: z.enum(["strong", "moderate", "weak"])}); export const flowAggregateResponse = z.object({ticker: z.string(), startTime: z.string(), endTime: z.string(), tradeCount: z.number().int().gte(0), sweepCount: z.number().int().gte(0), totalPremium: z.number(), aggregate: windowAggregateScores, premiumSplit: windowPremiumSplit, interpretation: windowInterpretation, queryTimeMs: z.number().int().gte(0)}); export const meta = z.object({timestamp: z.string(), requestId: z.string()}); export const flowAggregateSuccess = z.object({data: flowAggregateResponse, meta: meta}); 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 }; /** * Aggregate flow over an arbitrary [start, end] window * * GET /v1/flow/{ticker}/aggregate */ export const getApiV1FlowTickerAggregate = async (args: GetApiV1FlowTickerAggregateArgs, options?: GetApiV1FlowTickerAggregateOptions) => { const {baseUrl = "https://flow-api.skylit.ai", fetch: fetchFn = fetch, bearerApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.start_time != null) query.append("start_time", String(args.start_time)) if (args.end_time != null) query.append("end_time", String(args.end_time)) if (args.option_type != null) query.append("option_type", String(args.option_type)) if (args.min_premium != null) query.append("min_premium", String(args.min_premium)) if (args.exclude_multi_leg != null) query.append("exclude_multi_leg", String(args.exclude_multi_leg)) if (args.min_dte != null) query.append("min_dte", String(args.min_dte)) if (args.max_dte != null) query.append("max_dte", String(args.max_dte)) if (args.date != null) query.append("date", String(args.date)) if (bearerApiKey !== undefined) headers.set('authorization', `Bearer ${bearerApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/flow/${encodeURIComponent(String(args.ticker))}/aggregate${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(flowAggregateSuccess, await res.json()) };