import {z} from 'zod' export type TradableFilter = 'TRADABLE_FILTER_TRADABLE' | 'TRADABLE_FILTER_NON_TRADABLE' | 'TRADABLE_FILTER_ALL'; export type InstrumentState = 'INSTRUMENT_STATE_CLOSED' | 'INSTRUMENT_STATE_OPEN' | 'INSTRUMENT_STATE_PREOPEN' | 'INSTRUMENT_STATE_SUSPENDED' | 'INSTRUMENT_STATE_EXPIRED' | 'INSTRUMENT_STATE_TERMINATED' | 'INSTRUMENT_STATE_HALTED' | 'INSTRUMENT_STATE_MATCH_AND_CLOSE_AUCTION' | 'INSTRUMENT_STATE_PENDING'; export type FilterOperator = 'FILTER_OPERATOR_UNSPECIFIED' | 'FILTER_OPERATOR_EQ' | 'FILTER_OPERATOR_LIKE' | 'FILTER_OPERATOR_IN'; export type StringList = {values?: Array | undefined}; export type FieldFilter = {field?: string | undefined, operator?: FilterOperator | undefined, stringValue?: string | undefined, stringList?: StringList | undefined}; export type InstrumentFilter = {whereClause?: string | undefined, fieldFilters?: Array | undefined}; export type ListInstrumentsRequest = {pageSize?: number | undefined, pageToken?: string | undefined, symbols?: Array | undefined, productId?: string | undefined, tradableFilter?: TradableFilter | undefined, states?: Array | undefined, eventSeries?: string | undefined, eventCategory?: string | undefined, clearingSym?: string | undefined, startTimeGte?: string | undefined, startTimeLte?: string | undefined, endTimeGte?: string | undefined, endTimeLte?: string | undefined, filter?: InstrumentFilter | undefined}; export type CreateApiV1RefdataInstrumentsArgs = {body: ListInstrumentsRequest}; export type CreateApiV1RefdataInstrumentsOptions = {baseUrl?: string | undefined, XPMAccessKey?: string | undefined, XPMTimestamp?: string | undefined, XPMSignature?: string | undefined, fetch?: typeof fetch | undefined}; export const date = z.object({year: z.number().int().optional(), month: z.number().int().optional(), day: z.number().int().optional()}); export const timeOfDay = z.object({hours: z.number().int().optional(), minutes: z.number().int().optional(), seconds: z.number().int().optional()}); export const instrumentState = z.enum(["INSTRUMENT_STATE_CLOSED", "INSTRUMENT_STATE_OPEN", "INSTRUMENT_STATE_PREOPEN", "INSTRUMENT_STATE_SUSPENDED", "INSTRUMENT_STATE_EXPIRED", "INSTRUMENT_STATE_TERMINATED", "INSTRUMENT_STATE_HALTED", "INSTRUMENT_STATE_MATCH_AND_CLOSE_AUCTION", "INSTRUMENT_STATE_PENDING"]); export const tradingHours = z.object({daysOfWeek: z.array(z.number().int()).optional(), timeOfDay: timeOfDay.optional(), duration: z.string().optional(), state: instrumentState.optional(), hideMarketData: z.boolean().optional(), expireAllOrders: z.boolean().optional()}); export const priceLimit = z.object({low: z.string().optional(), high: z.string().optional(), lowSet: z.boolean().optional(), highSet: z.boolean().optional(), relativeLow: z.number().optional(), relativeHigh: z.number().optional(), relativeLowSet: z.boolean().optional(), relativeHighSet: z.boolean().optional()}); export const orderSizeLimit = z.object({low: z.string().optional(), high: z.string().optional(), lowSet: z.boolean().optional(), highSet: z.boolean().optional(), totalNotionalLow: z.string().optional(), totalNotionalHigh: z.string().optional(), totalNotionalLowSet: z.boolean().optional(), totalNotionalHighSet: z.boolean().optional()}); export const eventAttributes = z.object({question: z.string().optional(), payoutValue: z.string().optional(), eventDisplayName: z.string().optional(), eventId: z.string().optional(), strikeValue: z.string().optional(), evaluationType: z.string().optional(), strikeUnit: z.string().optional(), calculationMethod: z.string().optional(), timeSpecifier: z.string().optional(), positionAccountabilityValue: z.string().optional()}); export const instrument = z.object({symbol: z.string().optional(), tickSize: z.number().optional(), baseCurrency: z.string().optional(), multiplier: z.number().optional(), minimumTradeQty: z.string().optional(), startDate: date.optional(), expirationDate: date.optional(), terminationDate: date.optional(), tradingSchedule: z.array(tradingHours).optional(), description: z.string().optional(), clearingHouse: z.string().optional(), minimumUnaffiliatedFirms: z.string().optional(), nonTradable: z.boolean().optional(), jsonAttributes: z.string().optional(), productId: z.string().optional(), priceLimit: priceLimit.optional(), orderSizeLimit: orderSizeLimit.optional(), expirationTime: timeOfDay.optional(), tradeSettlementPeriod: z.string().optional(), state: instrumentState.optional(), priceScale: z.string().optional(), fractionalQtyScale: z.string().optional(), settlementCurrency: z.string().optional(), settlementPriceScale: z.string().optional(), metadata: z.record(z.string(), z.string()).optional(), eventAttributes: eventAttributes.optional(), createTime: z.string().optional(), updateTime: z.string().optional()}); export const listInstrumentsResponse = z.object({instruments: z.array(instrument).optional(), nextPageToken: z.string().optional(), eof: z.boolean().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 }; /** * List instruments * * POST /v1/refdata/instruments */ export const createApiV1RefdataInstruments = async (args: CreateApiV1RefdataInstrumentsArgs, options?: CreateApiV1RefdataInstrumentsOptions) => { const {baseUrl = "https://api.polymarket.us", fetch: fetchFn = fetch, XPMAccessKey, XPMTimestamp, XPMSignature} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (XPMAccessKey !== undefined) headers.set("X-PM-Access-Key", XPMAccessKey) if (XPMTimestamp !== undefined) headers.set("X-PM-Timestamp", XPMTimestamp) if (XPMSignature !== undefined) headers.set("X-PM-Signature", XPMSignature) const url = `${baseUrl.replace(/\/+$/, '')}/v1/refdata/instruments${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(listInstrumentsResponse, await res.json()) };