import {z} from 'zod' export type CreateApiTradingAsyncOrderCancelArgs = {orderId?: string | undefined, clOrderId?: string | undefined}; export type CreateApiTradingAsyncOrderCancelOptions = {baseUrl?: string | undefined, ApiAccessKey?: string | undefined, fetch?: typeof fetch | undefined}; export const allocation = z.object({counterQtyAllIn: z.string(), counterQtyAllInToSettle: z.string(), cumQty: z.string(), executionId: z.string().optional(), fee: z.string(), quantity: z.string(), subaccountId: z.string()}); export const asyncOrderExecutionReport = z.object({accountId: z.string().optional(), allocation: z.array(allocation).optional(), avgPx: z.string(), avgPxAllIn: z.string().optional(), cancelQty: z.string().optional(), clOrderId: z.string(), counterCurrency: z.string(), counterQty: z.string(), counterQtyAllIn: z.string(), cumQty: z.string(), currency: z.string(), execId: z.string().optional(), execType: z.enum(["PENDING_NEW", "REJECTED"]).optional(), fee: z.string().optional(), feeCurrency: z.string().optional(), leavesQty: z.string().optional(), limitPrice: z.string().optional(), orderId: z.string(), orderQty: z.string(), orderStatus: z.enum(["FILLED", "REJECTED", "CANCELED", "PENDING_NEW", "PARTIALLY_FILLED", "PENDING_CANCEL"]), orderType: z.enum(["LIMIT", "STOP_LIMIT", "TAKE_PROFIT_LIMIT", "STOP_LOSS"]), reasonText: z.string().optional(), rejectReason: z.enum(["InvalidTimeInForce", "InvalidSymbol", "InvalidCurrency", "InvalidSide", "InvalidQuantity", "InvalidOrderType", "InvalidAccount", "AccountDisabledForTrading", "UnauthorizedForTrading", "InsufficientLiquidity", "DuplicateOrder", "ExecutionLimitExceeded", "InternalError", "InvalidPrice", "InvalidLimitPrice", "InvalidTriggerPrice", "OrderNotCancelable", "InvalidAccountsInAllocation", "InvalidCurrencyForFOK"]).optional(), side: z.enum(["BUY", "SELL"]), subaccountId: z.string().optional(), submitTime: z.string(), symbol: z.string(), timeInForce: z.enum(["FOK", "IOC", "GTC"]).optional(), transactTime: z.string()}); export const asyncOrderResponse = z.object({data: asyncOrderExecutionReport}); 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 }; /** * Cancel an async order * * POST /trading/async-order/cancel */ export const createApiTradingAsyncOrderCancel = async (args: CreateApiTradingAsyncOrderCancelArgs, options?: CreateApiTradingAsyncOrderCancelOptions) => { const {baseUrl = "https://api.anchorage-staging.com/v2", fetch: fetchFn = fetch, ApiAccessKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.orderId != null) query.append("orderId", String(args.orderId)) if (args.clOrderId != null) query.append("clOrderId", String(args.clOrderId)) if (ApiAccessKey !== undefined) headers.set("Api-Access-Key", ApiAccessKey) const url = `${baseUrl.replace(/\/+$/, '')}/trading/async-order/cancel${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(asyncOrderResponse, await res.json()) };