import {z} from 'zod' export type AccountId = string; export type OrderId = string; export type GetApiAccountsAccountIdOrdersOrderIdArgs = {account_id: AccountId, order_id: OrderId}; export type GetApiAccountsAccountIdOrdersOrderIdOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const timestamp = z.number().int().gte(1710613560668).lte(2900000000000); export const orderId = z.string().min(1).max(256); export const referenceId = z.string().min(1).max(256); export const accountId = z.string().min(1).max(256); export const accountNumber = z.string().min(1).max(256); export const orderState = z.enum(["open", "rejected", "closed"]); export const orderStatus = z.enum(["new", "partially-filled", "filled", "canceled", "replaced", "pending-cancel", "stopped", "rejected", "suspended", "pending-new", "calculated", "expired", "accepted-for-bidding", "pending-replace", "done-for-day"]); export const symbol = z.string().min(1).max(32); export const orderType = z.enum(["limit", "market", "stop", "stop-limit"]); export const orderSide = z.enum(["buy", "sell", "sell-short"]); export const quantity = z.string().min(1).max(16); export const price = z.string().min(1).max(16); export const timeInForce = z.enum(["day", "ioc", "day-plus", "at-open", "at-close"]); export const orderUpdateReason = z.enum(["place", "modify", "cancel", "execution-report", "cancel-reject", "reject"]); export const strategyType = z.enum(["sor", "dark", "ap", "pov", "twap", "vwap", "dma"]); export const urgency = z.enum(["super-passive", "passive", "moderate", "aggressive", "super-aggressive"]); export const sorStrategy = z.object({type: strategyType, start_at: timestamp.optional(), end_at: timestamp.optional(), urgency: urgency.optional()}); export const minPercent = z.number().int().gte(0).lte(100); export const maxPercentVolume = z.number().int().gte(0).lte(50); export const vwapStrategy = z.object({type: strategyType, start_at: timestamp.optional(), end_at: timestamp.optional(), urgency: urgency.optional(), min_percent: minPercent.optional(), max_percent: maxPercentVolume.optional()}); export const twapStrategy = z.object({type: strategyType, start_at: timestamp.optional(), end_at: timestamp.optional(), urgency: urgency.optional(), min_percent: minPercent.optional(), max_percent: maxPercentVolume.optional()}); export const maxPercent = z.number().int().gte(0).lte(100); export const apStrategy = z.object({type: strategyType, start_at: timestamp.optional(), end_at: timestamp.optional(), urgency: urgency.optional(), min_percent: minPercent.optional(), max_percent: maxPercent.optional()}); export const targetPercent = z.number().int().gte(0).lte(100); export const povStrategy = z.object({type: strategyType, start_at: timestamp.optional(), end_at: timestamp.optional(), urgency: urgency.optional(), target_percent: targetPercent}); export const darkStrategy = z.object({type: strategyType, start_at: timestamp.optional(), end_at: timestamp.optional(), urgency: urgency.optional(), max_percent: maxPercent.optional()}); export const destination = z.enum(["arcx", "bats", "baty", "edga", "edgx", "eprl", "iexg", "memx", "xase", "xbos", "xcis", "xnms", "xnys"]); export const dmaStrategy = z.object({type: strategyType, destination: destination}); export const strategy = z.discriminatedUnion("type", [sorStrategy, vwapStrategy, twapStrategy, apStrategy, povStrategy, darkStrategy, dmaStrategy]); export const openCloseIndicator = z.enum(["open", "close"]); export const order = z.object({created_at: timestamp, updated_at: timestamp, order_id: orderId, reference_id: referenceId.optional(), version: z.number().int(), account_id: accountId, account_number: accountNumber, state: orderState, status: orderStatus, symbol: symbol, order_type: orderType, side: orderSide, quantity: quantity, price: price.optional(), stop_price: price.optional(), time_in_force: timeInForce, average_price: z.number().optional(), filled_quantity: quantity, order_update_reason: orderUpdateReason.optional(), text: z.string().optional(), strategy: strategy.optional(), running_position: quantity, open_close_indicator: openCloseIndicator.optional()}); export const getApiAccountsAccountIdOrdersOrderIdResponse = z.object({order: order}); 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 order * * GET /accounts/{account_id}/orders/{order_id} */ export const getApiAccountsAccountIdOrdersOrderId = async (args: GetApiAccountsAccountIdOrdersOrderIdArgs, options?: GetApiAccountsAccountIdOrdersOrderIdOptions) => { const {baseUrl = "https://api.clearstreet.io/studio/v2", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/accounts/${encodeURIComponent(String(args.account_id))}/orders/${encodeURIComponent(String(args.order_id))}${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(getApiAccountsAccountIdOrdersOrderIdResponse, await res.json()) };