import {z} from 'zod' export type OrderAllocation = {quantity: string, subaccountId: string}; export type NewOrderSingle = {accountId?: string | undefined, allocation?: Array | undefined, clOrderId: string, currency: string, limitPrice?: string | undefined, orderType: 'MARKET' | 'LIMIT' | 'RFQ' | 'LIMIT_ALL_IN', quantity: string, side: 'BUY' | 'SELL', subaccountId?: string | undefined, symbol: string, timestamp: string}; export type CreateApiTradingOrderArgs = {body: NewOrderSingle}; export type CreateApiTradingOrderOptions = {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 orderExecutionReport = z.object({accountId: z.string().optional(), allocation: z.array(allocation).optional(), avgPx: z.string(), avgPxAllIn: z.string().optional(), clOrderId: z.string(), counterCurrency: z.string(), counterQty: z.string(), counterQtyAllIn: z.string(), cumQty: z.string(), currency: z.string(), execId: z.string(), fee: z.string().optional(), feeCurrency: z.string().optional(), limitPrice: z.string().optional(), orderId: z.string(), orderQty: z.string(), orderStatus: z.enum(["FILLED", "REJECTED", "CANCELED"]), orderType: z.enum(["MARKET", "LIMIT"]), reasonText: z.string().optional(), rejectReason: z.enum(["InvalidSymbol", "InvalidCurrency", "InvalidSide", "InvalidQuantity", "InvalidOrderType", "InvalidAccount", "AccountDisabledForTrading", "UnauthorizedForTrading", "InsufficientLiquidity", "DuplicateOrder", "ExecutionLimitExceeded", "InternalError", "InvalidPrice", "InvalidAccountsInAllocation", "InvalidCurrencyForFOK"]).optional(), side: z.enum(["BUY", "SELL"]), subaccountId: z.string().optional(), subaccountTransactionId: z.string().optional(), symbol: z.string(), transactTime: z.string()}); export const tradingOrderResponse = z.object({data: orderExecutionReport}); 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 order * * POST /trading/order */ export const createApiTradingOrder = async (args: CreateApiTradingOrderArgs, options?: CreateApiTradingOrderOptions) => { 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/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(tradingOrderResponse, await res.json()) };