import {z} from 'zod' export type GetApiV1SecuritiesTickerOptionsChainArgs = {ticker: string, expiration?: string | undefined, minStrike?: number | undefined, maxStrike?: number | undefined, type?: string | undefined, limit?: number | undefined}; export type GetApiV1SecuritiesTickerOptionsChainOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const optionPreviousSessionDto = z.object({date: z.string().nullable().optional(), open: z.number().nullable().optional(), high: z.number().nullable().optional(), low: z.number().nullable().optional(), close: z.number().nullable().optional(), volume: z.number().int().nullable().optional(), vwap: z.number().nullable().optional(), tradeCount: z.number().int().nullable().optional()}); export const optionLastTradeDto = z.object({price: z.number().nullable().optional(), size: z.number().int().nullable().optional(), time: z.string().nullable().optional(), exchange: z.string().nullable().optional()}); export const optionContractDto = z.object({occTicker: z.string().nullable().optional(), contractType: z.string().nullable().optional(), exerciseStyle: z.string().nullable().optional(), strikePrice: z.number().optional(), expirationDate: z.string().optional(), sharesPerContract: z.number().int().optional(), snapshotDate: z.string().nullable().optional(), dayOpen: z.number().nullable().optional(), dayHigh: z.number().nullable().optional(), dayLow: z.number().nullable().optional(), dayClose: z.number().nullable().optional(), dayVolume: z.number().int().nullable().optional(), dayVwap: z.number().nullable().optional(), dayTradeCount: z.number().int().nullable().optional(), previousSession: optionPreviousSessionDto.optional(), impliedVolatility: z.number().nullable().optional(), openInterest: z.number().int().nullable().optional(), openInterestDate: z.string().nullable().optional(), delta: z.number().nullable().optional(), gamma: z.number().nullable().optional(), theta: z.number().nullable().optional(), vega: z.number().nullable().optional(), rho: z.number().nullable().optional(), greeksBasis: z.string().nullable().optional(), bidPrice: z.number().nullable().optional(), askPrice: z.number().nullable().optional(), bidSize: z.number().int().nullable().optional(), askSize: z.number().int().nullable().optional(), bidExchange: z.string().nullable().optional(), askExchange: z.string().nullable().optional(), quoteAsOf: z.string().nullable().optional(), delayed: z.boolean().optional(), lastTrade: optionLastTradeDto.optional()}); export const optionChainResponse = z.object({ticker: z.string().nullable().optional(), companyName: z.string().nullable().optional(), currency: z.string().nullable().optional(), expiration: z.string().nullable().optional(), quotesAvailable: z.boolean().optional(), returned: z.number().int().optional(), total: z.number().int().optional(), truncated: z.boolean().optional(), contracts: z.array(optionContractDto).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 }; /** * The option chain (calls and puts) for a stock for ONE expiration: strike, greeks (delta/gamma/theta/vega), implied volatility, open interest, daily price figures, and bid/ask. Defaults to the nearest upcoming expiration; pass `expiration=YYYY-MM-DD` to pick another. When the expiration holds more contracts than `limit`, the ones nearest the money are returned (`truncated` flags the cut). Narrow with `minStrike`/`maxStrike` and `type` (call/put) to reach the wings. Each contract's daily price and volume fields belong to snapshotDate, while openInterest belongs to its separate openInterestDate; bid/ask use real-time consolidated OPRA on Pro or a 15-minute delayed indicative feed on Plus. The Free plan covers end-of-day data only and receives 403. A Canadian listing (MIC:TICKER on XTSE or XTSX, e.g. XTSE:RY) returns the exchange's real-time bid/ask, implied volatility and open interest on Plus and Pro, in CAD (`currency`), with greeks computed from that implied volatility (`greeksBasis`). * * GET /v1/securities/{ticker}/options/chain */ export const getApiV1SecuritiesTickerOptionsChain = async (args: GetApiV1SecuritiesTickerOptionsChainArgs, options?: GetApiV1SecuritiesTickerOptionsChainOptions) => { const {baseUrl = "https://api.equibles.com", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.expiration != null) query.append("expiration", String(args.expiration)) if (args.minStrike != null) query.append("minStrike", String(args.minStrike)) if (args.maxStrike != null) query.append("maxStrike", String(args.maxStrike)) if (args.type != null) query.append("type", String(args.type)) if (args.limit != null) query.append("limit", String(args.limit)) if (ApiKey !== undefined) headers.set('authorization', `Bearer ${ApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/securities/${encodeURIComponent(String(args.ticker))}/options/chain${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(optionChainResponse, await res.json()) };