import {z} from 'zod' export type GetApiMarketsCandlesticksArgs = {market_tickers: string, start_ts: number, end_ts: number, period_interval: number, include_latest_before_start?: boolean | undefined}; export type GetApiMarketsCandlesticksOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const fixedPointDollars = z.string(); export const bidAskDistribution = z.object({open_dollars: fixedPointDollars, low_dollars: fixedPointDollars, high_dollars: fixedPointDollars, close_dollars: fixedPointDollars}); export const priceDistribution = z.object({open_dollars: fixedPointDollars.optional(), low_dollars: fixedPointDollars.optional(), high_dollars: fixedPointDollars.optional(), close_dollars: fixedPointDollars.optional(), mean_dollars: fixedPointDollars.optional(), previous_dollars: fixedPointDollars.optional(), min_dollars: fixedPointDollars.optional(), max_dollars: fixedPointDollars.optional()}); export const fixedPointCount = z.string(); export const marketCandlestick = z.object({end_period_ts: z.number().int(), yes_bid: bidAskDistribution, yes_ask: bidAskDistribution, price: priceDistribution, volume_fp: fixedPointCount, open_interest_fp: fixedPointCount}); export const marketCandlesticksResponse = z.object({market_ticker: z.string(), candlesticks: z.array(marketCandlestick)}); export const batchGetMarketCandlesticksResponse = z.object({markets: z.array(marketCandlesticksResponse)}); 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 }; /** * Batch Get Market Candlesticks * * GET /markets/candlesticks */ export const getApiMarketsCandlesticks = async (args: GetApiMarketsCandlesticksArgs, options?: GetApiMarketsCandlesticksOptions) => { const {baseUrl = "https://external-api.kalshi.com/trade-api/v2", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.market_tickers != null) query.append("market_tickers", String(args.market_tickers)) if (args.start_ts != null) query.append("start_ts", String(args.start_ts)) if (args.end_ts != null) query.append("end_ts", String(args.end_ts)) if (args.period_interval != null) query.append("period_interval", String(args.period_interval)) if (args.include_latest_before_start != null) query.append("include_latest_before_start", String(args.include_latest_before_start)) const url = `${baseUrl.replace(/\/+$/, '')}/markets/candlesticks${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(batchGetMarketCandlesticksResponse, await res.json()) };