import {z} from 'zod' export type Boolean = boolean; export type TradingAccountId = string; export type SimulationPosition = {symbol: string, quantity: string}; export type MarketSymbol = string; export type OrderTimeInForceAsString = string; export type SimulationOrder = {symbol: MarketSymbol, quantity: string, limitPrice?: string | undefined, timeInForce?: OrderTimeInForceAsString | undefined}; export type ReferencePrice = {symbol?: string | undefined, price?: string | undefined}; export type PriceVolOffsetParams = {cryptoPriceMultipliers?: {[key: string]: number} | undefined, globalCryptoPriceMultiplier?: number | undefined, volOffset?: number | undefined}; export type PortfolioSimulationRequest = {tradingAccountId: TradingAccountId, positions?: Array | undefined, orders?: Array | undefined, referencePrices?: Array | undefined, priceVolOffsetParams?: PriceVolOffsetParams | undefined}; export type CreateApiV1SimulatePortfolioMarginArgs = {includeExisting?: Boolean | undefined, body: PortfolioSimulationRequest}; export type CreateApiV1SimulatePortfolioMarginOptions = {baseUrl?: string | undefined, jwtTokenAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const portfolioSimulationResponse = z.object({collateralUSD: z.string().optional(), borrowedUSD: z.string().optional(), initialMarginUSD: z.string().optional(), warningMarginUSD: z.string().optional(), liquidationMarginUSD: z.string().optional(), fullLiquidationMarginUSD: z.string().optional(), defaultedMarginUSD: z.string().optional(), liquidityAddonUSD: z.string().optional(), marketRiskUSD: 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 }; /** * Simulate Portfolio Margin * * POST /v1/simulate-portfolio-margin */ export const createApiV1SimulatePortfolioMargin = async (args: CreateApiV1SimulatePortfolioMarginArgs, options?: CreateApiV1SimulatePortfolioMarginOptions) => { const {baseUrl = "https://api.exchange.bullish.com/trading-api", fetch: fetchFn = fetch, jwtTokenAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.includeExisting != null) query.append("includeExisting", String(args.includeExisting)) if (jwtTokenAuth !== undefined) headers.set('authorization', `Bearer ${jwtTokenAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/simulate-portfolio-margin${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(portfolioSimulationResponse, await res.json()) };