import {z} from 'zod' export type AddPortfolioLotRequest = {ticker: string, optionContract?: (string | null) | undefined, quantity: number, costPerUnit: number, acquiredDate: string, note?: (string | null) | undefined, fxRate?: (number | null) | undefined}; export type CreateApiV1PortfoliosIdLotsArgs = {id: string, body: AddPortfolioLotRequest}; export type CreateApiV1PortfoliosIdLotsOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const portfolioFxRateDto = z.object({from: z.string().nullable().optional(), to: z.string().nullable().optional(), rate: z.number().optional(), asOf: z.string().nullable().optional()}); export const portfolioLotDto = z.object({id: z.string().optional(), instrumentKind: z.string().nullable().optional(), ticker: z.string().nullable().optional(), exchange: z.string().nullable().optional(), name: z.string().nullable().optional(), occTicker: z.string().nullable().optional(), expirationDate: z.string().nullable().optional(), strikePrice: z.number().nullable().optional(), contractType: z.string().nullable().optional(), sharesPerContract: z.number().int().nullable().optional(), quantity: z.number().optional(), costPerUnit: z.number().optional(), costBasis: z.number().nullable().optional(), currency: z.string().nullable().optional(), purchaseFxRate: z.number().nullable().optional(), purchaseFxCurrency: z.string().nullable().optional(), acquiredDate: z.string().optional(), note: z.string().nullable().optional(), closedDate: z.string().nullable().optional(), closePricePerUnit: z.number().nullable().optional(), marketValue: z.number().nullable().optional(), unrealizedGain: z.number().nullable().optional(), realizedGain: z.number().nullable().optional(), convertedCostBasis: z.number().nullable().optional(), convertedMarketValue: z.number().nullable().optional(), convertedUnrealizedGain: z.number().nullable().optional(), convertedRealizedGain: z.number().nullable().optional(), purchaseRate: portfolioFxRateDto.optional(), closeRate: portfolioFxRateDto.optional(), isOpen: z.boolean().optional()}); export const portfolioLotResponse = z.object({portfolioId: z.string().optional(), portfolioName: z.string().nullable().optional(), deduplicated: z.boolean().optional(), lot: portfolioLotDto.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 }; /** * Records one purchase or sale as a lot. Pass `optionContract` with the OCC symbol to * record an option contract, or omit it for shares. `quantity` is signed — negative for a short * sale or a written option — and `costPerUnit` is always a positive price per share, because the * direction is carried by the sign of the quantity alone. Repeating an identical request within * a few minutes returns the lot already recorded with `deduplicated: true` and HTTP 200 instead * of adding a second holding, so a retried timeout is safe. * * POST /v1/portfolios/{id}/lots */ export const createApiV1PortfoliosIdLots = async (args: CreateApiV1PortfoliosIdLotsArgs, options?: CreateApiV1PortfoliosIdLotsOptions) => { const {baseUrl = "https://api.equibles.com", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set('authorization', `Bearer ${ApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/portfolios/${encodeURIComponent(String(args.id))}/lots${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(portfolioLotResponse, await res.json()) };