import {z} from 'zod' export type MarginMode = 'Cross' | 'Isolated'; export type OrderLinkId = string; export type OrderType = 'Limit' | 'Market'; export type Side = 'Sell' | 'Buy'; export type SlippageTolerance = {tick_size: number} | {percent: number}; export type SmpType = 'CancelMaker' | 'CancelTaker' | 'CancelBoth'; export type Symbol = string; export type TimeInForce = 'GTC' | 'IOC' | 'FOK' | {GTD: number} | 'Day'; export type TpSlMode = 'Full' | 'Partial'; export type TriggerBy = 'LastPrice' | 'IndexPrice' | 'MarkPrice'; export type TpSlSpec = {market: {trigger_by: TriggerBy, trigger_price: string}} | {limit: {limit_price: string, trigger_by: TriggerBy, trigger_price: string}}; export type TpSl = {mode: TpSlMode, stop_loss?: (TpSlSpec | null) | undefined, take_profit?: (TpSlSpec | null) | undefined}; export type TriggerDirection = 'Up' | 'Down'; export type ConditionalOrder = {trigger_by: TriggerBy, trigger_direction: TriggerDirection, trigger_price: string}; export type PlaceOrderRequest = {close_on_trigger?: boolean | undefined, expire_time?: (string | null) | undefined, margin_mode: MarginMode, order_link_id?: (OrderLinkId | null) | undefined, order_type: OrderType, post_only?: boolean | undefined, price: string, qty: string, reduce_only?: boolean | undefined, side: Side, slippage_tolerance?: (SlippageTolerance | null) | undefined, smp_group?: (number | null) | undefined, smp_type?: (SmpType | null) | undefined, sub_account_address: string, symbol: Symbol, time_in_force: TimeInForce, tpsl?: (TpSl | null) | undefined, trigger?: (ConditionalOrder | null) | undefined}; export type CreateApiApiV1OrderPlaceArgs = {body: PlaceOrderRequest}; export type CreateApiApiV1OrderPlaceOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const orderId = z.string(); export const orderLinkId = z.string(); export const placeOrderResponse = z.object({order_id: orderId, order_link_id: orderLinkId.nullable().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 }; /** * Place Order * * POST /api/v1/order/place */ export const createApiApiV1OrderPlace = async (args: CreateApiApiV1OrderPlaceArgs, options?: CreateApiApiV1OrderPlaceOptions) => { const {baseUrl = "https://api.ekiden.fi", 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 (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/order/place${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(placeOrderResponse, await res.json()) };