import {z} from 'zod' export type Side = 'buy' | 'sell'; export type OrderType = 'batch' | 'market'; export type FeesRequest = {pct?: unknown | undefined, base_amount?: unknown | undefined}; export type ActorRequest = {type: 'person', person: string}; export type CreateOrderRequest = {side: Side, type: OrderType, instrument: string, amount?: string | undefined, quantity?: string | undefined, fees: FeesRequest, currency: string, securities_account?: string | undefined, actor?: ActorRequest | undefined}; export type CreateApiAccountsAccountIdOrdersArgs = {account_id: string, 'LMG-Data-Privacy-Access-Principal': string, 'LMG-Data-Privacy-Access-Justification': string, 'Idempotency-Key'?: string | undefined, body: CreateOrderRequest}; export type CreateApiAccountsAccountIdOrdersOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const side = z.enum(["buy", "sell"]); export const orderType = z.enum(["batch", "market"]); export const feesResponse = z.object({pct: z.string().optional(), base_amount: z.string().optional()}); export const orderStatus = z.enum(["accepted", "canceled", "canceling", "confirmed", "created", "executed", "rejected"]); export const actorResponse = z.object({type: z.literal("person"), person: z.string()}); export const orderRejectionReason = z.enum(["insufficient_buying_power", "insufficient_available_securities", "insufficient_order_amount", "rejected_by_exchange", "manual_rejection", "unknown"]); export const statusChangeResponse = z.object({status: orderStatus, timestamp: z.string(), actor: actorResponse.optional(), reason: orderRejectionReason.nullable().optional()}); export const brokerAppsApiTypesRegulatoryDisclosureResponse = z.object({kid: z.string().optional(), estimated_amount: z.string(), estimated_price: z.string(), estimated_quantity: z.string(), service_costs_total: z.string(), service_costs_total_pct: z.string(), entry_costs: z.string().optional(), entry_costs_pct: z.string().optional(), third_party_grants: z.string(), third_party_grants_pct: z.string(), product_costs: z.string().optional(), product_costs_pct: z.string().optional(), running_costs: z.string().optional(), running_costs_pct: z.string().optional(), exit_costs: z.string(), exit_costs_pct: z.string(), acquisition_costs: z.string().optional(), acquisition_costs_pct: z.string().optional(), custody_costs: z.string().optional(), custody_costs_pct: z.string().optional(), impact_first_year: z.string().optional(), impact_first_year_pct: z.string().optional(), impact_subsequent_year: z.string().optional(), impact_subsequent_year_pct: z.string().optional(), impact_final_year: z.string().optional(), impact_final_year_pct: z.string().optional()}); export const appropriatenessConsentResponse = z.object({required: z.boolean()}); export const strongCustomerAuthenticationRequest = z.object({required: z.boolean(), challenge: z.string()}); export const orderResponse = z.object({id: z.string(), side: side, type: orderType, workflow: z.string().optional(), instrument: z.string(), amount: z.string().optional(), quantity: z.string().optional(), fee: z.string(), fees: feesResponse, currency: z.string().min(3).max(3), history: z.array(statusChangeResponse).optional(), regulatory_disclosures: brokerAppsApiTypesRegulatoryDisclosureResponse.optional(), appropriateness_check: appropriatenessConsentResponse.optional(), sca: strongCustomerAuthenticationRequest.optional(), securities_account: z.string().optional()}); 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 }; /** * Create Order * * POST /accounts/{account_id}/orders */ export const createApiAccountsAccountIdOrders = async (args: CreateApiAccountsAccountIdOrdersArgs, options?: CreateApiAccountsAccountIdOrdersOptions) => { const {baseUrl = "https://sandbox.api.lemon.markets/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['LMG-Data-Privacy-Access-Principal'] != null) headers.set("LMG-Data-Privacy-Access-Principal", String(args['LMG-Data-Privacy-Access-Principal'])) if (args['LMG-Data-Privacy-Access-Justification'] != null) headers.set("LMG-Data-Privacy-Access-Justification", String(args['LMG-Data-Privacy-Access-Justification'])) if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/accounts/${encodeURIComponent(String(args.account_id))}/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(orderResponse, await res.json()) };