import {z} from 'zod' export type GetApiV1TradingOrdersOpenArgs = {symbols?: Array | undefined, accounts?: Array | undefined}; export type GetApiV1TradingOrdersOpenOptions = {baseUrl?: string | undefined, XPMAccessKey?: string | undefined, XPMTimestamp?: string | undefined, XPMSignature?: string | undefined, fetch?: typeof fetch | undefined}; export const orderType = z.enum(["ORDER_TYPE_MARKET_TO_LIMIT", "ORDER_TYPE_LIMIT", "ORDER_TYPE_STOP", "ORDER_TYPE_STOP_LIMIT"]); export const side = z.enum(["SIDE_BUY", "SIDE_SELL"]); export const timeInForce = z.enum(["TIME_IN_FORCE_DAY", "TIME_IN_FORCE_GOOD_TILL_CANCEL", "TIME_IN_FORCE_IMMEDIATE_OR_CANCEL", "TIME_IN_FORCE_GOOD_TILL_TIME", "TIME_IN_FORCE_FILL_OR_KILL"]); export const orderState = z.enum(["ORDER_STATE_PARTIALLY_FILLED", "ORDER_STATE_FILLED", "ORDER_STATE_CANCELED", "ORDER_STATE_REPLACED", "ORDER_STATE_REJECTED", "ORDER_STATE_EXPIRED", "ORDER_STATE_PENDING_NEW", "ORDER_STATE_PENDING_REPLACE", "ORDER_STATE_PENDING_CANCEL", "ORDER_STATE_PENDING_RISK"]); export const selfMatchPreventionInstruction = z.enum(["SELF_MATCH_PREVENTION_INSTRUCTION_REJECT_AGGRESSOR", "SELF_MATCH_PREVENTION_INSTRUCTION_CANCEL_RESTING", "SELF_MATCH_PREVENTION_INSTRUCTION_REMOVE_BOTH"]); export const orderCapacity = z.enum(["ORDER_CAPACITY_AGENCY", "ORDER_CAPACITY_PRINCIPAL", "ORDER_CAPACITY_PROPRIETARY", "ORDER_CAPACITY_INDIVIDUAL", "ORDER_CAPACITY_RISKLESS_PRINCIPAL", "ORDER_CAPACITY_AGENT_FOR_OTHER_MEMBER"]); export const manualOrderIndicator = z.enum(["MANUAL_ORDER_INDICATOR_MANUAL", "MANUAL_ORDER_INDICATOR_AUTOMATED"]); export const order = z.object({id: z.string().optional(), type: orderType.optional(), side: side.optional(), orderQty: z.string().optional(), symbol: z.string().optional(), clordId: z.string().optional(), timeInForce: timeInForce.optional(), account: z.string().optional(), cumQty: z.string().optional(), avgPx: z.string().optional(), leavesQty: z.string().optional(), state: orderState.optional(), participant: z.string().optional(), price: z.string().optional(), insertTime: z.string().optional(), stopPrice: z.string().optional(), minQty: z.string().optional(), createTime: z.string().optional(), allOrNone: z.boolean().optional(), crossId: z.string().optional(), hostCrossId: z.string().optional(), submittingParticipant: z.string().optional(), clientAccountId: z.string().optional(), clientParticipantId: z.string().optional(), parentOrderId: z.string().optional(), commissionsBasisPoints: z.string().optional(), participateDontInitiate: z.boolean().optional(), cashOrderQty: z.string().optional(), strictLimit: z.boolean().optional(), goodTillTime: z.string().optional(), bestLimit: z.boolean().optional(), immediatelyExecutableLimit: z.boolean().optional(), lastTradeId: z.string().optional(), commissionNotionalTotalCollected: z.string().optional(), selfMatchPreventionInstruction: selfMatchPreventionInstruction.optional(), orderCapacity: orderCapacity.optional(), ignorePriceValidityChecks: z.boolean().optional(), lastTransactTime: z.string().optional(), makerCommissionsBasisPoints: z.string().optional(), manualOrderIndicator: manualOrderIndicator.optional(), fractionalQuantityScale: z.string().optional(), priceToQuantityFilled: z.record(z.string(), z.string()).optional()}); export const getOpenOrdersResponse = z.object({orders: z.array(order).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 open orders * * GET /v1/trading/orders/open */ export const getApiV1TradingOrdersOpen = async (args: GetApiV1TradingOrdersOpenArgs, options?: GetApiV1TradingOrdersOpenOptions) => { const {baseUrl = "https://api.polymarket.us", fetch: fetchFn = fetch, XPMAccessKey, XPMTimestamp, XPMSignature} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") for (const item of args.symbols ?? []) query.append("symbols", String(item)) for (const item of args.accounts ?? []) query.append("accounts", String(item)) 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/trading/orders/open${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(getOpenOrdersResponse, await res.json()) };