import {z} from 'zod' export type CreateApiV3OrdersArgs = {body: {contract_id: string, label?: string | undefined, market_id: string, minimum_accepted_quantity?: number | undefined, price: number, quantity: number, side: 'buy' | 'sell', type?: ('good_til_cancelled' | 'keep_in_play' | 'good_til_halted' | 'immediate_or_cancel') | undefined}}; export type CreateApiV3OrdersOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiV3OrdersResponse = z.object({available_balance: z.string(), available_quantity: z.number().int(), contract_id: z.string(), executed_avg_price: z.number().int().nullable(), exposure: z.string(), market_id: z.string(), order_id: z.string(), orig_price: z.number().int().nullable(), price: z.number().int().gte(1).lte(9999), quantity: z.number().int().gte(0).lte(4294967295), side: z.enum(["buy", "sell"]), total_executed_quantity: z.number().int()}); 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 orders on the exchange. * * POST /v3/orders/ */ export const createApiV3Orders = async (args: CreateApiV3OrdersArgs, options?: CreateApiV3OrdersOptions) => { const {baseUrl = "https://api.smarkets.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKey !== undefined) headers.set("Authorization", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v3/orders/${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(createApiV3OrdersResponse, await res.json()) };