import {z} from 'zod' export type Symbol = string; 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 SetTradingStopRequest = {active_price?: (string | null) | undefined, sl_size?: (string | null) | undefined, sub_account_address: string, symbol: Symbol, tp_size?: (string | null) | undefined, tpsl?: (TpSl | null) | undefined, trailing_stop?: (string | null) | undefined}; export type CreateApiApiV1PositionTradingStopArgs = {body: SetTradingStopRequest}; export type CreateApiApiV1PositionTradingStopOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const setTradingStopResponse = z.object({success: z.boolean(), time: z.string()}); 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 }; /** * Set Trading Stop * * POST /api/v1/position/trading-stop */ export const createApiApiV1PositionTradingStop = async (args: CreateApiApiV1PositionTradingStopArgs, options?: CreateApiApiV1PositionTradingStopOptions) => { 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/position/trading-stop${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(setTradingStopResponse, await res.json()) };