import {z} from 'zod' export type GetApiV1MarketSymbolStatsArgs = {symbol: string, start_time?: (string | null) | undefined, end_time?: (string | null) | undefined, limit?: (number | null) | undefined, timeframe?: (string | null) | undefined}; export type GetApiV1MarketSymbolStatsOptions = {baseUrl?: string | undefined, PhoenixBearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const marketStatsPoint = z.object({mark_price: z.number(), open_interest: z.number(), slot: z.number().int(), spot_price: z.number(), timestamp: z.string(), total_maker_fees: z.number().nullable().optional(), total_taker_fees: z.number().nullable().optional()}); export const marketStatsHistoryResponse = z.object({market_id: z.number().int(), stats: z.array(marketStatsPoint), symbol: z.string(), timeframe: z.string().nullable().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 }; /** * Get market stats history * * GET /v1/market/{symbol}/stats */ export const getApiV1MarketSymbolStats = async (args: GetApiV1MarketSymbolStatsArgs, options?: GetApiV1MarketSymbolStatsOptions) => { const {baseUrl = "https://perp-api.phoenix.trade", fetch: fetchFn = fetch, PhoenixBearerAuth} = 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.limit != null) query.append("limit", String(args.limit)) if (args.timeframe != null) query.append("timeframe", String(args.timeframe)) if (PhoenixBearerAuth !== undefined) headers.set('authorization', `Bearer ${PhoenixBearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/market/${encodeURIComponent(String(args.symbol))}/stats${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(marketStatsHistoryResponse, await res.json()) };