import {z} from 'zod' export type ConnectProtocolVersion = number; export type ConnectTimeoutHeader = number; export type PortfolioV1GetPortfolioRequest = {owner: string}; export type CreateApiPortfolioV1PortfolioServiceGetPortfolioArgs = {'Connect-Protocol-Version': ConnectProtocolVersion, 'Connect-Timeout-Ms'?: ConnectTimeoutHeader | undefined, body: PortfolioV1GetPortfolioRequest}; export type CreateApiPortfolioV1PortfolioServiceGetPortfolioOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const googleProtobufTimestamp = z.string(); export const baseObjectsV1Side = z.enum(["SIDE_LONG", "SIDE_SHORT"]); export const baseObjectsV1MarginType = z.literal("MARGIN_TYPE_ISOLATED"); export const baseObjectsV1OrderType = z.literal("ORDER_TYPE_MARKET"); export const baseObjectsV1OrderStatus = z.enum(["ORDER_STATUS_PENDING", "ORDER_STATUS_PARTIALLY_FILLED", "ORDER_STATUS_FULLY_FILLED", "ORDER_STATUS_CLOSED", "ORDER_STATUS_CANCELLED", "ORDER_STATUS_MERGED", "ORDER_STATUS_PARTIALLY_MERGED", "ORDER_STATUS_PARTIALLY_CANCELLED"]); export const baseObjectsV1Order = z.object({owner: z.string().optional(), orderId: z.string().optional(), timestamp: googleProtobufTimestamp.optional(), marketId: z.string().optional(), market: z.string().optional(), type: baseObjectsV1OrderType.optional(), side: baseObjectsV1Side.optional(), thresholdPrice: z.number().optional(), size: z.number().optional(), leverage: z.number().optional(), status: baseObjectsV1OrderStatus.optional(), filledSize: z.number().optional(), unfilledSize: z.number().optional(), reduceOnly: z.boolean().optional(), canceled: z.boolean().optional(), initialMargin: z.number().optional(), tickDecimals: z.number().int().optional(), fees: z.number().optional(), rebates: z.number().optional(), reduceOrderType: z.string().optional(), initialNotional: z.number().optional(), stopLossPrice: z.number().optional(), takeProfitPrice: z.number().optional()}); export const baseObjectsV1OrderRef = z.object({orderId: z.union([z.number().int(), z.string()]).optional(), marketId: z.union([z.number().int(), z.string()]).optional(), reduceOnly: z.boolean().optional()}); export const baseObjectsV1Position = z.object({owner: z.string().optional(), positionId: z.string().optional(), marketId: z.string().optional(), timestamp: googleProtobufTimestamp.optional(), market: z.string().optional(), side: baseObjectsV1Side.optional(), marginType: baseObjectsV1MarginType.optional(), nominalSize: z.number().optional(), entryPrice: z.number().optional(), markPrice: z.number().optional(), liquidationPrice: z.number().optional(), allocatedMargin: z.number().optional(), leverage: z.number().optional(), unrealizedPnl: z.number().optional(), reduceOnly: z.boolean().optional(), associatedOrders: z.array(baseObjectsV1Order).optional(), associatedOrderIds: z.array(baseObjectsV1OrderRef).optional(), tickDecimals: z.number().int().optional(), revenueSpent: z.number().optional(), effectiveSize: z.number().optional(), estimatedRebate: z.number().optional(), stopLossPrice: z.number().optional(), takeProfitPrice: z.number().optional()}); export const baseObjectsV1Portfolio = z.object({owner: z.string().optional(), timestamp: googleProtobufTimestamp.optional(), totalMargin: z.number().optional(), totalUnrealizedPnl: z.number().optional(), totalRealizedPnl: z.number().optional(), totalVolume: z.number().optional(), totalFees: z.number().optional(), totalProfit: z.number().optional(), totalLoss: z.number().optional(), totalTrades: z.string().optional(), totalEquity: z.number().optional(), maxDrawdown: z.number().optional(), positions: z.array(baseObjectsV1Position).optional(), orders: z.array(baseObjectsV1Order).optional()}); export const portfolioV1GetPortfolioResponse = z.object({portfolio: baseObjectsV1Portfolio.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 }; /** * GetPortfolio * * POST /portfolio.v1.PortfolioService/GetPortfolio */ export const createApiPortfolioV1PortfolioServiceGetPortfolio = async (args: CreateApiPortfolioV1PortfolioServiceGetPortfolioArgs, options?: CreateApiPortfolioV1PortfolioServiceGetPortfolioOptions) => { const {baseUrl = "https://api.fairground.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 (args['Connect-Protocol-Version'] != null) headers.set("Connect-Protocol-Version", String(args['Connect-Protocol-Version'])) if (args['Connect-Timeout-Ms'] != null) headers.set("Connect-Timeout-Ms", String(args['Connect-Timeout-Ms'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/portfolio.v1.PortfolioService/GetPortfolio${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(portfolioV1GetPortfolioResponse, await res.json()) };