import {z} from 'zod' export type OrderAllocation = {quantity: string, subaccountId: string}; export type NewAsyncOrder = {accountId?: string | undefined, allocation?: Array | undefined, clOrderId: string, currency: string, limitPrice?: string | undefined, orderType: 'LIMIT' | 'STOP_LOSS' | 'STOP_LIMIT' | 'TAKE_PROFIT_LIMIT', parameters?: ({endTime?: string | undefined, triggerPrice?: string | undefined}) | undefined, quantity: string, side: 'BUY' | 'SELL', subaccountId?: string | undefined, symbol: string, timeInForce: 'FOK' | 'IOC' | 'GTC', timestamp: string}; export type CreateApiTradingAsyncOrderArgs = {body: NewAsyncOrder}; export type CreateApiTradingAsyncOrderOptions = {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 }; /** * Place an async order * * POST /trading/async-order */ export const createApiTradingAsyncOrder = async (args: CreateApiTradingAsyncOrderArgs, options?: CreateApiTradingAsyncOrderOptions) => { const {baseUrl = "https://api.anchorage-staging.com/v2", fetch: fetchFn = fetch, ApiAccessKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiAccessKey !== undefined) headers.set("Api-Access-Key", ApiAccessKey) const url = `${baseUrl.replace(/\/+$/, '')}/trading/async-order${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(asyncOrderResponse, await res.json()) };