import {z} from 'zod' export type TradingAccountId = string; export type MarketSymbol = string; export type MarketTypeAsString = 'SPOT' | 'PERPETUAL' | 'DATED_FUTURE' | 'OPTION'; export type OptionTypeAsString = 'CALL' | 'PUT'; export type MarketTypeOrOptionTypeSortByAsString = 'marketType' | 'optionType'; export type GetApiV1DerivativesPositionsArgs = {tradingAccountId?: TradingAccountId | undefined, symbol?: MarketSymbol | undefined, marketType?: MarketTypeAsString | undefined, optionType?: OptionTypeAsString | undefined, sort?: MarketTypeOrOptionTypeSortByAsString | undefined}; export type GetApiV1DerivativesPositionsOptions = {baseUrl?: string | undefined, jwtTokenAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const tradingAccountId = z.string(); export const marketSymbol = z.string(); export const orderSide = z.enum(["BUY", "SELL"]); export const assetValue = z.string(); export const usdcValue = z.string(); export const dateTime = z.string(); export const timeStampAsString = z.string(); export const positionGreeks = z.object({delta: z.string().optional(), gamma: z.string().optional(), theta: z.string().optional(), vega: z.string().optional()}); export const derivativesPositionResponse = z.object({tradingAccountId: tradingAccountId.optional(), symbol: marketSymbol.optional(), side: orderSide.optional(), quantity: assetValue.optional(), notional: usdcValue.optional(), entryNotional: usdcValue.optional(), mtmPnl: usdcValue.optional(), reportedMtmPnl: usdcValue.optional(), reportedFundingPnl: usdcValue.optional(), realizedPnl: usdcValue.optional(), settlementAssetSymbol: z.string().optional(), createdAtDatetime: dateTime.optional(), createdAtTimestamp: timeStampAsString.optional(), updatedAtDatetime: dateTime.optional(), updatedAtTimestamp: timeStampAsString.optional(), greeks: positionGreeks.optional()}); export const getApiV1DerivativesPositionsResponse = z.array(derivativesPositionResponse); 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 }; /** * Get Derivatives Positions * * GET /v1/derivatives-positions */ export const getApiV1DerivativesPositions = async (args: GetApiV1DerivativesPositionsArgs, options?: GetApiV1DerivativesPositionsOptions) => { const {baseUrl = "https://api.exchange.bullish.com/trading-api", fetch: fetchFn = fetch, jwtTokenAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.tradingAccountId != null) query.append("tradingAccountId", String(args.tradingAccountId)) if (args.symbol != null) query.append("symbol", String(args.symbol)) if (args.marketType != null) query.append("marketType", String(args.marketType)) if (args.optionType != null) query.append("optionType", String(args.optionType)) if (args.sort != null) query.append("sort", String(args.sort)) if (jwtTokenAuth !== undefined) headers.set('authorization', `Bearer ${jwtTokenAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/derivatives-positions${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiV1DerivativesPositionsResponse, await res.json()) };