import {z} from 'zod' export type GetApiTradesFromDateToDatePageNumberArgs = {'access-token': string, 'from-date': string, 'to-date': string, 'page-number': string}; export type GetApiTradesFromDateToDatePageNumberOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const tradeHistoryResponseModel = z.object({dhanClientId: z.string().optional(), orderId: z.string().optional(), exchangeOrderId: z.string().optional(), exchangeTradeId: z.string().optional(), transactionType: z.enum(["BUY", "SELL"]).optional(), exchangeSegment: z.enum(["NSE_EQ", "NSE_FNO", "BSE_EQ", "BSE_FNO", "MCX_COMM"]).optional(), productType: z.enum(["CNC", "INTRADAY", "MARGIN", "MTF", "CO", "BO"]).optional(), orderType: z.enum(["LIMIT", "MARKET", "STOP_LOSS", "STOP_LOSS_MARKET"]).optional(), customSymbol: z.string().optional(), securityId: z.string().optional(), tradedQuantity: z.number().int().optional(), tradedPrice: z.number().optional(), isin: z.string().optional(), instrument: z.string().optional(), sebiTax: z.number().optional(), stt: z.number().optional(), brokerageCharges: z.number().optional(), serviceTax: z.number().optional(), exchangeTransactionCharges: z.number().optional(), stampDuty: z.number().optional(), createTime: z.string().optional(), updateTime: z.string().optional(), exchangeTime: z.string().optional(), drvExpiryDate: z.string().optional(), drvOptionType: z.enum(["CALL", "PUT", "NA"]).optional(), drvStrikePrice: z.number().optional()}); export const getApiTradesFromDateToDatePageNumberResponse = z.array(tradeHistoryResponseModel); 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 trade history * * GET /trades/{from-date}/{to-date}/{page-number} */ export const getApiTradesFromDateToDatePageNumber = async (args: GetApiTradesFromDateToDatePageNumberArgs, options?: GetApiTradesFromDateToDatePageNumberOptions) => { const {baseUrl = "https://api.dhan.co/v2", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['access-token'] != null) headers.set("access-token", String(args['access-token'])) const url = `${baseUrl.replace(/\/+$/, '')}/trades/${encodeURIComponent(String(args['from-date']))}/${encodeURIComponent(String(args['to-date']))}/${encodeURIComponent(String(args['page-number']))}${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(getApiTradesFromDateToDatePageNumberResponse, await res.json()) };