@discomedia/utils 1.0.76 → 1.0.78
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index-frontend.cjs +2024 -15229
- package/dist/index-frontend.cjs.map +7 -1
- package/dist/index-frontend.mjs +1985 -15219
- package/dist/index-frontend.mjs.map +7 -1
- package/dist/index.cjs +5368 -24346
- package/dist/index.cjs.map +7 -1
- package/dist/index.mjs +5326 -24333
- package/dist/index.mjs.map +7 -1
- package/dist/package.json +10 -11
- package/dist/test.mjs +1977 -0
- package/dist/test.mjs.map +7 -0
- package/dist/types/alpaca-market-data-api.d.ts.map +1 -1
- package/dist/types/alpaca-trading-api.d.ts.map +1 -1
- package/dist/types/index-frontend.d.ts +2 -1
- package/dist/types/index-frontend.d.ts.map +1 -1
- package/dist/types/index.d.ts +7 -4
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/llm-config.d.ts +4 -2
- package/dist/types/llm-config.d.ts.map +1 -1
- package/dist/types/llm-deepseek.d.ts.map +1 -1
- package/dist/types/llm-images.d.ts.map +1 -1
- package/dist/types/llm-openai.d.ts +7 -4
- package/dist/types/llm-openai.d.ts.map +1 -1
- package/dist/types/llm-openrouter.d.ts.map +1 -1
- package/dist/types/market-time.d.ts +1 -1
- package/dist/types/market-time.d.ts.map +1 -1
- package/dist/types/misc-utils.d.ts +1 -1
- package/dist/types/misc-utils.d.ts.map +1 -1
- package/dist/types/performance-timer.d.ts.map +1 -1
- package/dist/types/types/llm-types.d.ts +8 -5
- package/dist/types/types/llm-types.d.ts.map +1 -1
- package/package.json +10 -11
- package/dist/test.js +0 -17459
- package/dist/test.js.map +0 -1
- package/dist/types-frontend/alpaca-market-data-api.d.ts +0 -451
- package/dist/types-frontend/alpaca-market-data-api.d.ts.map +0 -1
- package/dist/types-frontend/alpaca-trading-api.d.ts +0 -407
- package/dist/types-frontend/alpaca-trading-api.d.ts.map +0 -1
- package/dist/types-frontend/format-tools.d.ts +0 -46
- package/dist/types-frontend/format-tools.d.ts.map +0 -1
- package/dist/types-frontend/index-frontend.d.ts +0 -18
- package/dist/types-frontend/index-frontend.d.ts.map +0 -1
- package/dist/types-frontend/index.d.ts +0 -59
- package/dist/types-frontend/index.d.ts.map +0 -1
- package/dist/types-frontend/json-tools.d.ts +0 -31
- package/dist/types-frontend/json-tools.d.ts.map +0 -1
- package/dist/types-frontend/llm-config.d.ts +0 -51
- package/dist/types-frontend/llm-config.d.ts.map +0 -1
- package/dist/types-frontend/llm-deepseek.d.ts +0 -12
- package/dist/types-frontend/llm-deepseek.d.ts.map +0 -1
- package/dist/types-frontend/llm-images.d.ts +0 -52
- package/dist/types-frontend/llm-images.d.ts.map +0 -1
- package/dist/types-frontend/llm-openai.d.ts +0 -79
- package/dist/types-frontend/llm-openai.d.ts.map +0 -1
- package/dist/types-frontend/llm-openrouter.d.ts +0 -28
- package/dist/types-frontend/llm-openrouter.d.ts.map +0 -1
- package/dist/types-frontend/llm-utils.d.ts +0 -16
- package/dist/types-frontend/llm-utils.d.ts.map +0 -1
- package/dist/types-frontend/logging.d.ts +0 -12
- package/dist/types-frontend/logging.d.ts.map +0 -1
- package/dist/types-frontend/market-hours.d.ts +0 -24
- package/dist/types-frontend/market-hours.d.ts.map +0 -1
- package/dist/types-frontend/market-time.d.ts +0 -270
- package/dist/types-frontend/market-time.d.ts.map +0 -1
- package/dist/types-frontend/misc-utils.d.ts +0 -43
- package/dist/types-frontend/misc-utils.d.ts.map +0 -1
- package/dist/types-frontend/performance-timer.d.ts +0 -73
- package/dist/types-frontend/performance-timer.d.ts.map +0 -1
- package/dist/types-frontend/test.d.ts +0 -2
- package/dist/types-frontend/test.d.ts.map +0 -1
- package/dist/types-frontend/testing/market-time-refactor-test.d.ts +0 -1
- package/dist/types-frontend/testing/market-time-refactor-test.d.ts.map +0 -1
- package/dist/types-frontend/types/alpaca-crypto-pairs.d.ts +0 -11
- package/dist/types-frontend/types/alpaca-crypto-pairs.d.ts.map +0 -1
- package/dist/types-frontend/types/alpaca-types.d.ts +0 -1181
- package/dist/types-frontend/types/alpaca-types.d.ts.map +0 -1
- package/dist/types-frontend/types/index.d.ts +0 -6
- package/dist/types-frontend/types/index.d.ts.map +0 -1
- package/dist/types-frontend/types/llm-types.d.ts +0 -174
- package/dist/types-frontend/types/llm-types.d.ts.map +0 -1
- package/dist/types-frontend/types/logging-types.d.ts +0 -10
- package/dist/types-frontend/types/logging-types.d.ts.map +0 -1
- package/dist/types-frontend/types/market-time-types.d.ts +0 -64
- package/dist/types-frontend/types/market-time-types.d.ts.map +0 -1
- package/dist/types-frontend/types/ta-types.d.ts +0 -89
- package/dist/types-frontend/types/ta-types.d.ts.map +0 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/logging.ts", "../src/market-hours.ts", "../src/market-time.ts", "../src/alpaca-market-data-api.ts", "../src/alpaca-trading-api.ts", "../src/index.ts", "../src/types/llm-types.ts", "../src/llm-openai.ts", "../src/llm-config.ts", "../src/json-tools.ts", "../src/llm-images.ts", "../src/llm-deepseek.ts", "../src/llm-openrouter.ts", "../src/test.ts"],
|
|
4
|
+
"sourcesContent": ["import { LogOptions } from './types/logging-types';\n\n/**\n * Logs a message to the console.\n * @param message The message to log.\n * @param options Optional options.\n * @param options.source The source of the message.\n * @param options.type The type of message to log.\n * @param options.symbol The trading symbol associated with this log.\n * @param options.account The account associated with this log.\n */\nexport function log(message: string, options: LogOptions = { source: 'App', type: 'info' }): void {\n // Format the timestamp\n const date = new Date();\n const timestamp = date.toLocaleString('en-US', { timeZone: 'America/New_York' });\n const account = options?.account;\n const symbol = options?.symbol;\n\n // Build the log message\n const logMessage = `[${timestamp}]${options?.source ? ` [${options.source}] ` : ''}${\n account ? ` [${account}] ` : ''\n }${symbol ? ` [${symbol}] ` : ''}${message}`;\n\n // Use appropriate console method based on type\n if (options?.type === 'error') {\n console.error(logMessage);\n } else if (options?.type === 'warn') {\n console.warn(logMessage);\n } else {\n console.log(logMessage);\n }\n}\n", "// market-hours.ts\n\nexport interface HolidayDetails {\n date: string;\n}\n\nexport interface MarketHolidaysForYear {\n [holidayName: string]: HolidayDetails;\n}\n\nexport interface MarketHolidays {\n [year: number]: MarketHolidaysForYear;\n}\n\nexport interface EarlyCloseDetails {\n date: string;\n time: string;\n optionsTime: string;\n notes: string;\n}\n\nexport interface EarlyClosesForYear {\n [date: string]: EarlyCloseDetails;\n}\n\nexport interface MarketEarlyCloses {\n [year: number]: EarlyClosesForYear;\n}\n\nexport const marketHolidays: MarketHolidays = {\n 2024: {\n \"New Year's Day\": { date: '2024-01-01' },\n 'Martin Luther King, Jr. Day': { date: '2024-01-15' },\n \"Washington's Birthday\": { date: '2024-02-19' },\n 'Good Friday': { date: '2024-03-29' },\n 'Memorial Day': { date: '2024-05-27' },\n 'Juneteenth National Independence Day': { date: '2024-06-19' },\n 'Independence Day': { date: '2024-07-04' },\n 'Labor Day': { date: '2024-09-02' },\n 'Thanksgiving Day': { date: '2024-11-28' },\n 'Christmas Day': { date: '2024-12-25' },\n },\n 2025: {\n \"New Year's Day\": { date: '2025-01-01' },\n 'Jimmy Carter Memorial Day': { date: '2025-01-09' },\n 'Martin Luther King, Jr. Day': { date: '2025-01-20' },\n \"Washington's Birthday\": { date: '2025-02-17' },\n 'Good Friday': { date: '2025-04-18' },\n 'Memorial Day': { date: '2025-05-26' },\n 'Juneteenth National Independence Day': { date: '2025-06-19' },\n 'Independence Day': { date: '2025-07-04' },\n 'Labor Day': { date: '2025-09-01' },\n 'Thanksgiving Day': { date: '2025-11-27' },\n 'Christmas Day': { date: '2025-12-25' },\n },\n 2026: {\n \"New Year's Day\": { date: '2026-01-01' },\n 'Martin Luther King, Jr. Day': { date: '2026-01-19' },\n \"Washington's Birthday\": { date: '2026-02-16' },\n 'Good Friday': { date: '2026-04-03' },\n 'Memorial Day': { date: '2026-05-25' },\n 'Juneteenth National Independence Day': { date: '2026-06-19' },\n 'Independence Day': { date: '2026-07-03' },\n 'Labor Day': { date: '2026-09-07' },\n 'Thanksgiving Day': { date: '2026-11-26' },\n 'Christmas Day': { date: '2026-12-25' },\n },\n};\n\nexport const marketEarlyCloses: MarketEarlyCloses = {\n 2024: {\n '2024-07-03': {\n date: '2024-07-03',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Wednesday, July 3, 2024 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2024-11-29': {\n date: '2024-11-29',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Friday, November 29, 2024 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2024-12-24': {\n date: '2024-12-24',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Tuesday, December 24, 2024 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n },\n 2025: {\n '2025-07-03': {\n date: '2025-07-03',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Thursday, July 3, 2025 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2025-11-28': {\n date: '2025-11-28',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Friday, November 28, 2025 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2025-12-24': {\n date: '2025-12-24',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Wednesday, December 24, 2025 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n },\n 2026: {\n '2026-07-02': {\n date: '2026-07-02',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Independence Day observed, market closes early at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2026-11-27': {\n date: '2026-11-27',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Friday, November 27, 2026 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2026-12-24': {\n date: '2026-12-24',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Thursday, December 24, 2026 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n },\n};\n", "import { log as baseLog } from './logging';\nimport { LogOptions } from './types/logging-types';\nimport {\n Period,\n IntradayReporting,\n PeriodDates,\n MarketTimeParams,\n OutputFormat,\n MarketOpenCloseResult,\n MarketStatus,\n MarketTimesConfig,\n TradingDaysBackOptions,\n} from './types/market-time-types';\nimport { marketHolidays, marketEarlyCloses } from './market-hours';\n\n// Constants for NY market times (Eastern Time)\nexport const MARKET_CONFIG = {\n TIMEZONE: 'America/New_York',\n UTC_OFFSET_STANDARD: -5, // EST\n UTC_OFFSET_DST: -4, // EDT\n TIMES: {\n EXTENDED_START: { hour: 4, minute: 0 },\n MARKET_OPEN: { hour: 9, minute: 30 },\n EARLY_MARKET_END: { hour: 10, minute: 0 },\n MARKET_CLOSE: { hour: 16, minute: 0 },\n EARLY_CLOSE: { hour: 13, minute: 0 },\n EXTENDED_END: { hour: 20, minute: 0 },\n EARLY_EXTENDED_END: { hour: 17, minute: 0 },\n },\n} as const;\n\nconst log = (message: string, options: LogOptions = { type: 'info' }) => {\n baseLog(message, { ...options, source: 'MarketTime' });\n};\n\n// Helper: Get NY offset for a given UTC date (DST rules for US)\n/**\n * Returns the NY timezone offset (in hours) for a given UTC date, accounting for US DST rules.\n * @param date - UTC date\n * @returns offset in hours (-5 for EST, -4 for EDT)\n */\nfunction getNYOffset(date: Date): number {\n // US DST starts 2nd Sunday in March, ends 1st Sunday in November\n const year = date.getUTCFullYear();\n const dstStart = getNthWeekdayOfMonth(year, 3, 0, 2); // March, Sunday, 2nd\n const dstEnd = getNthWeekdayOfMonth(year, 11, 0, 1); // November, Sunday, 1st\n const utcTime = date.getTime();\n\n if (utcTime >= dstStart.getTime() && utcTime < dstEnd.getTime()) {\n return MARKET_CONFIG.UTC_OFFSET_DST;\n }\n return MARKET_CONFIG.UTC_OFFSET_STANDARD;\n}\n\n// Helper: Get nth weekday of month in UTC\n/**\n * Returns the nth weekday of a given month in UTC.\n * @param year - Year\n * @param month - 1-based month (e.g. March = 3)\n * @param weekday - 0=Sunday, 1=Monday, ...\n * @param n - nth occurrence\n * @returns Date object for the nth weekday\n */\nfunction getNthWeekdayOfMonth(year: number, month: number, weekday: number, n: number): Date {\n // month: 1-based (March = 3), weekday: 0=Sunday\n const firstDay = new Date(Date.UTC(year, month - 1, 1));\n let count = 0;\n for (let d = 1; d <= 31; d++) {\n const date = new Date(Date.UTC(year, month - 1, d));\n if (date.getUTCMonth() !== month - 1) break;\n if (date.getUTCDay() === weekday) {\n count++;\n if (count === n) return date;\n }\n }\n // fallback: last day of month\n return new Date(Date.UTC(year, month - 1, 28));\n}\n\n// Helper: Convert UTC date to NY time (returns new Date object)\n/**\n * Converts a UTC date to NY time (returns a new Date object).\n * @param date - UTC date\n * @returns Date object in NY time\n */\nfunction toNYTime(date: Date): Date {\n const offset = getNYOffset(date);\n // NY offset in hours\n const utcMillis = date.getTime();\n const nyMillis = utcMillis + offset * 60 * 60 * 1000;\n return new Date(nyMillis);\n}\n\n// Helper: Convert NY time to UTC (returns new Date object)\n/**\n * Converts a NY time date to UTC (returns a new Date object).\n * @param date - NY time date\n * @returns Date object in UTC\n */\nfunction fromNYTime(date: Date): Date {\n const offset = getNYOffset(date);\n const nyMillis = date.getTime();\n const utcMillis = nyMillis - offset * 60 * 60 * 1000;\n return new Date(utcMillis);\n}\n\n// Helper: Format date in ISO, unix, etc.\n/**\n * Formats a date in ISO, unix-seconds, or unix-ms format.\n * @param date - Date object\n * @param outputFormat - Output format ('iso', 'unix-seconds', 'unix-ms')\n * @returns Formatted date string or number\n */\nfunction formatDate(date: Date, outputFormat: OutputFormat = 'iso'): string | number {\n switch (outputFormat) {\n case 'unix-seconds':\n return Math.floor(date.getTime() / 1000);\n case 'unix-ms':\n return date.getTime();\n case 'iso':\n default:\n return date.toISOString();\n }\n}\n\n// Helper: Format date in NY locale string\n/**\n * Formats a date in NY locale string.\n * @param date - Date object\n * @returns NY locale string\n */\nfunction formatNYLocale(date: Date): string {\n return date.toLocaleString('en-US', { timeZone: 'America/New_York' });\n}\n\n// Market calendar logic\n/**\n * Market calendar logic for holidays, weekends, and market days.\n */\nclass MarketCalendar {\n /**\n * Checks if a date is a weekend in NY time.\n * @param date - Date object\n * @returns true if weekend, false otherwise\n */\n isWeekend(date: Date): boolean {\n const day = toNYTime(date).getUTCDay();\n return day === 0 || day === 6;\n }\n\n /**\n * Checks if a date is a market holiday in NY time.\n * @param date - Date object\n * @returns true if holiday, false otherwise\n */\n isHoliday(date: Date): boolean {\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth() + 1;\n const day = nyDate.getUTCDate();\n const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;\n const yearHolidays = marketHolidays[year];\n if (!yearHolidays) return false;\n return Object.values(yearHolidays).some((holiday) => holiday.date === formattedDate);\n }\n\n /**\n * Checks if a date is an early close day in NY time.\n * @param date - Date object\n * @returns true if early close, false otherwise\n */\n isEarlyCloseDay(date: Date): boolean {\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth() + 1;\n const day = nyDate.getUTCDate();\n const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;\n const yearEarlyCloses = marketEarlyCloses[year];\n return yearEarlyCloses && yearEarlyCloses[formattedDate] !== undefined;\n }\n\n /**\n * Gets the early close time (in minutes from midnight) for a given date.\n * @param date - Date object\n * @returns minutes from midnight or null\n */\n getEarlyCloseTime(date: Date): number | null {\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth() + 1;\n const day = nyDate.getUTCDate();\n const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;\n const yearEarlyCloses = marketEarlyCloses[year];\n if (yearEarlyCloses && yearEarlyCloses[formattedDate]) {\n const [hours, minutes] = yearEarlyCloses[formattedDate].time.split(':').map(Number);\n return hours * 60 + minutes;\n }\n return null;\n }\n\n /**\n * Checks if a date is a market day (not weekend or holiday).\n * @param date - Date object\n * @returns true if market day, false otherwise\n */\n isMarketDay(date: Date): boolean {\n return !this.isWeekend(date) && !this.isHoliday(date);\n }\n\n /**\n * Gets the next market day after the given date.\n * @param date - Date object\n * @returns Date object for next market day\n */\n getNextMarketDay(date: Date): Date {\n let nextDay = new Date(date.getTime() + 24 * 60 * 60 * 1000);\n while (!this.isMarketDay(nextDay)) {\n nextDay = new Date(nextDay.getTime() + 24 * 60 * 60 * 1000);\n }\n return nextDay;\n }\n\n /**\n * Gets the previous market day before the given date.\n * @param date - Date object\n * @returns Date object for previous market day\n */\n getPreviousMarketDay(date: Date): Date {\n let prevDay = new Date(date.getTime() - 24 * 60 * 60 * 1000);\n while (!this.isMarketDay(prevDay)) {\n prevDay = new Date(prevDay.getTime() - 24 * 60 * 60 * 1000);\n }\n return prevDay;\n }\n}\n\n// Market open/close times\n/**\n * Returns market open/close times for a given date, including extended and early closes.\n * @param date - Date object\n * @returns MarketOpenCloseResult\n */\nfunction getMarketTimes(date: Date): MarketOpenCloseResult {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(date);\n if (!calendar.isMarketDay(date)) {\n return {\n marketOpen: false,\n open: null,\n close: null,\n openExt: null,\n closeExt: null,\n };\n }\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth();\n const day = nyDate.getUTCDate();\n\n // Helper to build NY time for a given hour/minute\n function buildNYTime(hour: number, minute: number): Date {\n const d = new Date(Date.UTC(year, month, day, hour, minute, 0, 0));\n return fromNYTime(d);\n }\n\n let open = buildNYTime(MARKET_CONFIG.TIMES.MARKET_OPEN.hour, MARKET_CONFIG.TIMES.MARKET_OPEN.minute);\n let close = buildNYTime(MARKET_CONFIG.TIMES.MARKET_CLOSE.hour, MARKET_CONFIG.TIMES.MARKET_CLOSE.minute);\n let openExt = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_START.hour, MARKET_CONFIG.TIMES.EXTENDED_START.minute);\n let closeExt = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_END.hour, MARKET_CONFIG.TIMES.EXTENDED_END.minute);\n\n if (calendar.isEarlyCloseDay(date)) {\n close = buildNYTime(MARKET_CONFIG.TIMES.EARLY_CLOSE.hour, MARKET_CONFIG.TIMES.EARLY_CLOSE.minute);\n closeExt = buildNYTime(MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour, MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute);\n }\n\n return {\n marketOpen: true,\n open,\n close,\n openExt,\n closeExt,\n };\n}\n\n// Is within market hours\n/**\n * Checks if a date/time is within market hours, extended hours, or continuous.\n * @param date - Date object\n * @param intradayReporting - 'market_hours', 'extended_hours', or 'continuous'\n * @returns true if within hours, false otherwise\n */\nexport function isWithinMarketHours(date: Date, intradayReporting: IntradayReporting = 'market_hours'): boolean {\n const calendar = new MarketCalendar();\n if (!calendar.isMarketDay(date)) return false;\n const nyDate = toNYTime(date);\n const minutes = nyDate.getUTCHours() * 60 + nyDate.getUTCMinutes();\n\n switch (intradayReporting) {\n case 'extended_hours': {\n let endMinutes = MARKET_CONFIG.TIMES.EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_END.minute;\n if (calendar.isEarlyCloseDay(date)) {\n endMinutes = MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute;\n }\n const startMinutes = MARKET_CONFIG.TIMES.EXTENDED_START.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_START.minute;\n return minutes >= startMinutes && minutes <= endMinutes;\n }\n case 'continuous':\n return true;\n default: {\n let endMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n if (calendar.isEarlyCloseDay(date)) {\n endMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n }\n const startMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n return minutes >= startMinutes && minutes <= endMinutes;\n }\n }\n}\n\n// Get last full trading date\n/**\n * Returns the last full trading date (market close) for a given date.\n * @param currentDate - Date object (default: now)\n * @returns Date object for last full trading date\n */\nfunction getLastFullTradingDateImpl(currentDate: Date = new Date()): Date {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(currentDate);\n const minutes = nyDate.getUTCHours() * 60 + nyDate.getUTCMinutes();\n const marketOpenMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n let marketCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n if (calendar.isEarlyCloseDay(currentDate)) {\n marketCloseMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n }\n\n // If not a market day, or before open, or during market hours, return previous market day's close\n if (\n !calendar.isMarketDay(currentDate) ||\n minutes < marketOpenMinutes ||\n (minutes >= marketOpenMinutes && minutes < marketCloseMinutes)\n ) {\n const prevMarketDay = calendar.getPreviousMarketDay(currentDate);\n let prevCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n if (calendar.isEarlyCloseDay(prevMarketDay)) {\n prevCloseMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n }\n const prevNYDate = toNYTime(prevMarketDay);\n const year = prevNYDate.getUTCFullYear();\n const month = prevNYDate.getUTCMonth();\n const day = prevNYDate.getUTCDate();\n const closeHour = Math.floor(prevCloseMinutes / 60);\n const closeMinute = prevCloseMinutes % 60;\n return fromNYTime(new Date(Date.UTC(year, month, day, closeHour, closeMinute, 0, 0)));\n }\n\n // After market close or after extended hours, return today's close\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth();\n const day = nyDate.getUTCDate();\n const closeHour = Math.floor(marketCloseMinutes / 60);\n const closeMinute = marketCloseMinutes % 60;\n return fromNYTime(new Date(Date.UTC(year, month, day, closeHour, closeMinute, 0, 0)));\n}\n\n// Get day boundaries\n/**\n * Returns the start and end boundaries for a market day, extended hours, or continuous.\n * @param date - Date object\n * @param intradayReporting - 'market_hours', 'extended_hours', or 'continuous'\n * @returns Object with start and end Date\n */\nfunction getDayBoundaries(\n date: Date,\n intradayReporting: IntradayReporting = 'market_hours'\n): { start: Date; end: Date } {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth();\n const day = nyDate.getUTCDate();\n\n function buildNYTime(hour: number, minute: number, sec = 0, ms = 0): Date {\n const d = new Date(Date.UTC(year, month, day, hour, minute, sec, ms));\n return fromNYTime(d);\n }\n\n let start: Date;\n let end: Date;\n\n switch (intradayReporting) {\n case 'extended_hours':\n start = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_START.hour, MARKET_CONFIG.TIMES.EXTENDED_START.minute, 0, 0);\n end = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_END.hour, MARKET_CONFIG.TIMES.EXTENDED_END.minute, 59, 999);\n if (calendar.isEarlyCloseDay(date)) {\n end = buildNYTime(\n MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour,\n MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute,\n 59,\n 999\n );\n }\n break;\n case 'continuous':\n start = new Date(Date.UTC(year, month, day, 0, 0, 0, 0));\n end = new Date(Date.UTC(year, month, day, 23, 59, 59, 999));\n break;\n default:\n start = buildNYTime(MARKET_CONFIG.TIMES.MARKET_OPEN.hour, MARKET_CONFIG.TIMES.MARKET_OPEN.minute, 0, 0);\n end = buildNYTime(MARKET_CONFIG.TIMES.MARKET_CLOSE.hour, MARKET_CONFIG.TIMES.MARKET_CLOSE.minute, 59, 999);\n if (calendar.isEarlyCloseDay(date)) {\n end = buildNYTime(MARKET_CONFIG.TIMES.EARLY_CLOSE.hour, MARKET_CONFIG.TIMES.EARLY_CLOSE.minute, 59, 999);\n }\n break;\n }\n return { start, end };\n}\n\n// Period calculator\n/**\n * Calculates the start date for a given period ending at endDate.\n * @param endDate - Date object\n * @param period - Period string\n * @returns Date object for period start\n */\nfunction calculatePeriodStartDate(endDate: Date, period: Period): Date {\n const calendar = new MarketCalendar();\n let startDate: Date;\n switch (period) {\n case 'YTD':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), 0, 1));\n break;\n case '1D':\n startDate = calendar.getPreviousMarketDay(endDate);\n break;\n case '3D':\n startDate = new Date(endDate.getTime() - 3 * 24 * 60 * 60 * 1000);\n break;\n case '1W':\n startDate = new Date(endDate.getTime() - 7 * 24 * 60 * 60 * 1000);\n break;\n case '2W':\n startDate = new Date(endDate.getTime() - 14 * 24 * 60 * 60 * 1000);\n break;\n case '1M':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), endDate.getUTCMonth() - 1, endDate.getUTCDate()));\n break;\n case '3M':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), endDate.getUTCMonth() - 3, endDate.getUTCDate()));\n break;\n case '6M':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), endDate.getUTCMonth() - 6, endDate.getUTCDate()));\n break;\n case '1Y':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear() - 1, endDate.getUTCMonth(), endDate.getUTCDate()));\n break;\n default:\n throw new Error(`Invalid period: ${period}`);\n }\n // Ensure start date is a market day\n while (!calendar.isMarketDay(startDate)) {\n startDate = calendar.getNextMarketDay(startDate);\n }\n return startDate;\n}\n\n// Get market time period\n/**\n * Returns the start and end dates for a market time period.\n * @param params - MarketTimeParams\n * @returns PeriodDates object\n */\nexport function getMarketTimePeriod(params: MarketTimeParams): PeriodDates {\n const { period, end = new Date(), intraday_reporting = 'market_hours', outputFormat = 'iso' } = params;\n\n if (!period) throw new Error('Period is required');\n const calendar = new MarketCalendar();\n\n const nyEndDate = toNYTime(end);\n let endDate: Date;\n const isCurrentMarketDay = calendar.isMarketDay(end);\n const isWithinHours = isWithinMarketHours(end, intraday_reporting);\n const minutes = nyEndDate.getUTCHours() * 60 + nyEndDate.getUTCMinutes();\n const marketStartMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n\n if (isCurrentMarketDay) {\n if (minutes < marketStartMinutes) {\n // Before market open - use previous day's close\n const lastMarketDay = calendar.getPreviousMarketDay(end);\n const { end: dayEnd } = getDayBoundaries(lastMarketDay, intraday_reporting);\n endDate = dayEnd;\n } else if (isWithinHours) {\n // During market hours - use current time\n endDate = end;\n } else {\n // After market close - use today's close\n const { end: dayEnd } = getDayBoundaries(end, intraday_reporting);\n endDate = dayEnd;\n }\n } else {\n // Not a market day - use previous market day's close\n const lastMarketDay = calendar.getPreviousMarketDay(end);\n const { end: dayEnd } = getDayBoundaries(lastMarketDay, intraday_reporting);\n endDate = dayEnd;\n }\n\n // Calculate start date\n const periodStartDate = calculatePeriodStartDate(endDate, period);\n const { start: dayStart } = getDayBoundaries(periodStartDate, intraday_reporting);\n\n if (endDate.getTime() < dayStart.getTime()) {\n throw new Error('Start date cannot be after end date');\n }\n\n return {\n start: formatDate(dayStart, outputFormat),\n end: formatDate(endDate, outputFormat),\n };\n}\n\n// Market status\n/**\n * Returns the current market status for a given date.\n * @param date - Date object (default: now)\n * @returns MarketStatus object\n */\nfunction getMarketStatusImpl(date: Date = new Date()): MarketStatus {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(date);\n const minutes = nyDate.getUTCHours() * 60 + nyDate.getUTCMinutes();\n const isMarketDay = calendar.isMarketDay(date);\n const isEarlyCloseDay = calendar.isEarlyCloseDay(date);\n\n const extendedStartMinutes = MARKET_CONFIG.TIMES.EXTENDED_START.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_START.minute;\n const marketStartMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n const earlyMarketEndMinutes =\n MARKET_CONFIG.TIMES.EARLY_MARKET_END.hour * 60 + MARKET_CONFIG.TIMES.EARLY_MARKET_END.minute;\n\n let marketCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n let extendedEndMinutes = MARKET_CONFIG.TIMES.EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_END.minute;\n if (isEarlyCloseDay) {\n marketCloseMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n extendedEndMinutes =\n MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute;\n }\n\n let status: MarketStatus['status'];\n let nextStatus: MarketStatus['nextStatus'];\n let nextStatusTime: Date;\n let marketPeriod: MarketStatus['marketPeriod'];\n\n if (!isMarketDay) {\n status = 'closed';\n nextStatus = 'extended hours';\n marketPeriod = 'closed';\n const nextMarketDay = calendar.getNextMarketDay(date);\n nextStatusTime = getDayBoundaries(nextMarketDay, 'extended_hours').start;\n } else if (minutes < extendedStartMinutes) {\n status = 'closed';\n nextStatus = 'extended hours';\n marketPeriod = 'closed';\n nextStatusTime = getDayBoundaries(date, 'extended_hours').start;\n } else if (minutes < marketStartMinutes) {\n status = 'extended hours';\n nextStatus = 'open';\n marketPeriod = 'preMarket';\n nextStatusTime = getDayBoundaries(date, 'market_hours').start;\n } else if (minutes < marketCloseMinutes) {\n status = 'open';\n nextStatus = 'extended hours';\n marketPeriod = minutes < earlyMarketEndMinutes ? 'earlyMarket' : 'regularMarket';\n nextStatusTime = getDayBoundaries(date, 'market_hours').end;\n } else if (minutes < extendedEndMinutes) {\n status = 'extended hours';\n nextStatus = 'closed';\n marketPeriod = 'afterMarket';\n nextStatusTime = getDayBoundaries(date, 'extended_hours').end;\n } else {\n status = 'closed';\n nextStatus = 'extended hours';\n marketPeriod = 'closed';\n const nextMarketDay = calendar.getNextMarketDay(date);\n nextStatusTime = getDayBoundaries(nextMarketDay, 'extended_hours').start;\n }\n\n // I think using nyDate here may be wrong - should use current time? i.e. date.getTime()\n const nextStatusTimeDifference = nextStatusTime.getTime() - date.getTime();\n\n return {\n time: date,\n timeString: formatNYLocale(nyDate),\n status,\n nextStatus,\n marketPeriod,\n nextStatusTime,\n nextStatusTimeDifference,\n nextStatusTimeString: formatNYLocale(nextStatusTime),\n };\n}\n\n// API exports\n/**\n * Returns market open/close times for a given date.\n * @param options - { date?: Date }\n * @returns MarketOpenCloseResult\n */\nexport function getMarketOpenClose(options: { date?: Date } = {}): MarketOpenCloseResult {\n const { date = new Date() } = options;\n return getMarketTimes(date);\n}\n\n/**\n * Returns the start and end dates for a market time period as Date objects.\n * @param params - MarketTimeParams\n * @returns Object with start and end Date\n */\nexport function getStartAndEndDates(params: MarketTimeParams = {}): { start: Date; end: Date } {\n const { start, end } = getMarketTimePeriod(params);\n return {\n start: typeof start === 'string' || typeof start === 'number' ? new Date(start) : start,\n end: typeof end === 'string' || typeof end === 'number' ? new Date(end) : end,\n };\n}\n\n/**\n * Returns the last full trading date as a Date object.\n */\n/**\n * Returns the last full trading date as a Date object.\n * @param currentDate - Date object (default: now)\n * @returns Date object for last full trading date\n */\nexport function getLastFullTradingDate(currentDate: Date = new Date()): Date {\n return getLastFullTradingDateImpl(currentDate);\n}\n\n/**\n * Returns the last full trading date and formatted YYYYMMDD string.\n */\n/**\n * Returns the last full trading date and formatted YYYY-MM-DD string.\n * @param currentDate - Date object (default: now)\n * @returns Object with date and YYYYMMDD string\n */\nexport function getLastFullTradingDateInfo(currentDate: Date = new Date()): { date: Date; YYYYMMDD: string } {\n const date = getLastFullTradingDateImpl(currentDate);\n return {\n date,\n YYYYMMDD: `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}-${String(\n date.getUTCDate()\n ).padStart(2, '0')}`,\n };\n}\n\n/**\n * Returns the next market day after the reference date.\n * @param referenceDate - Date object (default: now)\n * @returns Object with date, yyyymmdd string, and ISO string\n */\nexport function getNextMarketDay({ referenceDate }: { referenceDate?: Date } = {}): {\n date: Date;\n yyyymmdd: string;\n dateISOString: string;\n} {\n const calendar = new MarketCalendar();\n const startDate = referenceDate ?? new Date();\n\n // Find the next trading day (UTC Date object)\n const nextDate = calendar.getNextMarketDay(startDate);\n\n // Convert to NY time before extracting Y-M-D parts\n const nyNext = toNYTime(nextDate);\n const yyyymmdd = `${nyNext.getUTCFullYear()}-${String(nyNext.getUTCMonth() + 1).padStart(2, '0')}-${String(\n nyNext.getUTCDate()\n ).padStart(2, '0')}`;\n\n return {\n date: nextDate, // raw Date, unchanged\n yyyymmdd, // correct trading date string\n dateISOString: nextDate.toISOString(),\n };\n}\n\n/**\n * Returns the previous market day before the reference date.\n * @param referenceDate - Date object (default: now)\n * @returns Object with date, yyyymmdd string, and ISO string\n */\nexport function getPreviousMarketDay({ referenceDate }: { referenceDate?: Date } = {}) {\n const calendar = new MarketCalendar();\n const startDate = referenceDate || new Date();\n const prevDate = calendar.getPreviousMarketDay(startDate);\n\n // convert to NY time first\n const nyPrev = toNYTime(prevDate); // \u2190 already in this file\n const yyyymmdd = `${nyPrev.getUTCFullYear()}-${String(nyPrev.getUTCMonth() + 1).padStart(2, '0')}-${String(\n nyPrev.getUTCDate()\n ).padStart(2, '0')}`;\n\n return {\n date: prevDate,\n yyyymmdd,\n dateISOString: prevDate.toISOString(),\n };\n}\n\n/**\n * Returns the trading date for a given time. Note: Just trims the date string; does not validate if the date is a market day.\n * @param time - a string, number (unix timestamp), or Date object representing the time\n * @returns the trading date as a string in YYYY-MM-DD format\n */\n/**\n * Returns the trading date for a given time in YYYY-MM-DD format (NY time).\n * @param time - string, number, or Date\n * @returns trading date string\n */\nexport function getTradingDate(time: string | number | Date): string {\n const date = typeof time === 'number' ? new Date(time) : typeof time === 'string' ? new Date(time) : time;\n const nyDate = toNYTime(date);\n return `${nyDate.getUTCFullYear()}-${String(nyDate.getUTCMonth() + 1).padStart(2, '0')}-${String(\n nyDate.getUTCDate()\n ).padStart(2, '0')}`;\n}\n\n/**\n * Returns the NY timezone offset string for a given date.\n * @param date - Date object (default: now)\n * @returns '-04:00' for EDT, '-05:00' for EST\n */\nexport function getNYTimeZone(date?: Date): '-04:00' | '-05:00' {\n const offset = getNYOffset(date || new Date());\n return offset === -4 ? '-04:00' : '-05:00';\n}\n\n/**\n * Returns the regular market open and close Date objects for a given trading day string in the\n * America/New_York timezone (NYSE/NASDAQ calendar).\n *\n * This helper is convenient when you have a calendar date like '2025-10-03' and want the precise\n * open and close Date values for that day. It internally:\n * - Determines the NY offset for the day using `getNYTimeZone()`.\n * - Anchors a noon-time Date on that day in NY time to avoid DST edge cases.\n * - Verifies the day is a market day via `isMarketDay()`.\n * - Fetches the open/close times via `getMarketOpenClose()`.\n *\n * Throws if the provided day is not a market day or if open/close times are unavailable.\n *\n * See also:\n * - `getNYTimeZone(date?: Date)`\n * - `isMarketDay(date: Date)`\n * - `getMarketOpenClose(options?: { date?: Date })`\n *\n * @param dateStr - Trading day string in 'YYYY-MM-DD' format (Eastern Time date)\n * @returns An object containing `{ open: Date; close: Date }`\n * @example\n * ```ts\n * const { open, close } = disco.time.getOpenCloseForTradingDay('2025-10-03');\n * ```\n */\nexport function getOpenCloseForTradingDay(dateStr: string): { open: Date; close: Date } {\n // Build a UTC midnight anchor for the date, then derive the NY offset for that day.\n const utcAnchor = new Date(`${dateStr}T00:00:00Z`);\n const nyOffset = getNYTimeZone(utcAnchor); // '-04:00' | '-05:00'\n\n // Create a NY-local noon date to avoid DST midnight transitions.\n const nyNoon = new Date(`${dateStr}T12:00:00${nyOffset}`);\n\n if (!isMarketDay(nyNoon)) {\n throw new Error(`Not a market day in ET: ${dateStr}`);\n }\n\n const { open, close } = getMarketOpenClose({ date: nyNoon });\n if (!open || !close) {\n throw new Error(`No market times available for ${dateStr}`);\n }\n\n return { open, close };\n}\n\n/**\n * Converts any date to the market time zone (America/New_York, Eastern Time).\n * Returns a new Date object representing the same moment in time but adjusted to NY/Eastern timezone.\n * Automatically handles daylight saving time transitions (EST/EDT).\n * \n * @param date - Date object to convert to market time zone\n * @returns Date object in NY/Eastern time zone\n * @example\n * ```typescript\n * const utcDate = new Date('2024-01-15T15:30:00Z'); // 3:30 PM UTC\n * const nyDate = convertDateToMarketTimeZone(utcDate); // 10:30 AM EST (winter) or 11:30 AM EDT (summer)\n * ```\n */\nexport function convertDateToMarketTimeZone(date: Date): Date {\n return toNYTime(date);\n}\n\n/**\n * Returns the current market status for a given date.\n * @param options - { date?: Date }\n * @returns MarketStatus object\n */\nexport function getMarketStatus(options: { date?: Date } = {}): MarketStatus {\n const { date = new Date() } = options;\n return getMarketStatusImpl(date);\n}\n\n/**\n * Checks if a date is a market day.\n * @param date - Date object\n * @returns true if market day, false otherwise\n */\nexport function isMarketDay(date: Date): boolean {\n const calendar = new MarketCalendar();\n return calendar.isMarketDay(date);\n}\n\n/**\n * Returns full trading days from market open to market close.\n * endDate is always the most recent market close (previous day's close if before open, today's close if after open).\n * days: 1 or not specified = that day's open; 2 = previous market day's open, etc.\n */\n/**\n * Returns full trading days from market open to market close.\n * @param options - { endDate?: Date, days?: number }\n * @returns Object with startDate and endDate\n */\nexport function getTradingStartAndEndDates(\n options: {\n endDate?: Date;\n days?: number;\n } = {}\n): { startDate: Date; endDate: Date } {\n const { endDate = new Date(), days = 1 } = options;\n const calendar = new MarketCalendar();\n\n // Find the most recent market close\n let endMarketDay = endDate;\n const nyEnd = toNYTime(endDate);\n const marketOpenMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n const marketCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n const minutes = nyEnd.getUTCHours() * 60 + nyEnd.getUTCMinutes();\n\n if (\n !calendar.isMarketDay(endDate) ||\n minutes < marketOpenMinutes ||\n (minutes >= marketOpenMinutes && minutes < marketCloseMinutes)\n ) {\n // Before market open, not a market day, or during market hours: use previous market day\n endMarketDay = calendar.getPreviousMarketDay(endDate);\n } else {\n // After market close: use today\n endMarketDay = endDate;\n }\n\n // Get market close for endMarketDay\n const endClose = getMarketOpenClose({ date: endMarketDay }).close!;\n\n // Find start market day by iterating back over market days\n let startMarketDay = endMarketDay;\n let count = Math.max(1, days);\n for (let i = 1; i < count; i++) {\n startMarketDay = calendar.getPreviousMarketDay(startMarketDay);\n }\n // If days > 1, we need to go back (days-1) market days from endMarketDay\n if (days > 1) {\n startMarketDay = endMarketDay;\n for (let i = 1; i < days; i++) {\n startMarketDay = calendar.getPreviousMarketDay(startMarketDay);\n }\n }\n const startOpen = getMarketOpenClose({ date: startMarketDay }).open!;\n\n return { startDate: startOpen, endDate: endClose };\n}\n\n/**\n * Counts trading time between two dates (passed as standard Date objects), excluding weekends and holidays, and closed market hours, using other functions in this library.\n *\n * This function calculates the actual trading time between two dates by:\n * 1. Iterating through each calendar day between startDate and endDate (inclusive)\n * 2. For each day that is a market day (not weekend/holiday), getting market open/close times\n * 3. Calculating the overlap between the time range and market hours for that day\n * 4. Summing up all the trading minutes across all days\n *\n * The function automatically handles:\n * - Weekends (Saturday/Sunday) - skipped entirely\n * - Market holidays - skipped entirely\n * - Early close days (e.g. day before holidays) - uses early close time\n * - Times outside market hours - only counts time within 9:30am-4pm ET (or early close)\n *\n * Examples:\n * - 12pm to 3:30pm same day = 3.5 hours = 210 minutes = 0.54 days\n * - 9:30am to 4pm same day = 6.5 hours = 390 minutes = 1 day\n * - Friday 2pm to Monday 2pm = 6.5 hours (Friday 2pm-4pm + Monday 9:30am-2pm)\n *\n * @param startDate - Start date/time\n * @param endDate - End date/time (default: now)\n * @returns Object containing:\n * - days: Trading time as fraction of full trading days (6.5 hours = 1 day)\n * - hours: Trading time in hours\n * - minutes: Trading time in minutes\n */\nexport function countTradingDays(\n startDate: Date,\n endDate: Date = new Date()\n): {\n days: number;\n hours: number;\n minutes: number;\n} {\n const calendar = new MarketCalendar();\n\n // Ensure start is before end\n if (startDate.getTime() > endDate.getTime()) {\n throw new Error('Start date must be before end date');\n }\n\n let totalMinutes = 0;\n\n // Get the NY dates for iteration\n const startNY = toNYTime(startDate);\n const endNY = toNYTime(endDate);\n\n // Create date at start of first day (in NY time)\n const currentNY = new Date(\n Date.UTC(startNY.getUTCFullYear(), startNY.getUTCMonth(), startNY.getUTCDate(), 0, 0, 0, 0)\n );\n\n // Iterate through each calendar day\n while (currentNY.getTime() <= endNY.getTime()) {\n const currentUTC = fromNYTime(currentNY);\n\n // Check if this is a market day\n if (calendar.isMarketDay(currentUTC)) {\n // Get market hours for this day\n const marketTimes = getMarketTimes(currentUTC);\n\n if (marketTimes.marketOpen && marketTimes.open && marketTimes.close) {\n // Calculate the overlap between our time range and market hours\n const dayStart = Math.max(startDate.getTime(), marketTimes.open.getTime());\n const dayEnd = Math.min(endDate.getTime(), marketTimes.close.getTime());\n\n // Only count if there's actual overlap\n if (dayStart < dayEnd) {\n totalMinutes += (dayEnd - dayStart) / (1000 * 60);\n }\n }\n }\n\n // Move to next day\n currentNY.setUTCDate(currentNY.getUTCDate() + 1);\n }\n\n // Convert to days, hours, minutes\n const MINUTES_PER_TRADING_DAY = 390; // 6.5 hours\n const days = totalMinutes / MINUTES_PER_TRADING_DAY;\n const hours = totalMinutes / 60;\n const minutes = totalMinutes;\n\n return {\n days: Math.round(days * 1000) / 1000, // Round to 3 decimal places\n hours: Math.round(hours * 100) / 100, // Round to 2 decimal places\n minutes: Math.round(minutes),\n };\n}\n\n/**\n * Returns the trading day N days back from a reference date, along with its market open time.\n * Trading days are counted as full or half trading days (days that end count as 1 full trading day).\n * By default, the most recent completed trading day counts as day 1.\n * Set includeMostRecentFullDay to false to count strictly before that day.\n * \n * @param options - Object with:\n * - referenceDate: Date to count back from (default: now)\n * - days: Number of trading days to go back (must be an integer >= 1)\n * - includeMostRecentFullDay: Whether to include the most recent completed trading day (default: true)\n * @returns Object containing:\n * - date: Trading date in YYYY-MM-DD format\n * - marketOpenISO: Market open time as ISO string (e.g., \"2025-11-15T13:30:00.000Z\")\n * - unixTimestamp: Market open time as Unix timestamp in seconds\n * @example\n * ```typescript\n * // Get the trading day 1 day back (most recent full trading day)\n * const result = getTradingDaysBack({ days: 1 });\n * console.log(result.date); // \"2025-11-01\"\n * console.log(result.marketOpenISO); // \"2025-11-01T13:30:00.000Z\"\n * console.log(result.unixTimestamp); // 1730466600\n * \n * // Get the trading day 5 days back from a specific date\n * const result2 = getTradingDaysBack({ \n * referenceDate: new Date('2025-11-15T12:00:00-05:00'), \n * days: 5 \n * });\n * ```\n */\nexport function getTradingDaysBack(options: TradingDaysBackOptions): {\n date: string;\n marketOpenISO: string;\n unixTimestamp: number;\n} {\n const calendar = new MarketCalendar();\n const { referenceDate, days, includeMostRecentFullDay = true } = options;\n const refDate = referenceDate || new Date();\n const daysBack = days;\n\n if (!Number.isInteger(daysBack) || daysBack < 1) {\n throw new Error('days must be an integer >= 1');\n }\n\n // Start from the last full trading date relative to reference\n let targetDate = getLastFullTradingDateImpl(refDate);\n\n if (!includeMostRecentFullDay) {\n targetDate = calendar.getPreviousMarketDay(targetDate);\n }\n\n // Go back the specified number of days (we're already at day 1, so go back days-1 more)\n for (let i = 1; i < daysBack; i++) {\n targetDate = calendar.getPreviousMarketDay(targetDate);\n }\n\n // Get market open time for this date\n const marketTimes = getMarketTimes(targetDate);\n if (!marketTimes.open) {\n throw new Error(`No market open time for target date`);\n }\n\n // Format the date string (YYYY-MM-DD) in NY time\n const nyDate = toNYTime(marketTimes.open);\n const dateStr = `${nyDate.getUTCFullYear()}-${String(nyDate.getUTCMonth() + 1).padStart(2, '0')}-${String(nyDate.getUTCDate()).padStart(2, '0')}`;\n\n const marketOpenISO = marketTimes.open.toISOString();\n const unixTimestamp = Math.floor(marketTimes.open.getTime() / 1000);\n\n return {\n date: dateStr,\n marketOpenISO,\n unixTimestamp,\n };\n}\n\n// Export MARKET_TIMES for compatibility\nexport const MARKET_TIMES: MarketTimesConfig = {\n TIMEZONE: MARKET_CONFIG.TIMEZONE,\n PRE: {\n START: { HOUR: 4, MINUTE: 0, MINUTES: 240 },\n END: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n },\n EARLY_MORNING: {\n START: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n END: { HOUR: 10, MINUTE: 0, MINUTES: 600 },\n },\n EARLY_CLOSE_BEFORE_HOLIDAY: {\n START: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n END: { HOUR: 13, MINUTE: 0, MINUTES: 780 },\n },\n EARLY_EXTENDED_BEFORE_HOLIDAY: {\n START: { HOUR: 13, MINUTE: 0, MINUTES: 780 },\n END: { HOUR: 17, MINUTE: 0, MINUTES: 1020 },\n },\n REGULAR: {\n START: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n END: { HOUR: 16, MINUTE: 0, MINUTES: 960 },\n },\n EXTENDED: {\n START: { HOUR: 4, MINUTE: 0, MINUTES: 240 },\n END: { HOUR: 20, MINUTE: 0, MINUTES: 1200 },\n },\n};\n", "import 'dotenv/config';\nimport { log as baseLog } from './logging';\nimport { LogOptions } from './types/logging-types';\nimport {\n Bar,\n AlpacaQuote,\n TimeFrame,\n AlpacaTrade,\n AlpacaAsset,\n AssetClass,\n GetAssetsParams,\n OptionBar,\n OptionTrade,\n OptionsChainParams,\n OptionsChainResponse,\n LatestOptionsTradesParams,\n LatestOptionsTradesResponse,\n LatestOptionsQuotesParams,\n LatestOptionsQuotesResponse,\n LatestQuotesResponse,\n LatestTradesResponse,\n HistoricalOptionsBarsParams,\n HistoricalOptionsBarsResponse,\n HistoricalOptionsTradesParams,\n HistoricalOptionsTradesResponse,\n OptionsSnapshotsParams,\n OptionsSnapshotsResponse,\n OptionsConditionCodesResponse,\n OptionsExchangeCodesResponse,\n OptionTickType,\n SimpleNews,\n AlpacaNewsArticle,\n DataFeed,\n AlpacaStockStreamMessage,\n AlpacaOptionStreamMessage,\n StockStreamEventName,\n OptionStreamEventName,\n StockStreamEventMap,\n OptionStreamEventMap,\n CryptoTrade,\n CryptoQuote,\n CryptoOrderbook,\n CryptoSnapshot,\n CryptoHistoricalBarsResponse,\n CryptoLatestBarsResponse,\n CryptoHistoricalQuotesResponse,\n CryptoLatestQuotesResponse,\n CryptoHistoricalTradesResponse,\n CryptoLatestTradesResponse,\n CryptoSnapshotsResponse,\n CryptoLatestOrderbooksResponse,\n CryptoHistoricalBarsParams,\n CryptoHistoricalQuotesParams,\n CryptoHistoricalTradesParams,\n} from './types/alpaca-types';\nimport { getLastFullTradingDate } from './market-time';\nimport { EventEmitter } from 'events';\nimport WebSocket from 'ws';\n\nconst DEBUG_LOGGING = process.env['DEBUG'] === 'true' || false;\n\nconst log = (message: string, options: LogOptions = { type: 'info' }) => {\n if (!DEBUG_LOGGING && options.type === 'debug') {\n return;\n }\n baseLog(message, { ...options, source: 'AlpacaMarketDataAPI' });\n};\n\n// Default settings for market data API\nconst DEFAULT_ADJUSTMENT = 'all' as const;\nconst DEFAULT_FEED = 'sip' as DataFeed;\nconst DEFAULT_CURRENCY = 'USD' as const;\n\n/**\n * Parameters for retrieving historical market data bars\n * @see https://data.alpaca.markets/v2/stocks/bars\n */\nexport interface HistoricalBarsParams {\n /** Comma-separated list of stock symbols to query, e.g. 'AAPL,MSFT,TSLA' */\n symbols: string[];\n /**\n * Bar duration/timeframe\n * Format: [1-59]Min/T, [1-23]Hour/H, 1Day/D, 1Week/W, [1,2,3,4,6,12]Month/M\n * Examples: \"1Min\", \"5Min\", \"1Hour\", \"1Day\", \"1Week\", \"1Month\"\n */\n timeframe: TimeFrame;\n /**\n * Start datetime in RFC-3339 format (YYYY-MM-DD)\n * Example: \"2024-02-11T09:00:00Z\"\n */\n start?: string;\n /**\n * End datetime in RFC-3339 format (YYYY-MM-DD)\n * Example: \"2024-02-11T16:00:00Z\"\n */\n end?: string;\n /**\n * Number of bars to return (1-10000)\n * Default: 1000\n */\n limit?: number;\n /** \n\n /** \n * Pagination token for retrieving next page of results\n * Returned in the next_page_token field of the response\n */\n page_token?: string;\n /**\n * Specifies the price adjustments applied to the bars\n * - raw: no adjustments\n * - split: adjust for forward and reverse stock splits\n * - dividend: adjust for cash dividends\n * - spin-off: adjust for spin-offs\n * - all: apply all adjustments (default)\n * Can also be comma-separated combinations, e.g. 'split,spin-off'\n */\n adjustment?: 'raw' | 'split' | 'dividend' | 'spin-off' | 'all' | string;\n /**\n * Sort order of returned bars\n * - asc: Oldest to newest (default)\n * - desc: Newest to oldest\n */\n sort?: 'asc' | 'desc';\n}\n\n/**\n * Response from historical bars endpoint\n * Contains OHLCV (Open, High, Low, Close, Volume) data for requested symbols\n */\nexport interface HistoricalBarsResponse {\n /**\n * Map of symbol to array of bar data\n * Each bar contains OHLCV data for the specified timeframe\n */\n bars: {\n [symbol: string]: Bar[];\n };\n /**\n * Token for retrieving the next page of results\n * null if there are no more results\n */\n next_page_token: string | null;\n /** Currency of the price data in ISO 4217 format */\n currency: string;\n}\n\n/**\n * Response from latest bars endpoint\n * Contains the most recent minute bar for each requested symbol\n */\nexport interface LatestBarsResponse {\n /**\n * Map of symbol to latest bar data\n * Each bar contains OHLCV data for the most recent minute\n */\n bars: {\n [symbol: string]: Bar;\n };\n /** Currency of the price data in ISO 4217 format */\n currency: string;\n}\n\n/**\n * Response from last trade endpoint for a single symbol\n * Contains detailed information about the most recent trade\n */\nexport interface LastTradeResponse {\n /** Status of the request */\n status: string;\n /** The stock symbol that was queried */\n symbol: string;\n /**\n * Details of the last trade\n * @property price - Trade price\n * @property size - Trade size (quantity)\n * @property exchange - Exchange where trade occurred (see Common Exchange Codes in docs)\n * @property cond1-4 - Trade conditions\n * @property timestamp - UNIX epoch timestamp in milliseconds\n */\n last: {\n price: number;\n size: number;\n exchange: number;\n cond1: number;\n cond2: number;\n cond3: number;\n cond4: number;\n timestamp: number;\n };\n}\n\n/**\n * Singleton class for interacting with Alpaca Market Data API\n * Provides methods for fetching historical bars, latest bars, last trades, latest trades, latest quotes, and latest quote for a single symbol\n */\nexport class AlpacaMarketDataAPI extends EventEmitter {\n private static instance: AlpacaMarketDataAPI;\n private headers: Record<string, string>;\n private dataURL: string;\n private apiURL: string;\n private v1beta1url: string;\n private v1beta3url: string;\n private stockStreamUrl: string = 'wss://stream.data.alpaca.markets/v2/sip'; // production values\n private optionStreamUrl: string = 'wss://stream.data.alpaca.markets/v1beta3/options'; // production values\n private stockWs: WebSocket | null = null;\n private optionWs: WebSocket | null = null;\n private stockSubscriptions: Record<string, string[]> = { trades: [], quotes: [], bars: [] };\n private optionSubscriptions: Record<string, string[]> = { trades: [], quotes: [], bars: [] };\n private autoReconnect: boolean = true;\n private stockReconnectAttempts: number = 0;\n private optionReconnectAttempts: number = 0;\n private stockReconnectTimeout: NodeJS.Timeout | null = null;\n private optionReconnectTimeout: NodeJS.Timeout | null = null;\n\n public setMode(mode: 'sandbox' | 'test' | 'production' = 'production'): void {\n if (mode === 'sandbox') {\n // sandbox mode\n this.stockStreamUrl = 'wss://stream.data.sandbox.alpaca.markets/v2/sip';\n this.optionStreamUrl = 'wss://stream.data.sandbox.alpaca.markets/v1beta3/options';\n } else if (mode === 'test') {\n // test mode, can only use ticker FAKEPACA\n this.stockStreamUrl = 'wss://stream.data.alpaca.markets/v2/test';\n this.optionStreamUrl = 'wss://stream.data.alpaca.markets/v1beta3/options'; // there's no test mode for options\n } else {\n // production\n this.stockStreamUrl = 'wss://stream.data.alpaca.markets/v2/sip';\n this.optionStreamUrl = 'wss://stream.data.alpaca.markets/v1beta3/options';\n }\n }\n\n public getMode(): 'sandbox' | 'test' | 'production' {\n if (this.stockStreamUrl.includes('sandbox')) {\n return 'sandbox';\n } else if (this.stockStreamUrl.includes('test')) {\n return 'test';\n } else {\n return 'production';\n }\n }\n\n public setAutoReconnect(enabled: boolean): void {\n this.autoReconnect = enabled;\n log(`Auto-reconnect ${enabled ? 'enabled' : 'disabled'}`);\n }\n\n public getAutoReconnect(): boolean {\n return this.autoReconnect;\n }\n\n private constructor() {\n super();\n this.dataURL = 'https://data.alpaca.markets/v2';\n this.apiURL =\n process.env.ALPACA_ACCOUNT_TYPE === 'PAPER'\n ? 'https://paper-api.alpaca.markets/v2'\n : 'https://api.alpaca.markets/v2'; // used by some, e.g. getAssets\n this.v1beta1url = 'https://data.alpaca.markets/v1beta1'; // used for options endpoints\n this.v1beta3url = 'https://data.alpaca.markets/v1beta3'; // used for crypto endpoints\n this.setMode('production'); // sets stockStreamUrl and optionStreamUrl\n this.headers = {\n 'APCA-API-KEY-ID': process.env.ALPACA_API_KEY!,\n 'APCA-API-SECRET-KEY': process.env.ALPACA_SECRET_KEY!,\n 'Content-Type': 'application/json',\n };\n }\n\n public static getInstance(): AlpacaMarketDataAPI {\n if (!AlpacaMarketDataAPI.instance) {\n AlpacaMarketDataAPI.instance = new AlpacaMarketDataAPI();\n }\n return AlpacaMarketDataAPI.instance;\n }\n\n private getReconnectDelay(attempt: number): number {\n // 0: instant (0ms), 1: 5s, 2: 10s, 3: 15s, 4+: 60s\n const delays = [0, 5000, 10000, 15000, 60000];\n return attempt < delays.length ? delays[attempt] : 60000;\n }\n\n private scheduleReconnect(streamType: 'stock' | 'option'): void {\n if (!this.autoReconnect) {\n log(`Auto-reconnect disabled, not reconnecting ${streamType} stream`);\n return;\n }\n\n const attempts = streamType === 'stock' ? this.stockReconnectAttempts : this.optionReconnectAttempts;\n const delay = this.getReconnectDelay(attempts);\n \n log(`Scheduling ${streamType} stream reconnect (attempt ${attempts + 1}) in ${delay}ms`);\n\n const timeout = setTimeout(() => {\n log(`Attempting to reconnect ${streamType} stream (attempt ${attempts + 1})`);\n if (streamType === 'stock') {\n this.stockReconnectAttempts++;\n } else {\n this.optionReconnectAttempts++;\n }\n this.connect(streamType);\n }, delay);\n\n if (streamType === 'stock') {\n this.stockReconnectTimeout = timeout;\n } else {\n this.optionReconnectTimeout = timeout;\n }\n }\n\n // Type-safe event emitter methods\n public on<K extends StockStreamEventName>(event: K, listener: (data: StockStreamEventMap[K]) => void): this;\n public on<K extends OptionStreamEventName>(event: K, listener: (data: OptionStreamEventMap[K]) => void): this;\n public on(event: string | symbol, listener: (...args: any[]) => void): this {\n return super.on(event, listener);\n }\n\n public emit<K extends StockStreamEventName>(event: K, data: StockStreamEventMap[K]): boolean;\n public emit<K extends OptionStreamEventName>(event: K, data: OptionStreamEventMap[K]): boolean;\n public emit(event: string | symbol, ...args: any[]): boolean {\n return super.emit(event, ...args);\n }\n\n private connect(streamType: 'stock' | 'option'): void {\n const url = streamType === 'stock' ? this.stockStreamUrl : this.optionStreamUrl;\n const ws = new WebSocket(url);\n if (streamType === 'stock') {\n this.stockWs = ws;\n } else {\n this.optionWs = ws;\n }\n\n ws.on('open', () => {\n log(`${streamType} stream connected`);\n // Reset reconnect attempts on successful connection\n if (streamType === 'stock') {\n this.stockReconnectAttempts = 0;\n if (this.stockReconnectTimeout) {\n clearTimeout(this.stockReconnectTimeout);\n this.stockReconnectTimeout = null;\n }\n } else {\n this.optionReconnectAttempts = 0;\n if (this.optionReconnectTimeout) {\n clearTimeout(this.optionReconnectTimeout);\n this.optionReconnectTimeout = null;\n }\n }\n const authMessage = {\n action: 'auth',\n key: process.env.ALPACA_API_KEY!,\n secret: process.env.ALPACA_SECRET_KEY!,\n };\n ws.send(JSON.stringify(authMessage));\n });\n\n ws.on('message', (data: WebSocket.Data) => {\n //log(`RAW MESSASGE: ${data.toString()}`);\n const messages = JSON.parse(data.toString());\n for (const message of messages) {\n if (message.T === 'success' && message.msg === 'authenticated') {\n log(`${streamType} stream authenticated`);\n this.sendSubscription(streamType);\n } else if (message.T === 'error') {\n log(`${streamType} stream error: ${message.msg}`, { type: 'error' });\n } else if (message.S) {\n super.emit(`${streamType}-${message.T}`, message);\n super.emit(`${streamType}-data`, message as AlpacaStockStreamMessage | AlpacaOptionStreamMessage);\n }\n }\n });\n\n ws.on('close', (code: number, reason: Buffer) => {\n const reasonStr = reason.toString() || 'No reason provided';\n const codeDesc = this.getCloseCodeDescription(code);\n log(`${streamType} stream disconnected - Code: ${code} (${codeDesc}), Reason: ${reasonStr}`, { type: 'warn' });\n \n if (streamType === 'stock') {\n this.stockWs = null;\n } else {\n this.optionWs = null;\n }\n \n this.scheduleReconnect(streamType);\n });\n\n ws.on('error', (error: Error) => {\n log(`${streamType} stream error: ${error.message}`, { type: 'error' });\n });\n }\n\n private getCloseCodeDescription(code: number): string {\n const codes: Record<number, string> = {\n 1000: 'Normal Closure',\n 1001: 'Going Away',\n 1002: 'Protocol Error',\n 1003: 'Unsupported Data',\n 1005: 'No Status Received',\n 1006: 'Abnormal Closure',\n 1007: 'Invalid Frame Payload Data',\n 1008: 'Policy Violation',\n 1009: 'Message Too Big',\n 1010: 'Mandatory Extension',\n 1011: 'Internal Server Error',\n 1012: 'Service Restart',\n 1013: 'Try Again Later',\n 1014: 'Bad Gateway',\n 1015: 'TLS Handshake',\n };\n return codes[code] || 'Unknown';\n }\n\n private sendSubscription(streamType: 'stock' | 'option'): void {\n const ws = streamType === 'stock' ? this.stockWs : this.optionWs;\n const subscriptions = streamType === 'stock' ? this.stockSubscriptions : this.optionSubscriptions;\n if (ws && ws.readyState === WebSocket.OPEN) {\n const subMessagePayload: { trades?: string[]; quotes?: string[]; bars?: string[] } = {};\n\n if (subscriptions.trades.length > 0) {\n subMessagePayload.trades = subscriptions.trades;\n }\n if (subscriptions.quotes.length > 0) {\n subMessagePayload.quotes = subscriptions.quotes;\n }\n if (subscriptions.bars.length > 0) {\n subMessagePayload.bars = subscriptions.bars;\n }\n\n if (Object.keys(subMessagePayload).length > 0) {\n const subMessage = {\n action: 'subscribe',\n ...subMessagePayload,\n };\n ws.send(JSON.stringify(subMessage));\n }\n }\n }\n\n public connectStockStream(): void {\n if (!this.stockWs) {\n this.connect('stock');\n }\n }\n\n public connectOptionStream(): void {\n if (!this.optionWs) {\n this.connect('option');\n }\n }\n\n public disconnectStockStream(): void {\n if (this.stockReconnectTimeout) {\n clearTimeout(this.stockReconnectTimeout);\n this.stockReconnectTimeout = null;\n }\n this.stockReconnectAttempts = 0;\n if (this.stockWs) {\n this.stockWs.close();\n }\n }\n\n public disconnectOptionStream(): void {\n if (this.optionReconnectTimeout) {\n clearTimeout(this.optionReconnectTimeout);\n this.optionReconnectTimeout = null;\n }\n this.optionReconnectAttempts = 0;\n if (this.optionWs) {\n this.optionWs.close();\n }\n }\n\n public subscribe(\n streamType: 'stock' | 'option',\n subscriptions: { trades?: string[]; quotes?: string[]; bars?: string[] }\n ): void {\n const currentSubscriptions = streamType === 'stock' ? this.stockSubscriptions : this.optionSubscriptions;\n Object.entries(subscriptions).forEach(([key, value]) => {\n if (value) {\n currentSubscriptions[key] = [...new Set([...(currentSubscriptions[key] || []), ...value])];\n }\n });\n\n this.sendSubscription(streamType);\n }\n\n public unsubscribe(\n streamType: 'stock' | 'option',\n subscriptions: { trades?: string[]; quotes?: string[]; bars?: string[] }\n ): void {\n const currentSubscriptions = streamType === 'stock' ? this.stockSubscriptions : this.optionSubscriptions;\n Object.entries(subscriptions).forEach(([key, value]) => {\n if (value) {\n currentSubscriptions[key] = (currentSubscriptions[key] || []).filter((s) => !value.includes(s));\n }\n });\n const unsubMessage = {\n action: 'unsubscribe',\n ...subscriptions,\n };\n\n const ws = streamType === 'stock' ? this.stockWs : this.optionWs;\n if (ws && ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify(unsubMessage));\n }\n }\n\n private async makeRequest(\n endpoint: string,\n method: string = 'GET',\n params?: Record<string, any>,\n baseUrlName: 'data' | 'api' | 'v1beta1' | 'v1beta3' = 'data'\n ): Promise<any> {\n const baseUrl = baseUrlName === 'data' ? this.dataURL : \n baseUrlName === 'api' ? this.apiURL : \n baseUrlName === 'v1beta1' ? this.v1beta1url : this.v1beta3url;\n const url = new URL(`${baseUrl}${endpoint}`);\n\n try {\n if (params) {\n Object.entries(params).forEach(([key, value]) => {\n if (Array.isArray(value)) {\n url.searchParams.append(key, value.join(','));\n } else if (value !== undefined) {\n url.searchParams.append(key, value.toString());\n }\n });\n }\n\n const response = await fetch(url.toString(), {\n method,\n headers: this.headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n log(`Market Data API error (${response.status}): ${errorText}`, { type: 'error' });\n throw new Error(`Market Data API error (${response.status}): ${errorText}`);\n }\n\n const data = await response.json();\n return data;\n } catch (err) {\n const error = err as Error;\n log(`Error in makeRequest: ${error.message}. Endpoint: ${endpoint}. Url: ${url.toString()}`, { type: 'error' });\n if (error instanceof TypeError) {\n log(`Network error details: ${error.stack}`, { type: 'error' });\n }\n throw error;\n }\n }\n\n /**\n * Get historical OHLCV bars for specified symbols, including pre-market and post-market data\n * Automatically handles pagination to fetch all available data\n * @param params Parameters for historical bars request\n * @returns Historical bars data with all pages combined\n */\n async getHistoricalBars(params: HistoricalBarsParams): Promise<HistoricalBarsResponse> {\n const symbols = params.symbols;\n const symbolsStr = symbols.join(',');\n let allBars: { [symbol: string]: Bar[] } = {};\n let pageToken: string | null = null;\n let hasMorePages = true;\n let totalBarsCount = 0;\n let pageCount = 0;\n let currency = '';\n\n // Initialize bar arrays for each symbol\n symbols.forEach((symbol) => {\n allBars[symbol] = [];\n });\n\n log(\n `Starting ${params.timeframe}bars fetch for ${symbols.length} symbols (${symbolsStr}), ${params.start || 'no start'} to ${params.end || 'no end'})`, { symbol: symbolsStr }\n );\n\n while (hasMorePages) {\n pageCount++;\n const requestParams = {\n ...params,\n adjustment: params.adjustment ?? DEFAULT_ADJUSTMENT,\n feed: DEFAULT_FEED,\n ...(pageToken && { page_token: pageToken }),\n };\n\n const response: HistoricalBarsResponse = await this.makeRequest('/stocks/bars', 'GET', requestParams);\n\n if (!response.bars) {\n log(`No bars data found in response for ${symbols.length} symbols`, { symbol: symbolsStr, type: 'warn' });\n break;\n }\n\n // Track currency from first response\n if (!currency) {\n currency = response.currency;\n }\n\n // Combine bars for each symbol\n let pageBarsCount = 0;\n let earliestTimestamp: Date | null = null;\n let latestTimestamp: Date | null = null;\n\n Object.entries(response.bars).forEach(([symbol, bars]) => {\n if (bars && bars.length > 0) {\n allBars[symbol] = [...allBars[symbol], ...bars];\n pageBarsCount += bars.length;\n\n // Track date range for this page\n bars.forEach((bar) => {\n const barDate = new Date(bar.t);\n if (!earliestTimestamp || barDate < earliestTimestamp) {\n earliestTimestamp = barDate;\n }\n if (!latestTimestamp || barDate > latestTimestamp) {\n latestTimestamp = barDate;\n }\n });\n }\n });\n\n totalBarsCount += pageBarsCount;\n pageToken = response.next_page_token || null;\n hasMorePages = !!pageToken;\n\n // Enhanced logging with date range and progress info\n const dateRangeStr =\n earliestTimestamp && latestTimestamp\n ? `${new Date(earliestTimestamp).toLocaleDateString('en-US', { timeZone: 'America/New_York' })} to ${new Date(\n latestTimestamp\n ).toLocaleDateString('en-US', { timeZone: 'America/New_York' })}`\n : 'unknown range';\n\n log(\n `Page ${pageCount}: Fetched ${pageBarsCount.toLocaleString()} bars (total: ${totalBarsCount.toLocaleString()}) for ${\n symbols.length\n } symbols, date range: ${dateRangeStr}${hasMorePages ? ', more pages available' : ', complete'}`, {symbol: symbolsStr, type: 'debug' }\n );\n\n // Prevent infinite loops\n if (pageCount > 1000) {\n log(`Stopping pagination after ${pageCount} pages to prevent infinite loop`, { type: 'warn' });\n break;\n }\n }\n\n // Final summary\n const symbolCounts = Object.entries(allBars)\n .map(([symbol, bars]) => `${symbol}: ${bars.length}`)\n .join(', ');\n log(\n `${params.timeframe} bars fetch complete: ${totalBarsCount.toLocaleString()} total bars across ${pageCount} pages for ${symbols.length\n } symbols (${symbolCounts})`, { symbol: symbolsStr }\n );\n\n return {\n bars: allBars,\n next_page_token: null, // Always null since we fetch all pages\n currency: currency || DEFAULT_CURRENCY,\n };\n }\n\n /**\n * Get the most recent minute bar for requested symbols\n * @param symbols Array of stock symbols to query\n * @param currency Optional currency in ISO 4217 format\n * @returns Latest bar data for each symbol\n \n */\n async getLatestBars(symbols: string[], currency?: string): Promise<LatestBarsResponse> {\n return this.makeRequest('/stocks/bars/latest', 'GET', {\n symbols,\n feed: DEFAULT_FEED,\n currency: currency || DEFAULT_CURRENCY,\n });\n }\n\n /**\n * Get the last trade for a single symbol\n * @param symbol The stock symbol to query\n * @returns Last trade details including price, size, exchange, and conditions\n */\n async getLastTrade(symbol: string): Promise<LastTradeResponse> {\n return this.makeRequest(`/v1/last/stocks/${symbol}`, 'GET');\n }\n\n /**\n * Get the most recent trades for requested symbols\n * @param symbols Array of stock symbols to query\n * @param feed Optional data source (sip/iex/delayed_sip)\n * @param currency Optional currency in ISO 4217 format\n * @returns Latest trade data for each symbol\n \n */\n async getLatestTrades(symbols: string[], feed?: DataFeed, currency?: string): Promise<LatestTradesResponse> {\n return this.makeRequest('/stocks/trades/latest', 'GET', {\n symbols,\n feed: feed || DEFAULT_FEED,\n currency: currency || DEFAULT_CURRENCY,\n });\n }\n\n /**\n * Get the most recent quotes for requested symbols\n * @param symbols Array of stock symbols to query\n * @param feed Optional data source (sip/iex/delayed_sip)\n * @param currency Optional currency in ISO 4217 format\n * @returns Latest quote data for each symbol\n */\n async getLatestQuotes(symbols: string[], feed?: DataFeed, currency?: string): Promise<LatestQuotesResponse> {\n // Return empty response if symbols array is empty to avoid API error\n if (!symbols || symbols.length === 0) {\n log('No symbols provided to getLatestQuotes, returning empty response', { type: 'warn' });\n return {\n quotes: {},\n currency: currency || DEFAULT_CURRENCY,\n };\n }\n\n return this.makeRequest('/stocks/quotes/latest', 'GET', {\n symbols,\n feed: feed || DEFAULT_FEED,\n currency: currency || DEFAULT_CURRENCY,\n });\n }\n\n /**\n * Get the latest quote for a single symbol\n * @param symbol The stock symbol to query\n * @param feed Optional data source (sip/iex/delayed_sip)\n * @param currency Optional currency in ISO 4217 format\n * @returns Latest quote data with symbol and currency information\n */\n async getLatestQuote(\n symbol: string,\n feed?: DataFeed,\n currency?: string\n ): Promise<{ quote: AlpacaQuote; symbol: string; currency: string }> {\n return this.makeRequest(`/stocks/${symbol}/quotes/latest`, 'GET', {\n feed: feed || DEFAULT_FEED,\n currency,\n });\n }\n\n /**\n * Get the previous day's closing price for a symbol\n * @param symbol The stock symbol to query\n * @param referenceDate Optional reference date to get the previous close for\n * @returns Previous day's closing price data\n */\n async getPreviousClose(symbol: string, referenceDate?: Date): Promise<Bar | null> {\n const date = referenceDate || new Date();\n const prevMarketDate = getLastFullTradingDate(date);\n\n const response = await this.getHistoricalBars({\n symbols: [symbol],\n timeframe: '1Day',\n start: prevMarketDate.toISOString(),\n end: prevMarketDate.toISOString(),\n limit: 1,\n });\n\n if (!response.bars[symbol] || response.bars[symbol].length === 0) {\n log(`No previous close data available for ${symbol}`, { type: 'error', symbol });\n return null;\n }\n\n return response.bars[symbol][0];\n }\n\n /**\n * Get hourly price data for a symbol\n * @param symbol The stock symbol to query\n * @param start Start time in milliseconds\n * @param end End time in milliseconds\n * @returns Array of hourly price bars\n */\n async getHourlyPrices(symbol: string, start: number, end: number): Promise<Bar[]> {\n const response = await this.getHistoricalBars({\n symbols: [symbol],\n timeframe: '1Hour',\n start: new Date(start).toISOString(),\n end: new Date(end).toISOString(),\n limit: 96, // Last 96 hours (4 days)\n });\n\n return response.bars[symbol] || [];\n }\n\n /**\n * Get half-hourly price data for a symbol\n * @param symbol The stock symbol to query\n * @param start Start time in milliseconds\n * @param end End time in milliseconds\n * @returns Array of half-hourly price bars\n */\n async getHalfHourlyPrices(symbol: string, start: number, end: number): Promise<Bar[]> {\n const response = await this.getHistoricalBars({\n symbols: [symbol],\n timeframe: '30Min',\n start: new Date(start).toISOString(),\n end: new Date(end).toISOString(),\n limit: 16 * 2 * 4, // last 4 days, 16 hours per day, 2 bars per hour\n });\n\n return response.bars[symbol] || [];\n }\n\n /**\n * Get daily price data for a symbol\n * @param symbol The stock symbol to query\n * @param start Start time in milliseconds\n * @param end End time in milliseconds\n * @returns Array of daily price bars\n */\n async getDailyPrices(symbol: string, start: number, end: number): Promise<Bar[]> {\n const response = await this.getHistoricalBars({\n symbols: [symbol],\n timeframe: '1Day',\n start: new Date(start).toISOString(),\n end: new Date(end).toISOString(),\n limit: 100, // Last 100 days\n });\n\n return response.bars[symbol] || [];\n }\n\n /**\n * Get intraday price data for a symbol\n * @param symbol The stock symbol to query\n * @param minutePeriod Minutes per bar (1, 5, 15, etc.)\n * @param start Start time in milliseconds\n * @param end End time in milliseconds\n * @returns Array of intraday price bars\n */\n async getIntradayPrices(symbol: string, minutePeriod: number, start: number, end: number): Promise<Bar[]> {\n const timeframe = `${minutePeriod}Min` as TimeFrame;\n const response = await this.getHistoricalBars({\n symbols: [symbol],\n timeframe,\n start: new Date(start).toISOString(),\n end: new Date(end).toISOString(),\n });\n\n return response.bars[symbol] || [];\n }\n\n /**\n * Analyzes an array of price bars and returns a summary string\n * @param bars Array of price bars to analyze\n * @returns A string summarizing the price data\n */\n static analyzeBars(bars: Bar[]): string {\n if (!bars || bars.length === 0) {\n return 'No price data available';\n }\n\n const firstBar = bars[0];\n const lastBar = bars[bars.length - 1];\n const priceChange = lastBar.c - firstBar.o;\n const percentChange = (priceChange / firstBar.o) * 100;\n\n const volumeChange = lastBar.v - firstBar.v;\n const percentVolumeChange = (volumeChange / firstBar.v) * 100;\n\n const high = Math.max(...bars.map((bar) => bar.h));\n const low = Math.min(...bars.map((bar) => bar.l));\n const totalVolume = bars.reduce((sum, bar) => sum + bar.v, 0);\n const avgVolume = totalVolume / bars.length;\n\n return (\n `Price: $${firstBar.o.toFixed(2)} -> $${lastBar.c.toFixed(2)} (${percentChange.toFixed(2)}%), ` +\n `Volume: ${firstBar.v.toLocaleString()} -> ${lastBar.v.toLocaleString()} (${percentVolumeChange.toFixed(2)}%), ` +\n `High: $${high.toFixed(2)}, Low: $${low.toFixed(2)}, ` +\n `Avg Volume: ${avgVolume.toLocaleString()}`\n );\n }\n\n /**\n * Get assets available for trade and data consumption from Alpaca\n * @param params Optional query params\n * - status: 'active' | 'inactive' (default 'active')\n * - asset_class: 'us_equity' | 'us_option' | 'crypto' (default 'us_equity')\n * - shortable: if true (default), filters to assets with shortable=true and easy_to_borrow=true\n * @returns Array of AlpacaAsset objects\n * @see https://docs.alpaca.markets/reference/get-v2-assets-1\n */\n async getAssets(params?: GetAssetsParams): Promise<AlpacaAsset[]> {\n // Endpoint: GET /v2/assets\n const {\n status = 'active',\n asset_class = 'us_equity',\n shortable = true,\n }: { status: 'active' | 'inactive'; asset_class: AssetClass; shortable: boolean } = {\n status: params?.status ?? 'active',\n asset_class: params?.asset_class ?? 'us_equity',\n shortable: params?.shortable ?? true,\n };\n\n const assets: AlpacaAsset[] = await this.makeRequest(\n '/assets',\n 'GET',\n { status, asset_class },\n 'api'\n );\n\n if (!shortable) return assets;\n return assets.filter((a) => a.shortable === true && a.easy_to_borrow === true);\n }\n\n /**\n * Get a single asset by symbol or asset_id\n * @param symbolOrAssetId Symbol or asset_id\n * @returns AlpacaAsset object\n * @see https://docs.alpaca.markets/reference/get-v2-assets-symbol_or_asset_id\n */\n async getAsset(symbolOrAssetId: string): Promise<AlpacaAsset> {\n // Endpoint: GET /v2/assets/{symbol_or_asset_id}\n return this.makeRequest(`/assets/${encodeURIComponent(symbolOrAssetId)}`, 'GET', undefined, 'api');\n }\n\n // ===== OPTIONS MARKET DATA METHODS =====\n\n /**\n * Get options chain for an underlying symbol\n * Provides the latest trade, latest quote, and greeks for each contract symbol of the underlying symbol\n * @param params Options chain request parameters\n * @returns Options chain data with snapshots for each contract\n * @see https://docs.alpaca.markets/reference/optionchain\n */\n async getOptionsChain(params: OptionsChainParams): Promise<OptionsChainResponse> {\n const { underlying_symbol, ...queryParams } = params;\n return this.makeRequest(\n `/options/snapshots/${encodeURIComponent(underlying_symbol)}`,\n 'GET',\n queryParams,\n 'v1beta1'\n );\n }\n\n /**\n * Get the most recent trades for requested option contract symbols\n * @param params Latest options trades request parameters\n * @returns Latest trade data for each option contract symbol\n \n * @see https://docs.alpaca.markets/reference/optionlatesttrades\n */\n async getLatestOptionsTrades(params: LatestOptionsTradesParams): Promise<LatestOptionsTradesResponse> {\n // Remove limit and page_token as they're not supported by this endpoint\n const { limit, page_token, ...requestParams } = params;\n return this.makeRequest('/options/trades/latest', 'GET', requestParams, 'v1beta1');\n }\n\n /**\n * Get the most recent quotes for requested option contract symbols\n * @param params Latest options quotes request parameters\n * @returns Latest quote data for each option contract symbol\n \n * @see https://docs.alpaca.markets/reference/optionlatestquotes\n */\n async getLatestOptionsQuotes(params: LatestOptionsQuotesParams): Promise<LatestOptionsQuotesResponse> {\n // Remove limit and page_token as they're not supported by this endpoint\n const { limit, page_token, ...requestParams } = params;\n return this.makeRequest('/options/quotes/latest', 'GET', requestParams, 'v1beta1');\n }\n\n /**\n * Get historical OHLCV bars for option contract symbols\n * Automatically handles pagination to fetch all available data\n * @param params Historical options bars request parameters\n * @returns Historical bar data for each option contract symbol with all pages combined\n \n * @see https://docs.alpaca.markets/reference/optionbars\n */\n async getHistoricalOptionsBars(params: HistoricalOptionsBarsParams): Promise<HistoricalOptionsBarsResponse> {\n const symbols = params.symbols;\n const symbolsStr = symbols.join(',');\n let allBars: { [symbol: string]: OptionBar[] } = {};\n let pageToken: string | null = null;\n let hasMorePages = true;\n let totalBarsCount = 0;\n let pageCount = 0;\n\n // Initialize bar arrays for each symbol\n symbols.forEach((symbol) => {\n allBars[symbol] = [];\n });\n\n log(\n `Starting historical options bars fetch for ${symbols.length} symbols (${params.timeframe}, ${\n params.start || 'no start'\n } to ${params.end || 'no end'})`\n );\n\n while (hasMorePages) {\n pageCount++;\n const requestParams = {\n ...params,\n ...(pageToken && { page_token: pageToken }),\n };\n\n const response: HistoricalOptionsBarsResponse = await this.makeRequest(\n '/options/bars',\n 'GET',\n requestParams,\n 'v1beta1'\n );\n\n if (!response.bars) {\n log(`No options bars data found in response for ${symbols.length} symbols`, { type: 'warn' });\n break;\n }\n\n // Combine bars for each symbol\n let pageBarsCount = 0;\n let earliestTimestamp: Date | null = null;\n let latestTimestamp: Date | null = null;\n\n Object.entries(response.bars).forEach(([symbol, bars]) => {\n if (bars && bars.length > 0) {\n allBars[symbol] = [...allBars[symbol], ...bars];\n pageBarsCount += bars.length;\n\n // Track date range for this page\n bars.forEach((bar) => {\n const barDate = new Date(bar.t);\n if (!earliestTimestamp || barDate < earliestTimestamp) {\n earliestTimestamp = barDate;\n }\n if (!latestTimestamp || barDate > latestTimestamp) {\n latestTimestamp = barDate;\n }\n });\n }\n });\n\n totalBarsCount += pageBarsCount;\n pageToken = response.next_page_token || null;\n hasMorePages = !!pageToken;\n\n // Enhanced logging with date range and progress info\n const dateRangeStr =\n earliestTimestamp && latestTimestamp\n ? `${(earliestTimestamp as Date).toLocaleDateString('en-US', { timeZone: 'America/New_York' })} to ${(\n latestTimestamp as Date\n ).toLocaleDateString('en-US', { timeZone: 'America/New_York' })}`\n : 'unknown range';\n\n log(\n `Page ${pageCount}: Fetched ${pageBarsCount.toLocaleString()} option bars (total: ${totalBarsCount.toLocaleString()}) for ${\n symbols.length\n } symbols, date range: ${dateRangeStr}${hasMorePages ? ', more pages available' : ', complete'}`,\n {\n type: 'debug',\n }\n );\n\n // Prevent infinite loops\n if (pageCount > 1000) {\n log(`Stopping options bars pagination after ${pageCount} pages to prevent infinite loop`, { type: 'warn' });\n break;\n }\n }\n\n // Final summary\n const symbolCounts = Object.entries(allBars)\n .map(([symbol, bars]) => `${symbol}: ${bars.length}`)\n .join(', ');\n log(\n `Options bars fetch complete: ${totalBarsCount.toLocaleString()} total bars across ${pageCount} pages (${symbolCounts})`\n );\n\n return {\n bars: allBars,\n next_page_token: undefined, // Always undefined since we fetch all pages\n };\n }\n\n /**\n * Get historical trades for option contract symbols\n * Automatically handles pagination to fetch all available data\n * @param params Historical options trades request parameters\n * @returns Historical trade data for each option contract symbol with all pages combined\n \n * @see https://docs.alpaca.markets/reference/optiontrades\n */\n async getHistoricalOptionsTrades(params: HistoricalOptionsTradesParams): Promise<HistoricalOptionsTradesResponse> {\n const symbols = params.symbols;\n const symbolsStr = symbols.join(',');\n let allTrades: { [symbol: string]: OptionTrade[] } = {};\n let pageToken: string | null = null;\n let hasMorePages = true;\n let totalTradesCount = 0;\n let pageCount = 0;\n\n // Initialize trades arrays for each symbol\n symbols.forEach((symbol) => {\n allTrades[symbol] = [];\n });\n\n log(\n `Starting historical options trades fetch for ${symbols.length} symbols (${params.start || 'no start'} to ${\n params.end || 'no end'\n })`\n );\n\n while (hasMorePages) {\n pageCount++;\n const requestParams = {\n ...params,\n ...(pageToken && { page_token: pageToken }),\n };\n\n const response: HistoricalOptionsTradesResponse = await this.makeRequest(\n '/options/trades',\n 'GET',\n requestParams,\n 'v1beta1'\n );\n\n if (!response.trades) {\n log(`No options trades data found in response for ${symbols.length} symbols`, { type: 'warn' });\n break;\n }\n\n // Combine trades for each symbol\n let pageTradesCount = 0;\n let earliestTimestamp: Date | null = null;\n let latestTimestamp: Date | null = null;\n\n Object.entries(response.trades).forEach(([symbol, trades]) => {\n if (trades && trades.length > 0) {\n allTrades[symbol] = [...allTrades[symbol], ...trades];\n pageTradesCount += trades.length;\n\n // Track date range for this page\n trades.forEach((trade) => {\n const tradeDate = new Date(trade.t);\n if (!earliestTimestamp || tradeDate < earliestTimestamp) {\n earliestTimestamp = tradeDate;\n }\n if (!latestTimestamp || tradeDate > latestTimestamp) {\n latestTimestamp = tradeDate;\n }\n });\n }\n });\n\n totalTradesCount += pageTradesCount;\n pageToken = response.next_page_token || null;\n hasMorePages = !!pageToken;\n\n // Enhanced logging with date range and progress info\n const dateRangeStr =\n earliestTimestamp && latestTimestamp\n ? `${(earliestTimestamp as Date).toLocaleDateString('en-US', { timeZone: 'America/New_York' })} to ${(\n latestTimestamp as Date\n ).toLocaleDateString('en-US', { timeZone: 'America/New_York' })}`\n : 'unknown range';\n\n log(\n `Page ${pageCount}: Fetched ${pageTradesCount.toLocaleString()} option trades (total: ${totalTradesCount.toLocaleString()}) for ${\n symbols.length\n } symbols, date range: ${dateRangeStr}${hasMorePages ? ', more pages available' : ', complete'}`,\n {\n type: 'debug',\n }\n );\n\n // Prevent infinite loops\n if (pageCount > 1000) {\n log(`Stopping options trades pagination after ${pageCount} pages to prevent infinite loop`, { type: 'warn' });\n break;\n }\n }\n\n // Final summary\n const symbolCounts = Object.entries(allTrades)\n .map(([symbol, trades]) => `${symbol}: ${trades.length}`)\n .join(', ');\n log(\n `Options trades fetch complete: ${totalTradesCount.toLocaleString()} total trades across ${pageCount} pages (${symbolCounts})`\n );\n\n return {\n trades: allTrades,\n next_page_token: undefined, // Always undefined since we fetch all pages\n };\n }\n\n /**\n * Get snapshots for option contract symbols\n * Provides latest trade, latest quote, and greeks for each contract symbol\n * @param params Options snapshots request parameters\n * @returns Snapshot data for each option contract symbol\n \n * @see https://docs.alpaca.markets/reference/optionsnapshots\n */\n async getOptionsSnapshot(params: OptionsSnapshotsParams): Promise<OptionsSnapshotsResponse> {\n // Remove limit and page_token as they may not be supported by this endpoint\n const { limit, page_token, ...requestParams } = params;\n return this.makeRequest('/options/snapshots', 'GET', requestParams, 'v1beta1');\n }\n\n /**\n * Get condition codes for options trades or quotes\n * Returns the mapping between condition codes and their descriptions\n * @param tickType The type of tick data ('trade' or 'quote')\n * @returns Mapping of condition codes to descriptions\n \n * @see https://docs.alpaca.markets/reference/optionmetaconditions\n */\n async getOptionsConditionCodes(tickType: OptionTickType): Promise<OptionsConditionCodesResponse> {\n return this.makeRequest(`/options/meta/conditions/${tickType}`, 'GET', undefined, 'v1beta1');\n }\n\n /**\n * Get exchange codes for options\n * Returns the mapping between option exchange codes and exchange names\n * @returns Mapping of exchange codes to exchange names\n \n * @see https://docs.alpaca.markets/reference/optionmetaexchanges\n */\n async getOptionsExchangeCodes(): Promise<OptionsExchangeCodesResponse> {\n return this.makeRequest('/options/meta/exchanges', 'GET', undefined, 'v1beta1');\n }\n\n /**\n * Analyzes an array of option bars and returns a summary string\n * @param bars Array of option bars to analyze\n * @returns A string summarizing the option price data\n */\n static analyzeOptionBars(bars: OptionBar[]): string {\n if (!bars || bars.length === 0) {\n return 'No option price data available';\n }\n\n const firstBar = bars[0];\n const lastBar = bars[bars.length - 1];\n const priceChange = lastBar.c - firstBar.o;\n const percentChange = (priceChange / firstBar.o) * 100;\n\n const volumeChange = lastBar.v - firstBar.v;\n const percentVolumeChange = firstBar.v > 0 ? (volumeChange / firstBar.v) * 100 : 0;\n\n const high = Math.max(...bars.map((bar) => bar.h));\n const low = Math.min(...bars.map((bar) => bar.l));\n const totalVolume = bars.reduce((sum, bar) => sum + bar.v, 0);\n const avgVolume = totalVolume / bars.length;\n\n return (\n `Option Price: $${firstBar.o.toFixed(2)} -> $${lastBar.c.toFixed(2)} (${percentChange.toFixed(2)}%), ` +\n `Volume: ${firstBar.v.toLocaleString()} -> ${lastBar.v.toLocaleString()} (${percentVolumeChange.toFixed(2)}%), ` +\n `High: $${high.toFixed(2)}, Low: $${low.toFixed(2)}, ` +\n `Avg Volume: ${avgVolume.toLocaleString()}`\n );\n }\n\n /**\n * Formats option greeks for display\n * @param greeks Option greeks object\n * @returns Formatted string with greek values\n */\n static formatOptionGreeks(greeks: any): string {\n if (!greeks) {\n return 'No greeks data available';\n }\n\n const parts: string[] = [];\n if (greeks.delta !== undefined) parts.push(`Delta: ${greeks.delta.toFixed(4)}`);\n if (greeks.gamma !== undefined) parts.push(`Gamma: ${greeks.gamma.toFixed(4)}`);\n if (greeks.theta !== undefined) parts.push(`Theta: ${greeks.theta.toFixed(4)}`);\n if (greeks.vega !== undefined) parts.push(`Vega: ${greeks.vega.toFixed(4)}`);\n if (greeks.rho !== undefined) parts.push(`Rho: ${greeks.rho.toFixed(4)}`);\n\n return parts.length > 0 ? parts.join(', ') : 'No greeks data available';\n }\n\n /**\n * Interprets condition codes using the provided condition codes mapping\n * @param conditionCodes Array of condition codes from trade or quote\n * @param conditionCodesMap Mapping of condition codes to descriptions\n * @returns Formatted string with condition descriptions\n */\n static interpretConditionCodes(conditionCodes: string[], conditionCodesMap: OptionsConditionCodesResponse): string {\n if (!conditionCodes || conditionCodes.length === 0) {\n return 'No conditions';\n }\n\n const descriptions = conditionCodes\n .map((code) => conditionCodesMap[code] || `Unknown (${code})`)\n .filter((desc) => desc !== undefined);\n\n return descriptions.length > 0 ? descriptions.join(', ') : 'No condition descriptions available';\n }\n\n /**\n * Gets the exchange name from exchange code using the provided exchange codes mapping\n * @param exchangeCode Exchange code from trade or quote\n * @param exchangeCodesMap Mapping of exchange codes to names\n * @returns Exchange name or formatted unknown exchange\n */\n static getExchangeName(exchangeCode: string, exchangeCodesMap: OptionsExchangeCodesResponse): string {\n return exchangeCodesMap[exchangeCode] || `Unknown Exchange (${exchangeCode})`;\n }\n\n /**\n * Fetches news articles from Alpaca API for a symbol, paginating through all results.\n * @param symbol The symbol to fetch news for (e.g., 'AAPL')\n * @param params Optional parameters: start, end, limit, sort, include_content\n * @returns Array of SimpleNews articles\n */\n async fetchNews(\n symbol: string,\n params?: {\n start?: Date | string;\n end?: Date | string;\n limit?: number;\n sort?: 'asc' | 'desc';\n include_content?: boolean;\n }\n ): Promise<SimpleNews[]> {\n const defaultParams = {\n start: new Date(Date.now() - 24 * 60 * 60 * 1000),\n end: new Date(),\n limit: 10,\n sort: 'desc' as const,\n include_content: true,\n };\n const mergedParams = { ...defaultParams, ...params };\n let newsArticles: SimpleNews[] = [];\n let pageToken: string | null = null;\n let hasMorePages = true;\n let fetchedCount = 0;\n const maxLimit = mergedParams.limit;\n\n // Utility to clean content\n function cleanContent(content: string | undefined): string | undefined {\n if (!content) return undefined;\n // Remove excessive whitespace, newlines, and trim\n return content.replace(/\\s+/g, ' ').trim();\n }\n\n while (hasMorePages) {\n const queryParams: URLSearchParams = new URLSearchParams({\n ...(mergedParams.start && { start: new Date(mergedParams.start).toISOString() }),\n ...(mergedParams.end && { end: new Date(mergedParams.end).toISOString() }),\n ...(symbol && { symbols: symbol }),\n ...(mergedParams.limit && { limit: Math.min(50, maxLimit - fetchedCount).toString() }),\n ...(mergedParams.sort && { sort: mergedParams.sort }),\n ...(mergedParams.include_content !== undefined\n ? { include_content: mergedParams.include_content.toString() }\n : {}),\n ...(pageToken && { page_token: pageToken }),\n });\n const url: string = `${this.v1beta1url}/news?${queryParams}`;\n log(`Fetching news from: ${url}`, { type: 'debug', symbol });\n const response: Response = await fetch(url, {\n method: 'GET',\n headers: this.headers,\n });\n if (!response.ok) {\n const errorText = await response.text();\n log(`Alpaca news API error (${response.status}): ${errorText}`, { type: 'error', symbol });\n throw new Error(`Alpaca news API error (${response.status}): ${errorText}`);\n }\n const data: { news: AlpacaNewsArticle[]; next_page_token: string | null } = await response.json();\n if (!data.news || !Array.isArray(data.news)) {\n log(`No news data found in Alpaca response for ${symbol}`, { type: 'warn', symbol });\n break;\n }\n const transformedNews: SimpleNews[] = data.news.map((article: AlpacaNewsArticle) => ({\n symbols: article.symbols,\n title: article.headline,\n summary: cleanContent(article.summary) ?? '',\n content: article.content ? cleanContent(article.content) : undefined,\n url: article.url,\n source: article.source,\n author: article.author,\n date: article.updated_at || article.created_at,\n updatedDate: article.updated_at || article.created_at,\n sentiment: 0,\n }));\n newsArticles = newsArticles.concat(transformedNews);\n fetchedCount = newsArticles.length;\n pageToken = data.next_page_token || null;\n hasMorePages = !!pageToken && (!maxLimit || fetchedCount < maxLimit);\n log(\n `Fetched ${transformedNews.length} news articles (total: ${fetchedCount}) for ${symbol}. More pages: ${hasMorePages}`,\n { type: 'debug', symbol }\n );\n if (maxLimit && fetchedCount >= maxLimit) {\n newsArticles = newsArticles.slice(0, maxLimit);\n break;\n }\n }\n return newsArticles;\n }\n\n // ===== CRYPTO MARKET DATA METHODS =====\n\n /**\n * Get historical OHLCV bars for crypto symbols\n * Automatically handles pagination to fetch all available data\n * @param params Parameters for crypto historical bars request\n * @returns Historical bars data with all pages combined\n */\n async getCryptoHistoricalBars(params: CryptoHistoricalBarsParams): Promise<CryptoHistoricalBarsResponse> {\n const symbols = params.symbols;\n const symbolsStr = symbols.join(',');\n let allBars: { [symbol: string]: Bar[] } = {};\n let pageToken: string | null = null;\n let hasMorePages = true;\n let totalBarsCount = 0;\n let pageCount = 0;\n\n // Initialize bar arrays for each symbol\n symbols.forEach((symbol) => {\n allBars[symbol] = [];\n });\n\n log(\n `Starting crypto historical bars fetch for ${symbols.length} symbols (${params.timeframe}, ${params.start || 'no start'} to ${params.end || 'no end'})`\n );\n\n while (hasMorePages) {\n pageCount++;\n const requestParams = {\n ...params,\n symbols: symbolsStr,\n ...(pageToken && { page_token: pageToken }),\n };\n\n const response: CryptoHistoricalBarsResponse = await this.makeRequest(\n '/crypto/us/bars',\n 'GET',\n requestParams,\n 'v1beta3'\n );\n\n if (!response.bars) {\n log(`No crypto bars data found in response for ${symbols.length} symbols`, { type: 'warn' });\n break;\n }\n\n // Combine bars for each symbol\n let pageBarsCount = 0;\n Object.entries(response.bars).forEach(([symbol, bars]) => {\n if (bars && bars.length > 0) {\n allBars[symbol] = [...allBars[symbol], ...bars];\n pageBarsCount += bars.length;\n }\n });\n\n totalBarsCount += pageBarsCount;\n pageToken = response.next_page_token || null;\n hasMorePages = !!pageToken;\n\n log(\n `Page ${pageCount}: Fetched ${pageBarsCount.toLocaleString()} crypto bars (total: ${totalBarsCount.toLocaleString()}) for ${symbols.length} symbols${hasMorePages ? ', more pages available' : ', complete'}`, { type: 'debug' }\n );\n\n // Prevent infinite loops\n if (pageCount > 1000) {\n log(`Stopping crypto bars pagination after ${pageCount} pages to prevent infinite loop`, { type: 'warn' });\n break;\n }\n }\n\n log(\n `Crypto historical bars fetch complete: ${totalBarsCount.toLocaleString()} total bars across ${pageCount} pages`\n );\n\n return {\n bars: allBars,\n next_page_token: null, // Always null since we fetch all pages\n };\n }\n\n /**\n * Get the most recent minute bar for requested crypto symbols\n * @param symbols Array of crypto symbols to query\n * @returns Latest bar data for each symbol\n */\n async getCryptoLatestBars(symbols: string[]): Promise<CryptoLatestBarsResponse> {\n return this.makeRequest('/crypto/us/latest/bars', 'GET', { symbols: symbols.join(',') }, 'v1beta3');\n }\n\n /**\n * Get historical quotes for crypto symbols\n * Automatically handles pagination to fetch all available data\n * @param params Parameters for crypto historical quotes request\n * @returns Historical quotes data with all pages combined\n */\n async getCryptoHistoricalQuotes(params: CryptoHistoricalQuotesParams): Promise<CryptoHistoricalQuotesResponse> {\n const symbols = params.symbols;\n const symbolsStr = symbols.join(',');\n let allQuotes: { [symbol: string]: CryptoQuote[] } = {};\n let pageToken: string | null = null;\n let hasMorePages = true;\n let totalQuotesCount = 0;\n let pageCount = 0;\n\n // Initialize quotes arrays for each symbol\n symbols.forEach((symbol) => {\n allQuotes[symbol] = [];\n });\n\n log(\n `Starting crypto historical quotes fetch for ${symbols.length} symbols (${params.start || 'no start'} to ${params.end || 'no end'})`\n );\n\n while (hasMorePages) {\n pageCount++;\n const requestParams = {\n ...params,\n symbols: symbolsStr,\n ...(pageToken && { page_token: pageToken }),\n };\n\n const response: CryptoHistoricalQuotesResponse = await this.makeRequest(\n '/crypto/us/quotes',\n 'GET',\n requestParams,\n 'v1beta3'\n );\n\n if (!response.quotes) {\n log(`No crypto quotes data found in response for ${symbols.length} symbols`, { type: 'warn' });\n break;\n }\n\n // Combine quotes for each symbol\n let pageQuotesCount = 0;\n Object.entries(response.quotes).forEach(([symbol, quotes]) => {\n if (quotes && quotes.length > 0) {\n allQuotes[symbol] = [...allQuotes[symbol], ...quotes];\n pageQuotesCount += quotes.length;\n }\n });\n\n totalQuotesCount += pageQuotesCount;\n pageToken = response.next_page_token || null;\n hasMorePages = !!pageToken;\n\n log(\n `Page ${pageCount}: Fetched ${pageQuotesCount.toLocaleString()} crypto quotes (total: ${totalQuotesCount.toLocaleString()}) for ${symbols.length} symbols${hasMorePages ? ', more pages available' : ', complete'}`, { type: 'debug' }\n );\n\n // Prevent infinite loops\n if (pageCount > 1000) {\n log(`Stopping crypto quotes pagination after ${pageCount} pages to prevent infinite loop`, { type: 'warn' });\n break;\n }\n }\n\n log(\n `Crypto historical quotes fetch complete: ${totalQuotesCount.toLocaleString()} total quotes across ${pageCount} pages`\n );\n\n return {\n quotes: allQuotes,\n next_page_token: null, // Always null since we fetch all pages\n };\n }\n\n /**\n * Get the most recent quotes for requested crypto symbols\n * @param symbols Array of crypto symbols to query\n * @returns Latest quote data for each symbol\n */\n async getCryptoLatestQuotes(symbols: string[]): Promise<CryptoLatestQuotesResponse> {\n if (!symbols || symbols.length === 0) {\n log('No symbols provided to getCryptoLatestQuotes, returning empty response', { type: 'warn' });\n return { quotes: {} };\n }\n\n return this.makeRequest('/crypto/us/latest/quotes', 'GET', { symbols: symbols.join(',') }, 'v1beta3');\n }\n\n /**\n * Get historical trades for crypto symbols\n * Automatically handles pagination to fetch all available data\n * @param params Parameters for crypto historical trades request\n * @returns Historical trades data with all pages combined\n */\n async getCryptoHistoricalTrades(params: CryptoHistoricalTradesParams): Promise<CryptoHistoricalTradesResponse> {\n const symbols = params.symbols;\n const symbolsStr = symbols.join(',');\n let allTrades: { [symbol: string]: CryptoTrade[] } = {};\n let pageToken: string | null = null;\n let hasMorePages = true;\n let totalTradesCount = 0;\n let pageCount = 0;\n\n // Initialize trades arrays for each symbol\n symbols.forEach((symbol) => {\n allTrades[symbol] = [];\n });\n\n log(\n `Starting crypto historical trades fetch for ${symbols.length} symbols (${params.start || 'no start'} to ${params.end || 'no end'})`\n );\n\n while (hasMorePages) {\n pageCount++;\n const requestParams = {\n ...params,\n symbols: symbolsStr,\n ...(pageToken && { page_token: pageToken }),\n };\n\n const response: CryptoHistoricalTradesResponse = await this.makeRequest(\n '/crypto/us/trades',\n 'GET',\n requestParams,\n 'v1beta3'\n );\n\n if (!response.trades) {\n log(`No crypto trades data found in response for ${symbols.length} symbols`, { type: 'warn' });\n break;\n }\n\n // Combine trades for each symbol\n let pageTradesCount = 0;\n Object.entries(response.trades).forEach(([symbol, trades]) => {\n if (trades && trades.length > 0) {\n allTrades[symbol] = [...allTrades[symbol], ...trades];\n pageTradesCount += trades.length;\n }\n });\n\n totalTradesCount += pageTradesCount;\n pageToken = response.next_page_token || null;\n hasMorePages = !!pageToken;\n\n log(\n `Page ${pageCount}: Fetched ${pageTradesCount.toLocaleString()} crypto trades (total: ${totalTradesCount.toLocaleString()}) for ${symbols.length} symbols${hasMorePages ? ', more pages available' : ', complete'}`, { type: 'debug' }\n );\n\n // Prevent infinite loops\n if (pageCount > 1000) {\n log(`Stopping crypto trades pagination after ${pageCount} pages to prevent infinite loop`, { type: 'warn' });\n break;\n }\n }\n\n log(\n `Crypto historical trades fetch complete: ${totalTradesCount.toLocaleString()} total trades across ${pageCount} pages`\n );\n\n return {\n trades: allTrades,\n next_page_token: null, // Always null since we fetch all pages\n };\n }\n\n /**\n * Get the most recent trades for requested crypto symbols\n * @param symbols Array of crypto symbols to query\n * @returns Latest trade data for each symbol\n */\n async getCryptoLatestTrades(symbols: string[]): Promise<CryptoLatestTradesResponse> {\n if (!symbols || symbols.length === 0) {\n log('No symbols provided to getCryptoLatestTrades, returning empty response', { type: 'warn' });\n return { trades: {} };\n }\n\n return this.makeRequest('/crypto/us/latest/trades', 'GET', { symbols: symbols.join(',') }, 'v1beta3');\n }\n\n /**\n * Get snapshots for crypto symbols\n * Returns the latest trade, latest quote, latest minute bar, latest daily bar, and previous daily bar data\n * @param symbols Array of crypto symbols to query\n * @returns Snapshot data for each symbol\n */\n async getCryptoSnapshots(symbols: string[]): Promise<CryptoSnapshotsResponse> {\n if (!symbols || symbols.length === 0) {\n log('No symbols provided to getCryptoSnapshots, returning empty response', { type: 'warn' });\n return { snapshots: {} };\n }\n\n return this.makeRequest('/crypto/us/snapshots', 'GET', { symbols: symbols.join(',') }, 'v1beta3');\n }\n\n /**\n * Get the latest orderbook for requested crypto symbols\n * @param symbols Array of crypto symbols to query\n * @returns Latest orderbook data for each symbol\n */\n async getCryptoLatestOrderbooks(symbols: string[]): Promise<CryptoLatestOrderbooksResponse> {\n if (!symbols || symbols.length === 0) {\n log('No symbols provided to getCryptoLatestOrderbooks, returning empty response', { type: 'warn' });\n return { orderbooks: {} };\n }\n\n return this.makeRequest('/crypto/us/latest/orderbooks', 'GET', { symbols: symbols.join(',') }, 'v1beta3');\n }\n\n /**\n * Analyzes an array of crypto bars and returns a summary string\n * @param bars Array of crypto bars to analyze\n * @returns A string summarizing the crypto price data\n */\n static analyzeCryptoBars(bars: Bar[]): string {\n if (!bars || bars.length === 0) {\n return 'No crypto price data available';\n }\n\n const firstBar = bars[0];\n const lastBar = bars[bars.length - 1];\n const priceChange = lastBar.c - firstBar.o;\n const percentChange = (priceChange / firstBar.o) * 100;\n\n const volumeChange = lastBar.v - firstBar.v;\n const percentVolumeChange = firstBar.v > 0 ? (volumeChange / firstBar.v) * 100 : 0;\n\n const high = Math.max(...bars.map((bar) => bar.h));\n const low = Math.min(...bars.map((bar) => bar.l));\n const totalVolume = bars.reduce((sum, bar) => sum + bar.v, 0);\n const avgVolume = totalVolume / bars.length;\n\n return (\n `Crypto Price: $${firstBar.o.toFixed(6)} -> $${lastBar.c.toFixed(6)} (${percentChange.toFixed(2)}%), ` +\n `Volume: ${firstBar.v.toLocaleString()} -> ${lastBar.v.toLocaleString()} (${percentVolumeChange.toFixed(2)}%), ` +\n `High: $${high.toFixed(6)}, Low: $${low.toFixed(6)}, ` +\n `Avg Volume: ${avgVolume.toLocaleString()}`\n );\n }\n}\n\n// Export the singleton instance\nexport const marketDataAPI = AlpacaMarketDataAPI.getInstance();\n", "import WebSocket from 'ws';\nimport { log as baseLog } from './logging';\nimport {\n AlpacaAccountDetails,\n AlpacaAPIErrorResponse,\n AlpacaCredentials,\n AlpacaRequestContext,\n AlpacaPosition,\n AssetClass,\n GetOptionContractsParams,\n GetOrdersParams,\n JsonObject,\n JsonValue,\n OptionAccountActivity,\n OptionContract,\n OptionContractsResponse,\n AlpacaOrder,\n OrderLeg,\n TradeUpdate,\n CreateOrderParams,\n CreateMultiLegOrderParams,\n PortfolioHistoryResponse,\n EquitiesTradeOptions,\n} from './types/alpaca-types';\nimport { LogOptions } from './types/logging-types';\nimport { marketDataAPI } from './alpaca-market-data-api';\nimport { getTradingDate } from './market-time';\n\nconst limitPriceSlippagePercent100 = 0.1; // 0.1%\n\ntype AlpacaRequestBody = CreateOrderParams | CreateMultiLegOrderParams | JsonObject;\n\nclass AlpacaRequestError extends Error {\n readonly method: string;\n readonly status: number | null;\n readonly url: string;\n readonly responseCode: number | null;\n readonly responseDetails: AlpacaAPIErrorResponse | null;\n readonly rawResponse: string | null;\n readonly symbol?: string;\n\n constructor(params: {\n message: string;\n method: string;\n status?: number;\n url: string;\n responseCode?: number | null;\n responseDetails?: AlpacaAPIErrorResponse | null;\n rawResponse?: string | null;\n symbol?: string;\n }) {\n super(params.message);\n this.name = 'AlpacaRequestError';\n this.method = params.method;\n this.status = params.status ?? null;\n this.url = params.url;\n this.responseCode = params.responseCode ?? null;\n this.responseDetails = params.responseDetails ?? null;\n this.rawResponse = params.rawResponse ?? null;\n this.symbol = params.symbol;\n }\n}\n\n/** \nWebsocket example\n const alpacaAPI = createAlpacaTradingAPI(credentials); // type AlpacaCredentials\n alpacaAPI.onTradeUpdate((update: TradeUpdate) => {\n this.log(`Received trade update: event ${update.event} for an order to ${update.order.side} ${update.order.qty} of ${update.order.symbol}`);\n });\n alpacaAPI.connectWebsocket(); // necessary to connect to the WebSocket\n\nPortfolio History examples\n // Get standard portfolio history\n const portfolioHistory = await alpacaAPI.getPortfolioHistory({\n timeframe: '1D',\n period: '1M'\n });\n\n // Get daily portfolio history with current day included (if available from hourly data)\n const dailyHistory = await alpacaAPI.getPortfolioDailyHistory({\n period: '1M'\n });\n*/\n\nexport class AlpacaTradingAPI {\n static new(credentials: AlpacaCredentials): AlpacaTradingAPI {\n return new AlpacaTradingAPI(credentials) as AlpacaTradingAPI;\n }\n\n static getInstance(credentials: AlpacaCredentials): AlpacaTradingAPI {\n return new AlpacaTradingAPI(credentials) as AlpacaTradingAPI;\n }\n\n private ws: WebSocket | null = null;\n private headers: Record<string, string>;\n private tradeUpdateCallback: ((update: TradeUpdate) => void) | null = null;\n private credentials: AlpacaCredentials;\n private apiBaseUrl: string;\n private wsUrl: string;\n private authenticated = false;\n private connecting = false;\n private reconnectDelay = 10000; // 10 seconds between reconnection attempts\n private reconnectTimeout: NodeJS.Timeout | null = null;\n private messageHandlers: Map<string, (data: any) => void> = new Map();\n private debugLogging = false;\n private manualDisconnect = false;\n\n /**\n * Constructor for AlpacaTradingAPI\n * @param credentials - Alpaca credentials,\n * accountName: string; // The account identifier used inthis.logs and tracking\n * apiKey: string; // Alpaca API key\n * apiSecret: string; // Alpaca API secret\n * type: AlpacaAccountType;\n * orderType: AlpacaOrderType;\n * @param options - Optional options\n * debugLogging: boolean; // Whether to log messages of type 'debug'\n */\n constructor(credentials: AlpacaCredentials, options?: { debugLogging?: boolean }) {\n this.credentials = credentials;\n\n // Set URLs based on account type\n this.apiBaseUrl =\n credentials.type === 'PAPER' ? 'https://paper-api.alpaca.markets/v2' : 'https://api.alpaca.markets/v2';\n\n this.wsUrl =\n credentials.type === 'PAPER' ? 'wss://paper-api.alpaca.markets/stream' : 'wss://api.alpaca.markets/stream';\n\n this.headers = {\n 'APCA-API-KEY-ID': credentials.apiKey,\n 'APCA-API-SECRET-KEY': credentials.apiSecret,\n 'Content-Type': 'application/json',\n };\n\n // Initialize message handlers\n this.messageHandlers.set('authorization', this.handleAuthMessage.bind(this));\n this.messageHandlers.set('listening', this.handleListenMessage.bind(this));\n this.messageHandlers.set('trade_updates', this.handleTradeUpdate.bind(this));\n\n this.debugLogging = options?.debugLogging || false;\n }\n\n private log(message: string, options: LogOptions = { type: 'info' }): void {\n if (this.debugLogging && options.type === 'debug') {\n return;\n }\n baseLog(message, { ...options, source: 'AlpacaTradingAPI', account: this.credentials.accountName });\n }\n\n /**\n * Round a price to the nearest 2 decimal places for Alpaca, or 4 decimal places for prices less than $1\n * @param price - The price to round\n * @returns The rounded price\n */\n private roundPriceForAlpaca = (price: number): number => {\n return price >= 1 ? Math.round(price * 100) / 100 : Math.round(price * 10000) / 10000;\n };\n\n private isJsonObject(value: JsonValue): value is JsonObject {\n return value !== null && !Array.isArray(value) && typeof value === 'object';\n }\n\n private parseAlpacaAPIErrorResponse(rawResponse: string): AlpacaAPIErrorResponse | null {\n if (rawResponse.trim() === '') {\n return null;\n }\n\n try {\n const parsedValue = JSON.parse(rawResponse) as JsonValue;\n if (!this.isJsonObject(parsedValue)) {\n return null;\n }\n\n const code = parsedValue['code'];\n const message = parsedValue['message'];\n const symbol = parsedValue['symbol'];\n\n if (typeof code !== 'number' || typeof message !== 'string') {\n return null;\n }\n\n if (symbol !== undefined && typeof symbol !== 'string') {\n return null;\n }\n\n return parsedValue as AlpacaAPIErrorResponse;\n } catch {\n return null;\n }\n }\n\n private formatJsonValueForLog(value: JsonValue | undefined): string {\n if (value === undefined) {\n return 'undefined';\n }\n\n if (Array.isArray(value)) {\n return value.map((entry) => this.formatJsonValueForLog(entry)).join(', ');\n }\n\n if (value === null) {\n return 'null';\n }\n\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n\n return `${value}`;\n }\n\n private formatAlpacaAPIErrorDetails(errorResponse: AlpacaAPIErrorResponse): string {\n return Object.entries(errorResponse)\n .filter(([key]) => key !== 'code' && key !== 'message' && key !== 'symbol')\n .map(([key, value]) => `${key}=${this.formatJsonValueForLog(value)}`)\n .join(', ');\n }\n\n private formatRequestAction(requestContext?: AlpacaRequestContext): string {\n return requestContext?.action ? `${requestContext.action} failed` : 'Alpaca request failed';\n }\n\n private buildAlpacaAPIErrorMessage(params: {\n requestContext?: AlpacaRequestContext;\n status: number;\n url: string;\n errorResponse: AlpacaAPIErrorResponse | null;\n rawResponse: string;\n }): string {\n const { requestContext, status, url, errorResponse, rawResponse } = params;\n const action = this.formatRequestAction(requestContext);\n const message = errorResponse?.message ?? (rawResponse || 'No error body returned');\n const responseCode = errorResponse?.code ? ` (code ${errorResponse.code})` : '';\n const detailSummary = errorResponse ? this.formatAlpacaAPIErrorDetails(errorResponse) : '';\n const detailText =\n detailSummary !== ''\n ? ` Details: ${detailSummary}.`\n : rawResponse.trim() !== '' && errorResponse === null\n ? ` Response: ${rawResponse}.`\n : '';\n\n return `${action}: Alpaca API ${status}${responseCode}: ${message}.${detailText} Url: ${url}`;\n }\n\n private buildRequestExecutionErrorMessage(params: {\n requestContext?: AlpacaRequestContext;\n url: string;\n errorMessage: string;\n }): string {\n const { requestContext, url, errorMessage } = params;\n const action = this.formatRequestAction(requestContext);\n return `${action}: ${errorMessage}. Url: ${url}`;\n }\n\n private handleAuthMessage(data: any): void {\n if (data.status === 'authorized') {\n this.authenticated = true;\n this.log('WebSocket authenticated');\n } else {\n this.log(`Authentication failed: ${data.message || 'Unknown error'}`, {\n type: 'error',\n });\n }\n }\n\n private handleListenMessage(data: any): void {\n if (data.streams?.includes('trade_updates')) {\n this.log('Successfully subscribed to trade updates');\n }\n }\n\n private handleTradeUpdate(data: TradeUpdate): void {\n if (this.tradeUpdateCallback) {\n this.log(\n `Trade update: ${data.event} to ${data.order.side} ${data.order.qty} shares${\n data.event === 'partial_fill' ? ` (filled shares: ${data.order.filled_qty})` : ''\n }, type ${data.order.type}`,\n {\n symbol: data.order.symbol,\n type: 'debug',\n }\n );\n this.tradeUpdateCallback(data);\n }\n }\n\n private handleMessage(message: string): void {\n try {\n const data = JSON.parse(message);\n const handler = this.messageHandlers.get(data.stream);\n\n if (handler) {\n handler(data.data);\n } else {\n this.log(`Received message for unknown stream: ${data.stream}`, {\n type: 'warn',\n });\n }\n } catch (error) {\n this.log('Failed to parse WebSocket message', {\n type: 'error',\n metadata: { error: error instanceof Error ? error.message : 'Unknown error' },\n });\n }\n }\n\n connectWebsocket(): void {\n // Reset manual disconnect flag to allow reconnection logic\n this.manualDisconnect = false;\n if (this.connecting) {\n this.log('Connection attempt skipped - already connecting');\n return;\n }\n\n if (this.ws?.readyState === WebSocket.OPEN) {\n this.log('Connection attempt skipped - already connected');\n return;\n }\n\n this.connecting = true;\n\n if (this.ws) {\n this.ws.removeAllListeners();\n this.ws.terminate();\n this.ws = null;\n }\n\n this.log(`Connecting to WebSocket at ${this.wsUrl}...`);\n\n this.ws = new WebSocket(this.wsUrl);\n\n this.ws.on('open', async () => {\n try {\n this.log('WebSocket connected');\n await this.authenticate();\n await this.subscribeToTradeUpdates();\n this.connecting = false;\n } catch (error) {\n this.log('Failed to setup WebSocket connection', {\n type: 'error',\n metadata: { error: error instanceof Error ? error.message : 'Unknown error' },\n });\n this.ws?.close();\n }\n });\n\n this.ws.on('message', (data: WebSocket.Data) => {\n this.handleMessage(data.toString());\n });\n\n this.ws.on('error', (error) => {\n this.log('WebSocket error', {\n type: 'error',\n metadata: { error: error instanceof Error ? error.message : 'Unknown error' },\n });\n this.connecting = false;\n });\n\n this.ws.on('close', () => {\n this.log('WebSocket connection closed');\n this.authenticated = false;\n this.connecting = false;\n\n // Clear any existing reconnect timeout\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n\n // Schedule reconnection unless this was a manual disconnect\n if (!this.manualDisconnect) {\n this.reconnectTimeout = setTimeout(() => {\n this.log('Attempting to reconnect...');\n this.connectWebsocket();\n }, this.reconnectDelay);\n }\n });\n }\n\n /**\n * Cleanly disconnect from the WebSocket and stop auto-reconnects\n */\n disconnect(): void {\n // Prevent auto-reconnect scheduling\n this.manualDisconnect = true;\n\n // Clear any scheduled reconnect\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n\n if (this.ws) {\n this.log('Disconnecting WebSocket...');\n\n // Remove listeners first to avoid duplicate handlers after reconnects\n this.ws.removeAllListeners();\n\n try {\n // Attempt graceful close\n if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {\n this.ws.close(1000, 'Client disconnect');\n } else {\n this.ws.terminate();\n }\n } catch {\n // Fallback terminate on any error\n try {\n this.ws.terminate();\n } catch {\n /* no-op */\n }\n }\n\n this.ws = null;\n }\n\n this.authenticated = false;\n this.connecting = false;\n this.log('WebSocket disconnected');\n }\n\n private async authenticate(): Promise<void> {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new Error('WebSocket not ready for authentication');\n }\n\n const authMessage = {\n action: 'auth',\n key: this.credentials.apiKey,\n secret: this.credentials.apiSecret,\n };\n\n this.ws.send(JSON.stringify(authMessage));\n\n return new Promise((resolve, reject) => {\n const authTimeout = setTimeout(() => {\n this.log('Authentication timeout', { type: 'error' });\n reject(new Error('Authentication timed out'));\n }, 10000);\n\n const handleAuthResponse = (data: WebSocket.Data) => {\n try {\n const message = JSON.parse(data.toString());\n if (message.stream === 'authorization') {\n this.ws?.removeListener('message', handleAuthResponse);\n clearTimeout(authTimeout);\n\n if (message.data?.status === 'authorized') {\n this.authenticated = true;\n resolve();\n } else {\n const error = `Authentication failed: ${message.data?.message || 'Unknown error'}`;\n this.log(error, { type: 'error' });\n reject(new Error(error));\n }\n }\n } catch (error) {\n this.log('Failed to parse auth response', {\n type: 'error',\n metadata: { error: error instanceof Error ? error.message : 'Unknown error' },\n });\n }\n };\n\n this.ws?.on('message', handleAuthResponse);\n });\n }\n\n private async subscribeToTradeUpdates(): Promise<void> {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN || !this.authenticated) {\n throw new Error('WebSocket not ready for subscription');\n }\n\n const listenMessage = {\n action: 'listen',\n data: {\n streams: ['trade_updates'],\n },\n };\n\n this.ws.send(JSON.stringify(listenMessage));\n\n return new Promise((resolve, reject) => {\n const listenTimeout = setTimeout(() => {\n reject(new Error('Subscribe timeout'));\n }, 10000);\n\n const handleListenResponse = (data: WebSocket.Data) => {\n try {\n const message = JSON.parse(data.toString());\n if (message.stream === 'listening') {\n this.ws?.removeListener('message', handleListenResponse);\n clearTimeout(listenTimeout);\n\n if (message.data?.streams?.includes('trade_updates')) {\n resolve();\n } else {\n reject(new Error('Failed to subscribe to trade updates'));\n }\n }\n } catch (error) {\n this.log('Failed to parse listen response', {\n type: 'error',\n metadata: { error: error instanceof Error ? error.message : 'Unknown error' },\n });\n }\n };\n\n this.ws?.on('message', handleListenResponse);\n });\n }\n\n private async makeRequest<TResponse>(\n endpoint: string,\n method: string = 'GET',\n body?: AlpacaRequestBody,\n queryString: string = '',\n requestContext?: AlpacaRequestContext\n ): Promise<TResponse> {\n const url = `${this.apiBaseUrl}${endpoint}${queryString}`;\n try {\n const response = await fetch(url, {\n method,\n headers: this.headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const rawResponse = await response.text();\n const errorResponse = this.parseAlpacaAPIErrorResponse(rawResponse);\n const symbol = requestContext?.symbol ?? errorResponse?.symbol;\n const error = new AlpacaRequestError({\n message: this.buildAlpacaAPIErrorMessage({\n requestContext,\n status: response.status,\n url,\n errorResponse,\n rawResponse,\n }),\n method,\n status: response.status,\n url,\n responseCode: errorResponse?.code ?? null,\n responseDetails: errorResponse,\n rawResponse,\n symbol,\n });\n\n this.log(error.message, { symbol, type: 'error' });\n throw error;\n }\n\n // Handle responses with no content (e.g., 204 No Content)\n if (response.status === 204 || response.headers.get('content-length') === '0') {\n return null as TResponse;\n }\n\n const contentType = response.headers.get('content-type');\n if (contentType && contentType.includes('application/json')) {\n return (await response.json()) as TResponse;\n }\n\n // For non-JSON responses, return the text content\n const textContent = await response.text();\n return (textContent || null) as TResponse;\n } catch (error) {\n if (error instanceof AlpacaRequestError) {\n throw error;\n }\n\n const normalizedError = error instanceof Error ? error : new Error(`${error}`);\n const symbol = requestContext?.symbol;\n const requestError = new AlpacaRequestError({\n message: this.buildRequestExecutionErrorMessage({\n requestContext,\n url,\n errorMessage: normalizedError.message,\n }),\n method,\n url,\n rawResponse: null,\n symbol,\n });\n\n this.log(requestError.message, { symbol, type: 'error' });\n throw requestError;\n }\n }\n\n async getPositions(assetClass?: AssetClass): Promise<AlpacaPosition[]> {\n const positions = await this.makeRequest<AlpacaPosition[]>('/positions', 'GET', undefined, '', {\n action: 'Get positions',\n });\n if (assetClass) {\n return positions.filter((position) => position.asset_class === assetClass);\n }\n return positions;\n }\n\n /**\n * Get all orders\n * @param params (GetOrdersParams) - optional parameters to filter the orders\n * - status: 'open' | 'closed' | 'all'\n * - limit: number\n * - after: string\n * - until: string\n * - direction: 'asc' | 'desc'\n * - nested: boolean\n * - symbols: string[], an array of all the symbols\n * - side: 'buy' | 'sell'\n * @returns all orders\n */\n async getOrders(params: GetOrdersParams = {}): Promise<AlpacaOrder[]> {\n const queryParams = new URLSearchParams();\n\n if (params.status) queryParams.append('status', params.status);\n if (params.limit) queryParams.append('limit', params.limit.toString());\n if (params.after) queryParams.append('after', params.after);\n if (params.until) queryParams.append('until', params.until);\n if (params.direction) queryParams.append('direction', params.direction);\n if (params.nested) queryParams.append('nested', params.nested.toString());\n if (params.symbols) queryParams.append('symbols', params.symbols.join(','));\n if (params.side) queryParams.append('side', params.side);\n\n const endpoint = `/orders${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;\n return this.makeRequest<AlpacaOrder[]>(endpoint, 'GET', undefined, '', {\n action: 'Get orders',\n symbol: params.symbols?.join(','),\n });\n }\n\n async getAccountDetails(): Promise<AlpacaAccountDetails> {\n return this.makeRequest<AlpacaAccountDetails>('/account', 'GET', undefined, '', {\n action: 'Get account details',\n });\n }\n\n /**\n * Create a trailing stop order\n * @param symbol (string) - the symbol of the order\n * @param qty (number) - the quantity of the order\n * @param side (string) - the side of the order\n * @param trailPercent100 (number) - the trail percent of the order (scale 100, i.e. 0.5 = 0.5%)\n * @param position_intent (string) - the position intent of the order\n * @param client_order_id (string) - optional client order id\n * @returns The created trailing stop order\n */\n async createTrailingStop(\n symbol: string,\n qty: number,\n side: 'buy' | 'sell',\n trailPercent100: number,\n position_intent: 'buy_to_open' | 'buy_to_close' | 'sell_to_open' | 'sell_to_close',\n client_order_id?: string\n ): Promise<AlpacaOrder> {\n this.log(\n `Creating trailing stop ${side.toUpperCase()} ${qty} shares for ${symbol} with trail percent ${trailPercent100}%`,\n {\n symbol,\n }\n );\n\n const body: CreateOrderParams = {\n symbol,\n qty: Math.abs(qty).toString(),\n side,\n position_intent,\n order_class: 'simple',\n type: 'trailing_stop',\n trail_percent: trailPercent100.toString(),\n time_in_force: 'gtc',\n };\n if (client_order_id !== undefined) {\n body.client_order_id = client_order_id;\n }\n return this.makeRequest<AlpacaOrder>('/orders', 'POST', body, '', {\n action: 'Create trailing stop order',\n symbol,\n });\n }\n\n /**\n * Create a stop order (stop or stop-limit)\n * @param symbol (string) - the symbol of the order\n * @param qty (number) - the quantity of the order\n * @param side (string) - the side of the order\n * @param stopPrice (number) - the stop price that triggers the order\n * @param position_intent (string) - the position intent of the order\n * @param limitPrice (number) - optional limit price (if provided, creates a stop-limit order)\n * @param client_order_id (string) - optional client order id\n * @returns The created stop order\n */\n async createStopOrder(\n symbol: string,\n qty: number,\n side: 'buy' | 'sell',\n stopPrice: number,\n position_intent: 'buy_to_open' | 'buy_to_close' | 'sell_to_open' | 'sell_to_close',\n limitPrice?: number,\n client_order_id?: string\n ): Promise<AlpacaOrder> {\n const isStopLimit = limitPrice !== undefined;\n const orderType = isStopLimit ? 'stop-limit' : 'stop';\n\n this.log(\n `Creating ${orderType} ${side.toUpperCase()} ${qty} shares for ${symbol} with stop price ${stopPrice}${isStopLimit ? ` and limit price ${limitPrice}` : ''}`,\n {\n symbol,\n }\n );\n\n const body: CreateOrderParams = {\n symbol,\n qty: Math.abs(qty).toString(),\n side,\n position_intent,\n order_class: 'simple',\n type: isStopLimit ? 'stop_limit' : 'stop',\n stop_price: this.roundPriceForAlpaca(stopPrice).toString(),\n time_in_force: 'gtc',\n };\n\n if (limitPrice !== undefined) {\n body.limit_price = this.roundPriceForAlpaca(limitPrice).toString();\n }\n\n if (client_order_id !== undefined) {\n body.client_order_id = client_order_id;\n }\n\n return this.makeRequest<AlpacaOrder>('/orders', 'POST', body, '', {\n action: `Create ${orderType} order`,\n symbol,\n });\n }\n\n /**\n * Create a market order\n * @param symbol (string) - the symbol of the order\n * @param qty (number) - the quantity of the order\n * @param side (string) - the side of the order\n * @param position_intent (string) - the position intent of the order. Important for knowing if a position needs a trailing stop.\n * @param client_order_id (string) - optional client order id\n */\n async createMarketOrder(\n symbol: string,\n qty: number,\n side: 'buy' | 'sell',\n position_intent: 'buy_to_open' | 'buy_to_close' | 'sell_to_open' | 'sell_to_close',\n client_order_id?: string\n ): Promise<AlpacaOrder> {\n this.log(`Creating market order for ${symbol}: ${side} ${qty} shares (${position_intent})`, {\n symbol,\n });\n\n const body: CreateOrderParams = {\n symbol,\n qty: Math.abs(qty).toString(),\n side,\n position_intent,\n type: 'market',\n time_in_force: 'day',\n order_class: 'simple',\n };\n if (client_order_id !== undefined) {\n body.client_order_id = client_order_id;\n }\n return this.makeRequest<AlpacaOrder>('/orders', 'POST', body, '', {\n action: 'Create market order',\n symbol,\n });\n }\n\n /**\n * Create a Market on Open (MOO) order - executes in the opening auction\n *\n * IMPORTANT TIMING CONSTRAINTS:\n * - Valid submission window: After 7:00pm ET and before 9:28am ET\n * - Orders submitted between 9:28am and 7:00pm ET will be REJECTED\n * - Orders submitted after 7:00pm ET are queued for the next trading day's opening auction\n * - Example: An order at 8:00pm Monday will execute at Tuesday's market open (9:30am)\n *\n * @param symbol - The symbol of the order\n * @param qty - The quantity of shares\n * @param side - Buy or sell\n * @param position_intent - The position intent (buy_to_open, sell_to_close, etc.)\n * @param client_order_id - Optional client order id\n * @returns The created order\n */\n async createMOOOrder(\n symbol: string,\n qty: number,\n side: 'buy' | 'sell',\n position_intent: 'buy_to_open' | 'buy_to_close' | 'sell_to_open' | 'sell_to_close',\n client_order_id?: string\n ): Promise<AlpacaOrder> {\n this.log(`Creating Market on Open order for ${symbol}: ${side} ${qty} shares (${position_intent})`, {\n symbol,\n });\n\n const body: CreateOrderParams = {\n symbol,\n qty: Math.abs(qty).toString(),\n side,\n position_intent,\n type: 'market',\n time_in_force: 'opg',\n order_class: 'simple',\n };\n if (client_order_id !== undefined) {\n body.client_order_id = client_order_id;\n }\n return this.makeRequest<AlpacaOrder>('/orders', 'POST', body, '', {\n action: 'Create market on open order',\n symbol,\n });\n }\n\n /**\n * Create a Market on Close (MOC) order - executes in the closing auction\n *\n * IMPORTANT TIMING CONSTRAINTS:\n * - Valid submission window: After 7:00pm ET (previous day) and before 3:50pm ET (same day)\n * - Orders submitted between 3:50pm and 7:00pm ET will be REJECTED\n * - Orders submitted after 7:00pm ET are queued for the next trading day's closing auction\n * - Example: An order at 8:00pm Monday will execute at Tuesday's market close (4:00pm)\n *\n * @param symbol - The symbol of the order\n * @param qty - The quantity of shares\n * @param side - Buy or sell\n * @param position_intent - The position intent (buy_to_open, sell_to_close, etc.)\n * @param client_order_id - Optional client order id\n * @returns The created order\n */\n async createMOCOrder(\n symbol: string,\n qty: number,\n side: 'buy' | 'sell',\n position_intent: 'buy_to_open' | 'buy_to_close' | 'sell_to_open' | 'sell_to_close',\n client_order_id?: string\n ): Promise<AlpacaOrder> {\n this.log(`Creating Market on Close order for ${symbol}: ${side} ${qty} shares (${position_intent})`, {\n symbol,\n });\n\n const body: CreateOrderParams = {\n symbol,\n qty: Math.abs(qty).toString(),\n side,\n position_intent,\n type: 'market',\n time_in_force: 'cls',\n order_class: 'simple',\n };\n if (client_order_id !== undefined) {\n body.client_order_id = client_order_id;\n }\n return this.makeRequest<AlpacaOrder>('/orders', 'POST', body, '', {\n action: 'Create market on close order',\n symbol,\n });\n }\n\n /**\n * Create an OCO (One-Cancels-Other) order with take profit and stop loss\n * @param symbol (string) - the symbol of the order\n * @param qty (number) - the quantity of the order\n * @param side (string) - the side of the order (buy or sell)\n * @param position_intent (string) - the position intent of the order\n * @param limitPrice (number) - the limit price for the entry order (OCO orders must be limit orders)\n * @param takeProfitPrice (number) - the take profit price\n * @param stopLossPrice (number) - the stop loss price\n * @param stopLossLimitPrice (number) - optional limit price for stop loss (creates stop-limit instead of stop)\n * @param client_order_id (string) - optional client order id\n * @returns The created OCO order\n */\n async createOCOOrder(\n symbol: string,\n qty: number,\n side: 'buy' | 'sell',\n position_intent: 'buy_to_open' | 'buy_to_close' | 'sell_to_open' | 'sell_to_close',\n limitPrice: number,\n takeProfitPrice: number,\n stopLossPrice: number,\n stopLossLimitPrice?: number,\n client_order_id?: string\n ): Promise<AlpacaOrder> {\n this.log(\n `Creating OCO order ${side.toUpperCase()} ${qty} shares for ${symbol} at limit ${limitPrice} with take profit ${takeProfitPrice} and stop loss ${stopLossPrice}`,\n {\n symbol,\n }\n );\n\n const body: CreateOrderParams = {\n symbol,\n qty: Math.abs(qty).toString(),\n side,\n position_intent,\n order_class: 'oco',\n type: 'limit',\n limit_price: this.roundPriceForAlpaca(limitPrice).toString(),\n time_in_force: 'gtc',\n take_profit: {\n limit_price: this.roundPriceForAlpaca(takeProfitPrice).toString(),\n },\n stop_loss: {\n stop_price: this.roundPriceForAlpaca(stopLossPrice).toString(),\n },\n };\n\n // If stop loss limit price is provided, create stop-limit order\n if (stopLossLimitPrice !== undefined) {\n body.stop_loss = {\n stop_price: this.roundPriceForAlpaca(stopLossPrice).toString(),\n limit_price: this.roundPriceForAlpaca(stopLossLimitPrice).toString(),\n };\n }\n\n if (client_order_id !== undefined) {\n body.client_order_id = client_order_id;\n }\n\n return this.makeRequest<AlpacaOrder>('/orders', 'POST', body, '', {\n action: 'Create OCO order',\n symbol,\n });\n }\n\n /**\n * Get the current trail percent for a symbol, assuming that it has an open position and a trailing stop order to close it. Because this relies on an orders request for one symbol, you can't do it too often.\n * @param symbol (string) - the symbol of the order\n * @returns the current trail percent\n */\n async getCurrentTrailPercent(symbol: string): Promise<number | null> {\n const orders = await this.getOrders({\n status: 'open',\n symbols: [symbol],\n });\n\n const trailingStopOrder = orders.find(\n (order) =>\n order.type === 'trailing_stop' &&\n (order.position_intent === 'sell_to_close' || order.position_intent === 'buy_to_close')\n );\n\n if (!trailingStopOrder) {\n this.log(`No closing trailing stop order found for ${symbol}`, {\n symbol,\n });\n return null;\n }\n\n if (!trailingStopOrder.trail_percent) {\n this.log(`Trailing stop order found for ${symbol} but no trail_percent value`, {\n symbol,\n });\n return null;\n }\n\n const trailPercent = parseFloat(trailingStopOrder.trail_percent);\n return trailPercent;\n }\n\n /**\n * Update the trail percent for a trailing stop order\n * @param symbol (string) - the symbol of the order\n * @param trailPercent100 (number) - the trail percent of the order (scale 100, i.e. 0.5 = 0.5%)\n */\n async updateTrailingStop(symbol: string, trailPercent100: number): Promise<void> {\n // First get all open orders for this symbol\n const orders = await this.getOrders({\n status: 'open',\n symbols: [symbol],\n });\n\n // Find the trailing stop order\n const trailingStopOrder = orders.find((order) => order.type === 'trailing_stop');\n\n if (!trailingStopOrder) {\n this.log(`No open trailing stop order found for ${symbol}`, { type: 'error', symbol });\n return;\n }\n\n // Check if the trail_percent is already set to the desired value\n const currentTrailPercent = trailingStopOrder.trail_percent ? parseFloat(trailingStopOrder.trail_percent) : null;\n\n // Compare with a small epsilon to handle floating point precision\n const epsilon = 0.0001;\n if (currentTrailPercent !== null && Math.abs(currentTrailPercent - trailPercent100) < epsilon) {\n this.log(\n `Trailing stop for ${symbol} already set to ${trailPercent100}% (current: ${currentTrailPercent}%), skipping update`,\n {\n symbol,\n }\n );\n return;\n }\n\n this.log(`Updating trailing stop for ${symbol} from ${currentTrailPercent}% to ${trailPercent100}%`, {\n symbol,\n });\n\n await this.makeRequest<AlpacaOrder>(\n `/orders/${trailingStopOrder.id}`,\n 'PATCH',\n { trail: trailPercent100.toString() },\n '',\n {\n action: 'Update trailing stop order',\n symbol,\n }\n );\n }\n\n /**\n * Cancel all open orders\n */\n async cancelAllOrders(): Promise<void> {\n this.log(`Canceling all open orders`);\n try {\n await this.makeRequest<null>('/orders', 'DELETE', undefined, '', {\n action: 'Cancel all open orders',\n });\n } catch (error) {\n if (!(error instanceof AlpacaRequestError)) {\n this.log(`Error canceling all orders: ${error instanceof Error ? error.message : `${error}`}`, {\n type: 'error',\n });\n }\n }\n }\n\n /**\n * Cancel a specific order by its ID\n * @param orderId The id of the order to cancel\n * @throws Error if the order is not cancelable (status 422) or if the order doesn't exist\n * @returns Promise that resolves when the order is successfully canceled\n */\n async cancelOrder(orderId: string): Promise<void> {\n this.log(`Attempting to cancel order ${orderId}`);\n\n try {\n await this.makeRequest<null>(`/orders/${orderId}`, 'DELETE', undefined, '', {\n action: `Cancel order ${orderId}`,\n });\n this.log(`Successfully canceled order ${orderId}`);\n } catch (error) {\n // If the error is a 422, it means the order is not cancelable\n if (error instanceof AlpacaRequestError && error.status === 422) {\n throw new Error(`Order ${orderId} is not cancelable`);\n }\n // Re-throw other errors\n throw error;\n }\n }\n\n /**\n * Create a limit order\n * @param symbol (string) - the symbol of the order\n * @param qty (number) - the quantity of the order\n * @param side (string) - the side of the order\n * @param limitPrice (number) - the limit price of the order\n * @param position_intent (string) - the position intent of the order\n * @param extended_hours (boolean) - whether the order is in extended hours\n * @param client_order_id (string) - the client order id of the order\n */\n async createLimitOrder(\n symbol: string,\n qty: number,\n side: 'buy' | 'sell',\n limitPrice: number,\n position_intent: 'buy_to_open' | 'buy_to_close' | 'sell_to_open' | 'sell_to_close',\n extended_hours: boolean = false,\n client_order_id?: string\n ): Promise<AlpacaOrder> {\n this.log(\n `Creating limit order for ${symbol}: ${side} ${qty} shares at $${limitPrice.toFixed(2)} (${position_intent})`,\n {\n symbol,\n }\n );\n\n const body: CreateOrderParams = {\n symbol,\n qty: Math.abs(qty).toString(),\n side,\n position_intent,\n type: 'limit',\n limit_price: this.roundPriceForAlpaca(limitPrice).toString(),\n time_in_force: 'day',\n order_class: 'simple',\n extended_hours,\n };\n if (client_order_id !== undefined) {\n body.client_order_id = client_order_id;\n }\n return this.makeRequest<AlpacaOrder>('/orders', 'POST', body, '', {\n action: 'Create limit order',\n symbol,\n });\n }\n\n /**\n * Close all equities positions\n * @param options (object) - the options for closing the positions\n * - cancel_orders (boolean) - whether to cancel related orders\n * - useLimitOrders (boolean) - whether to use limit orders to close the positions\n */\n async closeAllPositions(\n options: { cancel_orders: boolean; useLimitOrders: boolean } = { cancel_orders: true, useLimitOrders: false }\n ): Promise<void> {\n this.log(\n `Closing all positions${options.useLimitOrders ? ' using limit orders' : ''}${\n options.cancel_orders ? ' and canceling open orders' : ''\n }`\n );\n\n if (options.useLimitOrders) {\n // Get all positions\n const positions = await this.getPositions('us_equity');\n\n if (positions.length === 0) {\n this.log('No positions to close');\n return;\n }\n\n this.log(`Found ${positions.length} positions to close`);\n\n // Get latest quotes for all positions\n const symbols = positions.map((position) => position.symbol);\n const quotesResponse = await marketDataAPI.getLatestQuotes(symbols);\n\n const lengthOfQuotes = Object.keys(quotesResponse.quotes).length;\n if (lengthOfQuotes === 0) {\n this.log('No quotes available for positions, received 0 quotes', {\n type: 'error',\n });\n return;\n }\n\n if (lengthOfQuotes !== positions.length) {\n this.log(\n `Received ${lengthOfQuotes} quotes for ${positions.length} positions, expected ${positions.length} quotes`,\n { type: 'warn' }\n );\n return;\n }\n\n // Create limit orders to close each position\n for (const position of positions) {\n const quote = quotesResponse.quotes[position.symbol];\n if (!quote) {\n this.log(`No quote available for ${position.symbol}, skipping limit order`, {\n symbol: position.symbol,\n type: 'warn',\n });\n continue;\n }\n\n const qty = Math.abs(parseFloat(position.qty));\n const side = position.side === 'long' ? 'sell' : 'buy';\n const positionIntent = side === 'sell' ? 'sell_to_close' : 'buy_to_close';\n\n // Get the current price from the quote\n const currentPrice = side === 'sell' ? quote.bp : quote.ap; // Use bid for sells, ask for buys\n\n if (!currentPrice) {\n this.log(`No valid price available for ${position.symbol}, skipping limit order`, {\n symbol: position.symbol,\n type: 'warn',\n });\n continue;\n }\n\n // Apply slippage from config\n const limitSlippagePercent1 = limitPriceSlippagePercent100 / 100;\n const limitPrice =\n side === 'sell'\n ? this.roundPriceForAlpaca(currentPrice * (1 - limitSlippagePercent1)) // Sell slightly lower\n : this.roundPriceForAlpaca(currentPrice * (1 + limitSlippagePercent1)); // Buy slightly higher\n\n this.log(\n `Creating limit order to close ${position.symbol} position: ${side} ${qty} shares at $${limitPrice.toFixed(\n 2\n )}`,\n {\n symbol: position.symbol,\n }\n );\n\n await this.createLimitOrder(position.symbol, qty, side, limitPrice, positionIntent);\n }\n } else {\n await this.makeRequest<null>('/positions', 'DELETE', undefined, options.cancel_orders ? '?cancel_orders=true' : '', {\n action: 'Close all positions',\n });\n }\n }\n\n /**\n * Close all equities positions using limit orders during extended hours trading\n * @param cancelOrders Whether to cancel related orders (default: true)\n * @returns Promise that resolves when all positions are closed\n */\n async closeAllPositionsAfterHours(): Promise<void> {\n this.log('Closing all positions using limit orders during extended hours trading');\n\n // Get all positions\n const positions = await this.getPositions();\n this.log(`Found ${positions.length} positions to close`);\n\n if (positions.length === 0) {\n this.log('No positions to close');\n return;\n }\n\n await this.cancelAllOrders();\n this.log(`Cancelled all open orders`);\n\n // Get latest quotes for all positions\n const symbols = positions.map((position) => position.symbol);\n const quotesResponse = await marketDataAPI.getLatestQuotes(symbols);\n\n // Create limit orders to close each position\n for (const position of positions) {\n const quote = quotesResponse.quotes[position.symbol];\n if (!quote) {\n this.log(`No quote available for ${position.symbol}, skipping limit order`, {\n symbol: position.symbol,\n type: 'warn',\n });\n continue;\n }\n\n const qty = Math.abs(parseFloat(position.qty));\n const side = position.side === 'long' ? 'sell' : 'buy';\n const positionIntent = side === 'sell' ? 'sell_to_close' : 'buy_to_close';\n\n // Get the current price from the quote\n const currentPrice = side === 'sell' ? quote.bp : quote.ap; // Use bid for sells, ask for buys\n\n if (!currentPrice) {\n this.log(`No valid price available for ${position.symbol}, skipping limit order`, {\n symbol: position.symbol,\n type: 'warn',\n });\n continue;\n }\n\n // Apply slippage from config\n const limitSlippagePercent1 = limitPriceSlippagePercent100 / 100;\n const limitPrice =\n side === 'sell'\n ? this.roundPriceForAlpaca(currentPrice * (1 - limitSlippagePercent1)) // Sell slightly lower\n : this.roundPriceForAlpaca(currentPrice * (1 + limitSlippagePercent1)); // Buy slightly higher\n\n this.log(\n `Creating extended hours limit order to close ${\n position.symbol\n } position: ${side} ${qty} shares at $${limitPrice.toFixed(2)}`,\n {\n symbol: position.symbol,\n }\n );\n\n await this.createLimitOrder(\n position.symbol,\n qty,\n side,\n limitPrice,\n positionIntent,\n true // Enable extended hours trading\n );\n }\n\n this.log(`All positions closed: ${positions.map((p) => p.symbol).join(', ')}`);\n }\n\n onTradeUpdate(callback: (update: TradeUpdate) => void): void {\n this.tradeUpdateCallback = callback;\n }\n\n /**\n * Get portfolio history for the account\n * @param params Parameters for the portfolio history request\n * @returns Portfolio history data\n */\n async getPortfolioHistory(params: {\n timeframe?: '1Min' | '5Min' | '15Min' | '1H' | '1D';\n period?: string;\n start?: string; // Start date in ISO format\n end?: string; // End date in ISO format\n extended_hours?: boolean;\n date_end?: string;\n }): Promise<PortfolioHistoryResponse> {\n const queryParams = new URLSearchParams();\n if (params.timeframe) queryParams.append('timeframe', params.timeframe);\n if (params.period) queryParams.append('period', params.period);\n if (params.extended_hours !== undefined) queryParams.append('extended_hours', params.extended_hours.toString());\n if (params.start) queryParams.append('start', params.start);\n if (params.end) queryParams.append('end', params.end);\n if (params.date_end) queryParams.append('date_end', params.date_end);\n\n const response = await this.makeRequest<PortfolioHistoryResponse>(\n `/account/portfolio/history?${queryParams.toString()}`,\n 'GET',\n undefined,\n '',\n {\n action: 'Get portfolio history',\n }\n );\n return response;\n }\n\n /**\n * Get portfolio daily history for the account, ensuring the most recent day is included\n * by combining daily and hourly history if needed.\n *\n * This function performs two API calls:\n * 1. Retrieves daily portfolio history\n * 2. Retrieves hourly portfolio history to check for more recent data\n *\n * If hourly history has timestamps more recent than the last timestamp in daily history,\n * it appends one additional day to the daily history using the most recent hourly values.\n *\n * @param params Parameters for the portfolio history request (same as getPortfolioHistory except timeframe is forced to '1D')\n * @returns Portfolio history data with daily timeframe, including the most recent day if available from hourly data\n */\n async getPortfolioDailyHistory(params: {\n period?: string;\n start?: string; // Start date in ISO format\n end?: string; // End date in ISO format\n extended_hours?: boolean;\n date_end?: string;\n }): Promise<PortfolioHistoryResponse> {\n // Get daily and hourly history in parallel\n const dailyParams = { ...params, timeframe: '1D' as const };\n const hourlyParams = { timeframe: '1Min' as const, period: '1D' };\n\n const [dailyHistory, hourlyHistory] = await Promise.all([\n this.getPortfolioHistory(dailyParams),\n this.getPortfolioHistory(hourlyParams),\n ]);\n\n // If no hourly history, return daily as-is\n if (!hourlyHistory.timestamp || hourlyHistory.timestamp.length === 0) {\n return dailyHistory;\n }\n\n // Get the last timestamp from daily history\n const lastDailyTimestamp = dailyHistory.timestamp[dailyHistory.timestamp.length - 1];\n\n // Check if hourly history has more recent data\n const recentHourlyData = hourlyHistory.timestamp\n .map((timestamp, index) => ({ timestamp, index }))\n .filter(({ timestamp }) => timestamp > lastDailyTimestamp);\n\n // If no more recent hourly data, return daily history as-is\n if (recentHourlyData.length === 0) {\n return dailyHistory;\n }\n\n // Get the most recent hourly data point\n const mostRecentHourly = recentHourlyData[recentHourlyData.length - 1];\n const mostRecentIndex = mostRecentHourly.index;\n\n // Calculate the timestamp for the new daily entry.\n // Alpaca's daily history timestamps are at 00:00:00Z for the calendar day\n // following the NY trading date. Derive the trading date in NY time from the\n // most recent intraday timestamp, then set the new daily timestamp to\n // midnight UTC of the next calendar day.\n const mostRecentMs = mostRecentHourly.timestamp * 1000; // hourly timestamps are seconds\n const tradingDateStr = getTradingDate(new Date(mostRecentMs)); // e.g., '2025-09-05' (NY trading date)\n const [yearStr, monthStr, dayStr] = tradingDateStr.split('-');\n const year = Number(yearStr);\n const month = Number(monthStr); // 1-based\n const day = Number(dayStr);\n const newDailyTimestamp = Math.floor(Date.UTC(year, month - 1, day + 1, 0, 0, 0, 0) / 1000);\n\n // Create a new daily history entry with the most recent hourly values\n const updatedDailyHistory: PortfolioHistoryResponse = {\n ...dailyHistory,\n timestamp: [...dailyHistory.timestamp, newDailyTimestamp],\n equity: [...dailyHistory.equity, hourlyHistory.equity[mostRecentIndex]],\n profit_loss: [...dailyHistory.profit_loss, hourlyHistory.profit_loss[mostRecentIndex]],\n profit_loss_pct: [...dailyHistory.profit_loss_pct, hourlyHistory.profit_loss_pct[mostRecentIndex]],\n };\n\n return updatedDailyHistory;\n }\n\n /**\n * Get option contracts based on specified parameters\n * @param params Parameters to filter option contracts\n * @returns Option contracts matching the criteria\n */\n async getOptionContracts(params: GetOptionContractsParams): Promise<OptionContractsResponse> {\n const queryParams = new URLSearchParams();\n\n queryParams.append('underlying_symbols', params.underlying_symbols.join(','));\n\n if (params.expiration_date_gte) queryParams.append('expiration_date_gte', params.expiration_date_gte);\n if (params.expiration_date_lte) queryParams.append('expiration_date_lte', params.expiration_date_lte);\n if (params.strike_price_gte) queryParams.append('strike_price_gte', params.strike_price_gte);\n if (params.strike_price_lte) queryParams.append('strike_price_lte', params.strike_price_lte);\n if (params.type) queryParams.append('type', params.type);\n if (params.status) queryParams.append('status', params.status);\n if (params.limit) queryParams.append('limit', params.limit.toString());\n if (params.page_token) queryParams.append('page_token', params.page_token);\n\n this.log(`Fetching option contracts for ${params.underlying_symbols.join(', ')}`, {\n symbol: params.underlying_symbols.join(', '),\n });\n\n const response = await this.makeRequest<OptionContractsResponse>(\n `/options/contracts?${queryParams.toString()}`,\n 'GET',\n undefined,\n '',\n {\n action: 'Get option contracts',\n symbol: params.underlying_symbols.join(', '),\n }\n );\n this.log(`Found ${response.option_contracts.length} option contracts`, {\n symbol: params.underlying_symbols.join(', '),\n });\n return response;\n }\n\n /**\n * Get a specific option contract by symbol or ID\n * @param symbolOrId The symbol or ID of the option contract\n * @returns The option contract details\n */\n async getOptionContract(symbolOrId: string): Promise<OptionContract> {\n this.log(`Fetching option contract details for ${symbolOrId}`, {\n symbol: symbolOrId,\n });\n const response = await this.makeRequest<OptionContract>(`/options/contracts/${symbolOrId}`, 'GET', undefined, '', {\n action: 'Get option contract details',\n symbol: symbolOrId,\n });\n this.log(`Found option contract details for ${symbolOrId}: ${response.name}`, {\n symbol: symbolOrId,\n });\n return response;\n }\n\n /**\n * Create a simple option order (market or limit)\n * @param symbol Option contract symbol\n * @param qty Quantity of contracts (must be a whole number)\n * @param side Buy or sell\n * @param position_intent Position intent (buy_to_open, buy_to_close, sell_to_open, sell_to_close)\n * @param type Order type (market or limit)\n * @param limitPrice Limit price (required for limit orders)\n * @returns The created order\n */\n async createOptionOrder(\n symbol: string,\n qty: number,\n side: 'buy' | 'sell',\n position_intent: 'buy_to_open' | 'buy_to_close' | 'sell_to_open' | 'sell_to_close',\n type: 'market' | 'limit',\n limitPrice?: number\n ): Promise<AlpacaOrder> {\n if (!Number.isInteger(qty) || qty <= 0) {\n this.log('Quantity must be a positive whole number for option orders', { symbol, type: 'error' });\n }\n\n if (type === 'limit' && limitPrice === undefined) {\n this.log('Limit price is required for limit orders', { symbol, type: 'error' });\n }\n\n this.log(\n `Creating ${type} option order for ${symbol}: ${side} ${qty} contracts (${position_intent})${\n type === 'limit' ? ` at $${limitPrice?.toFixed(2)}` : ''\n }`,\n {\n symbol,\n }\n );\n\n const orderData: CreateOrderParams = {\n symbol,\n qty: qty.toString(),\n side,\n position_intent,\n type,\n time_in_force: 'day',\n order_class: 'simple',\n extended_hours: false,\n };\n\n if (type === 'limit' && limitPrice !== undefined) {\n orderData.limit_price = this.roundPriceForAlpaca(limitPrice).toString();\n }\n\n return this.makeRequest<AlpacaOrder>('/orders', 'POST', orderData, '', {\n action: 'Create option order',\n symbol,\n });\n }\n\n /**\n * Create a multi-leg option order\n * @param legs Array of order legs\n * @param qty Quantity of the multi-leg order (must be a whole number)\n * @param type Order type (market or limit)\n * @param limitPrice Limit price (required for limit orders)\n * @returns The created multi-leg order\n */\n async createMultiLegOptionOrder(\n legs: OrderLeg[],\n qty: number,\n type: 'market' | 'limit',\n limitPrice?: number\n ): Promise<AlpacaOrder> {\n const legSymbols = legs.map((leg) => leg.symbol).join(', ');\n\n if (!Number.isInteger(qty) || qty <= 0) {\n this.log('Quantity must be a positive whole number for option orders', {\n symbol: legSymbols,\n type: 'error',\n });\n }\n\n if (type === 'limit' && limitPrice === undefined) {\n this.log('Limit price is required for limit orders', { symbol: legSymbols, type: 'error' });\n }\n\n if (legs.length < 2) {\n this.log('Multi-leg orders require at least 2 legs', { symbol: legSymbols, type: 'error' });\n }\n\n this.log(\n `Creating multi-leg ${type} option order with ${legs.length} legs (${legSymbols})${\n type === 'limit' ? ` at $${limitPrice?.toFixed(2)}` : ''\n }`,\n {\n symbol: legSymbols,\n }\n );\n\n const orderData: CreateMultiLegOrderParams = {\n order_class: 'mleg',\n qty: qty.toString(),\n type,\n time_in_force: 'day',\n legs,\n };\n\n if (type === 'limit' && limitPrice !== undefined) {\n orderData.limit_price = this.roundPriceForAlpaca(limitPrice).toString();\n }\n\n return this.makeRequest<AlpacaOrder>('/orders', 'POST', orderData, '', {\n action: 'Create multi-leg option order',\n symbol: legSymbols,\n });\n }\n\n /**\n * Exercise an option contract\n * @param symbolOrContractId The symbol or ID of the option contract to exercise\n * @returns Response from the exercise request\n */\n async exerciseOption(symbolOrContractId: string): Promise<null> {\n this.log(`Exercising option contract ${symbolOrContractId}`, {\n symbol: symbolOrContractId,\n });\n return this.makeRequest<null>(`/positions/${symbolOrContractId}/exercise`, 'POST', undefined, '', {\n action: 'Exercise option contract',\n symbol: symbolOrContractId,\n });\n }\n\n /**\n * Get option positions\n * @returns Array of option positions\n */\n async getOptionPositions(): Promise<AlpacaPosition[]> {\n this.log('Fetching option positions');\n const positions = await this.getPositions('us_option');\n return positions;\n }\n\n async getOptionsOpenSpreadTrades(): Promise<void> {\n this.log('Fetching option open trades');\n // this function will get all open positions, extract the symbol and see when they were created.\n // figures out when the earliest date was (should be today)\n // then it pulls all orders after the earliest date that were closed and that were of class 'mleg'\n // Each of these contains two orders. they look like this:\n }\n\n /**\n * Get option account activities (exercises, assignments, expirations)\n * @param activityType Type of option activity to filter by\n * @param date Date to filter activities (YYYY-MM-DD format)\n * @returns Array of option account activities\n */\n async getOptionActivities(\n activityType?: 'OPEXC' | 'OPASN' | 'OPEXP',\n date?: string\n ): Promise<OptionAccountActivity[]> {\n const queryParams = new URLSearchParams();\n\n if (activityType) {\n queryParams.append('activity_types', activityType);\n } else {\n queryParams.append('activity_types', 'OPEXC,OPASN,OPEXP');\n }\n\n if (date) {\n queryParams.append('date', date);\n }\n\n this.log(\n `Fetching option activities${activityType ? ` of type ${activityType}` : ''}${date ? ` for date ${date}` : ''}`\n );\n\n return this.makeRequest<OptionAccountActivity[]>(`/account/activities?${queryParams.toString()}`, 'GET', undefined, '', {\n action: 'Get option activities',\n });\n }\n\n /**\n * Create a long call spread (buy lower strike call, sell higher strike call)\n * @param lowerStrikeCallSymbol Symbol of the lower strike call option\n * @param higherStrikeCallSymbol Symbol of the higher strike call option\n * @param qty Quantity of spreads to create (must be a whole number)\n * @param limitPrice Limit price for the spread\n * @returns The created multi-leg order\n */\n async createLongCallSpread(\n lowerStrikeCallSymbol: string,\n higherStrikeCallSymbol: string,\n qty: number,\n limitPrice: number\n ): Promise<AlpacaOrder> {\n this.log(\n `Creating long call spread: Buy ${lowerStrikeCallSymbol}, Sell ${higherStrikeCallSymbol}, Qty: ${qty}, Price: $${limitPrice.toFixed(\n 2\n )}`,\n {\n symbol: `${lowerStrikeCallSymbol},${higherStrikeCallSymbol}`,\n }\n );\n\n const legs: OrderLeg[] = [\n {\n symbol: lowerStrikeCallSymbol,\n ratio_qty: '1',\n side: 'buy',\n position_intent: 'buy_to_open',\n },\n {\n symbol: higherStrikeCallSymbol,\n ratio_qty: '1',\n side: 'sell',\n position_intent: 'sell_to_open',\n },\n ];\n\n return this.createMultiLegOptionOrder(legs, qty, 'limit', limitPrice);\n }\n\n /**\n * Create a long put spread (buy higher strike put, sell lower strike put)\n * @param higherStrikePutSymbol Symbol of the higher strike put option\n * @param lowerStrikePutSymbol Symbol of the lower strike put option\n * @param qty Quantity of spreads to create (must be a whole number)\n * @param limitPrice Limit price for the spread\n * @returns The created multi-leg order\n */\n async createLongPutSpread(\n higherStrikePutSymbol: string,\n lowerStrikePutSymbol: string,\n qty: number,\n limitPrice: number\n ): Promise<AlpacaOrder> {\n this.log(\n `Creating long put spread: Buy ${higherStrikePutSymbol}, Sell ${lowerStrikePutSymbol}, Qty: ${qty}, Price: $${limitPrice.toFixed(\n 2\n )}`,\n {\n symbol: `${higherStrikePutSymbol},${lowerStrikePutSymbol}`,\n }\n );\n\n const legs: OrderLeg[] = [\n {\n symbol: higherStrikePutSymbol,\n ratio_qty: '1',\n side: 'buy',\n position_intent: 'buy_to_open',\n },\n {\n symbol: lowerStrikePutSymbol,\n ratio_qty: '1',\n side: 'sell',\n position_intent: 'sell_to_open',\n },\n ];\n\n return this.createMultiLegOptionOrder(legs, qty, 'limit', limitPrice);\n }\n\n /**\n * Create an iron condor (sell call spread and put spread)\n * @param longPutSymbol Symbol of the lower strike put (long)\n * @param shortPutSymbol Symbol of the higher strike put (short)\n * @param shortCallSymbol Symbol of the lower strike call (short)\n * @param longCallSymbol Symbol of the higher strike call (long)\n * @param qty Quantity of iron condors to create (must be a whole number)\n * @param limitPrice Limit price for the iron condor (credit)\n * @returns The created multi-leg order\n */\n async createIronCondor(\n longPutSymbol: string,\n shortPutSymbol: string,\n shortCallSymbol: string,\n longCallSymbol: string,\n qty: number,\n limitPrice: number\n ): Promise<AlpacaOrder> {\n this.log(`Creating iron condor with ${qty} contracts at $${limitPrice.toFixed(2)}`, {\n symbol: `${longPutSymbol},${shortPutSymbol},${shortCallSymbol},${longCallSymbol}`,\n });\n\n const legs: OrderLeg[] = [\n {\n symbol: longPutSymbol,\n ratio_qty: '1',\n side: 'buy',\n position_intent: 'buy_to_open',\n },\n {\n symbol: shortPutSymbol,\n ratio_qty: '1',\n side: 'sell',\n position_intent: 'sell_to_open',\n },\n {\n symbol: shortCallSymbol,\n ratio_qty: '1',\n side: 'sell',\n position_intent: 'sell_to_open',\n },\n {\n symbol: longCallSymbol,\n ratio_qty: '1',\n side: 'buy',\n position_intent: 'buy_to_open',\n },\n ];\n\n return this.createMultiLegOptionOrder(legs, qty, 'limit', limitPrice);\n }\n\n /**\n * Create a covered call (sell call option against owned stock)\n * @param stockSymbol Symbol of the underlying stock\n * @param callOptionSymbol Symbol of the call option to sell\n * @param qty Quantity of covered calls to create (must be a whole number)\n * @param limitPrice Limit price for the call option\n * @returns The created order\n */\n async createCoveredCall(\n stockSymbol: string,\n callOptionSymbol: string,\n qty: number,\n limitPrice: number\n ): Promise<AlpacaOrder> {\n this.log(\n `Creating covered call: Sell ${callOptionSymbol} against ${stockSymbol}, Qty: ${qty}, Price: $${limitPrice.toFixed(\n 2\n )}`,\n {\n symbol: `${stockSymbol},${callOptionSymbol}`,\n }\n );\n\n // For covered calls, we don't need to include the stock leg if we already own the shares\n // We just create a simple sell order for the call option\n return this.createOptionOrder(callOptionSymbol, qty, 'sell', 'sell_to_open', 'limit', limitPrice);\n }\n\n /**\n * Roll an option position to a new expiration or strike\n * @param currentOptionSymbol Symbol of the current option position\n * @param newOptionSymbol Symbol of the new option to roll to\n * @param qty Quantity of options to roll (must be a whole number)\n * @param currentPositionSide Side of the current position ('buy' or 'sell')\n * @param limitPrice Net limit price for the roll\n * @returns The created multi-leg order\n */\n async rollOptionPosition(\n currentOptionSymbol: string,\n newOptionSymbol: string,\n qty: number,\n currentPositionSide: 'buy' | 'sell',\n limitPrice: number\n ): Promise<AlpacaOrder> {\n this.log(`Rolling ${qty} ${currentOptionSymbol} to ${newOptionSymbol} at net price $${limitPrice.toFixed(2)}`, {\n symbol: `${currentOptionSymbol},${newOptionSymbol}`,\n });\n\n // If current position is long, we need to sell to close and buy to open\n // If current position is short, we need to buy to close and sell to open\n const closePositionSide = currentPositionSide === 'buy' ? 'sell' : 'buy';\n const openPositionSide = currentPositionSide;\n\n const closePositionIntent = closePositionSide === 'buy' ? 'buy_to_close' : 'sell_to_close';\n const openPositionIntent = openPositionSide === 'buy' ? 'buy_to_open' : 'sell_to_open';\n\n const legs: OrderLeg[] = [\n {\n symbol: currentOptionSymbol,\n ratio_qty: '1',\n side: closePositionSide,\n position_intent: closePositionIntent,\n },\n {\n symbol: newOptionSymbol,\n ratio_qty: '1',\n side: openPositionSide,\n position_intent: openPositionIntent,\n },\n ];\n\n return this.createMultiLegOptionOrder(legs, qty, 'limit', limitPrice);\n }\n\n /**\n * Get option chain for a specific underlying symbol and expiration date\n * @param underlyingSymbol The underlying stock symbol\n * @param expirationDate The expiration date (YYYY-MM-DD format)\n * @returns Option contracts for the specified symbol and expiration date\n */\n async getOptionChain(underlyingSymbol: string, expirationDate: string): Promise<OptionContract[]> {\n this.log(`Fetching option chain for ${underlyingSymbol} with expiration date ${expirationDate}`, {\n symbol: underlyingSymbol,\n });\n\n try {\n const params: GetOptionContractsParams = {\n underlying_symbols: [underlyingSymbol],\n expiration_date_gte: expirationDate,\n expiration_date_lte: expirationDate,\n status: 'active',\n limit: 500, // Get a large number to ensure we get all strikes\n };\n\n const response = await this.getOptionContracts(params);\n return response.option_contracts || [];\n } catch (error) {\n if (!(error instanceof AlpacaRequestError)) {\n this.log(\n `Failed to fetch option chain for ${underlyingSymbol}: ${error instanceof Error ? error.message : `${error}`}`,\n {\n type: 'error',\n symbol: underlyingSymbol,\n }\n );\n }\n return [];\n }\n }\n\n /**\n * Get all available expiration dates for a specific underlying symbol\n * @param underlyingSymbol The underlying stock symbol\n * @returns Array of available expiration dates\n */\n async getOptionExpirationDates(underlyingSymbol: string): Promise<string[]> {\n this.log(`Fetching available expiration dates for ${underlyingSymbol}`, {\n symbol: underlyingSymbol,\n });\n\n try {\n const params: GetOptionContractsParams = {\n underlying_symbols: [underlyingSymbol],\n status: 'active',\n limit: 1000, // Get a large number to ensure we get contracts with all expiration dates\n };\n\n const response = await this.getOptionContracts(params);\n\n // Extract unique expiration dates\n const expirationDates = new Set<string>();\n if (response.option_contracts) {\n response.option_contracts.forEach((contract) => {\n expirationDates.add(contract.expiration_date);\n });\n }\n\n // Convert to array and sort\n return Array.from(expirationDates).sort();\n } catch (error) {\n if (!(error instanceof AlpacaRequestError)) {\n this.log(\n `Failed to fetch expiration dates for ${underlyingSymbol}: ${\n error instanceof Error ? error.message : `${error}`\n }`,\n {\n type: 'error',\n symbol: underlyingSymbol,\n }\n );\n }\n return [];\n }\n }\n\n /**\n * Get the current options trading level for the account\n * @returns The options trading level (0-3)\n */\n async getOptionsTradingLevel(): Promise<number> {\n this.log('Fetching options trading level');\n\n const accountDetails = await this.getAccountDetails();\n return accountDetails.options_trading_level || 0;\n }\n\n /**\n * Check if the account has options trading enabled\n * @returns Boolean indicating if options trading is enabled\n */\n async isOptionsEnabled(): Promise<boolean> {\n this.log('Checking if options trading is enabled');\n\n const accountDetails = await this.getAccountDetails();\n\n // Check if options trading level is 2 or higher (Level 2+ allows buying calls/puts)\n // Level 0: Options disabled\n // Level 1: Only covered calls and cash-secured puts\n // Level 2+: Can buy calls and puts (required for executeOptionsOrder)\n const optionsLevel = accountDetails.options_trading_level || 0;\n const isEnabled = optionsLevel >= 2;\n\n this.log(`Options trading level: ${optionsLevel}, enabled: ${isEnabled}`);\n\n return isEnabled;\n }\n\n /**\n * Close all option positions\n * @param cancelOrders Whether to cancel related orders (default: true)\n * @returns Response from the close positions request\n */\n async closeAllOptionPositions(cancelOrders: boolean = true): Promise<void> {\n this.log(`Closing all option positions${cancelOrders ? ' and canceling related orders' : ''}`);\n\n const optionPositions = await this.getOptionPositions();\n\n if (optionPositions.length === 0) {\n this.log('No option positions to close');\n return;\n }\n\n // Create market orders to close each position\n for (const position of optionPositions) {\n const side = position.side === 'long' ? 'sell' : 'buy';\n const positionIntent = side === 'sell' ? 'sell_to_close' : 'buy_to_close';\n\n this.log(`Closing ${position.side} position of ${position.qty} contracts for ${position.symbol}`, {\n symbol: position.symbol,\n });\n\n await this.createOptionOrder(position.symbol, parseInt(position.qty), side, positionIntent, 'market');\n }\n\n if (cancelOrders) {\n // Get all open option orders\n const orders = await this.getOrders({ status: 'open' });\n const optionOrders = orders.filter((order) => order.asset_class === 'us_option');\n\n // Cancel each open option order\n for (const order of optionOrders) {\n this.log(`Canceling open order for ${order.symbol}`, {\n symbol: order.symbol,\n });\n await this.makeRequest<null>(`/orders/${order.id}`, 'DELETE', undefined, '', {\n action: `Cancel option order ${order.id}`,\n symbol: order.symbol,\n });\n }\n }\n }\n\n /**\n * Close a specific option position\n * @param symbol The option contract symbol\n * @param qty Optional quantity to close (defaults to entire position)\n * @returns The created order\n */\n async closeOptionPosition(symbol: string, qty?: number): Promise<AlpacaOrder> {\n this.log(`Closing option position for ${symbol}${qty ? ` (${qty} contracts)` : ''}`, {\n symbol,\n });\n\n // Get the position details\n const positions = await this.getOptionPositions();\n const position = positions.find((p) => p.symbol === symbol);\n\n if (!position) {\n throw new Error(`No position found for option contract ${symbol}`);\n }\n\n const quantityToClose = qty || parseInt(position.qty);\n const side = position.side === 'long' ? 'sell' : 'buy';\n const positionIntent = side === 'sell' ? 'sell_to_close' : 'buy_to_close';\n\n return this.createOptionOrder(symbol, quantityToClose, side, positionIntent, 'market');\n }\n\n /**\n * Create a complete equities trade with optional stop loss and take profit\n * @param params Trade parameters including symbol, qty, side, and optional referencePrice\n * @param options Trade options including order type, extended hours, stop loss, and take profit settings\n * @returns The created order\n */\n async createEquitiesTrade(\n params: {\n symbol: string;\n qty: number;\n side: 'buy' | 'sell';\n referencePrice?: number;\n },\n options?: EquitiesTradeOptions\n ): Promise<AlpacaOrder> {\n const { symbol, qty, side, referencePrice } = params;\n const {\n type = 'market',\n limitPrice,\n extendedHours = false,\n useStopLoss = false,\n stopPrice,\n stopPercent100,\n useTakeProfit = false,\n takeProfitPrice,\n takeProfitPercent100,\n clientOrderId,\n } = options || {};\n\n // Validation: Extended hours + market order is not allowed\n if (extendedHours && type === 'market') {\n this.log('Cannot create market order with extended hours enabled', {\n symbol,\n type: 'error',\n });\n throw new Error('Cannot create market order with extended hours enabled');\n }\n\n // Validation: Limit orders require limit price\n if (type === 'limit' && limitPrice === undefined) {\n this.log('Limit price is required for limit orders', {\n symbol,\n type: 'error',\n });\n throw new Error('Limit price is required for limit orders');\n }\n\n let calculatedStopPrice: number | undefined;\n let calculatedTakeProfitPrice: number | undefined;\n\n // Handle stop loss validation and calculation\n if (useStopLoss) {\n if (stopPrice === undefined && stopPercent100 === undefined) {\n this.log('Either stopPrice or stopPercent100 must be provided when useStopLoss is true', {\n symbol,\n type: 'error',\n });\n throw new Error('Either stopPrice or stopPercent100 must be provided when useStopLoss is true');\n }\n\n if (stopPercent100 !== undefined) {\n if (referencePrice === undefined) {\n this.log('referencePrice is required when using stopPercent100', {\n symbol,\n type: 'error',\n });\n throw new Error('referencePrice is required when using stopPercent100');\n }\n\n // Calculate stop price based on percentage and side\n const stopPercentDecimal = stopPercent100 / 100;\n if (side === 'buy') {\n // For buy orders, stop loss is below the reference price\n calculatedStopPrice = referencePrice * (1 - stopPercentDecimal);\n } else {\n // For sell orders, stop loss is above the reference price\n calculatedStopPrice = referencePrice * (1 + stopPercentDecimal);\n }\n } else {\n calculatedStopPrice = stopPrice;\n }\n }\n\n // Handle take profit validation and calculation\n if (useTakeProfit) {\n if (takeProfitPrice === undefined && takeProfitPercent100 === undefined) {\n this.log('Either takeProfitPrice or takeProfitPercent100 must be provided when useTakeProfit is true', {\n symbol,\n type: 'error',\n });\n throw new Error('Either takeProfitPrice or takeProfitPercent100 must be provided when useTakeProfit is true');\n }\n\n if (takeProfitPercent100 !== undefined) {\n if (referencePrice === undefined) {\n this.log('referencePrice is required when using takeProfitPercent100', {\n symbol,\n type: 'error',\n });\n throw new Error('referencePrice is required when using takeProfitPercent100');\n }\n\n // Calculate take profit price based on percentage and side\n const takeProfitPercentDecimal = takeProfitPercent100 / 100;\n if (side === 'buy') {\n // For buy orders, take profit is above the reference price\n calculatedTakeProfitPrice = referencePrice * (1 + takeProfitPercentDecimal);\n } else {\n // For sell orders, take profit is below the reference price\n calculatedTakeProfitPrice = referencePrice * (1 - takeProfitPercentDecimal);\n }\n } else {\n calculatedTakeProfitPrice = takeProfitPrice;\n }\n }\n\n // Determine order class based on what's enabled\n let orderClass: 'simple' | 'oto' | 'bracket' = 'simple';\n if (useStopLoss && useTakeProfit) {\n orderClass = 'bracket';\n } else if (useStopLoss || useTakeProfit) {\n orderClass = 'oto';\n }\n\n // Build the order request\n const orderData: CreateOrderParams = {\n symbol,\n qty: Math.abs(qty).toString(),\n side,\n type,\n time_in_force: 'day',\n order_class: orderClass,\n extended_hours: extendedHours,\n position_intent: side === 'buy' ? 'buy_to_open' : 'sell_to_open',\n };\n\n if (clientOrderId) {\n orderData.client_order_id = clientOrderId;\n }\n\n // Add limit price for limit orders\n if (type === 'limit' && limitPrice !== undefined) {\n orderData.limit_price = this.roundPriceForAlpaca(limitPrice).toString();\n }\n\n // Add stop loss if enabled\n if (useStopLoss && calculatedStopPrice !== undefined) {\n orderData.stop_loss = {\n stop_price: this.roundPriceForAlpaca(calculatedStopPrice).toString(),\n };\n }\n\n // Add take profit if enabled\n if (useTakeProfit && calculatedTakeProfitPrice !== undefined) {\n orderData.take_profit = {\n limit_price: this.roundPriceForAlpaca(calculatedTakeProfitPrice).toString(),\n };\n }\n\n const logMessage = `Creating ${orderClass} ${type} ${side} order for ${symbol}: ${qty} shares${\n type === 'limit' ? ` at $${limitPrice?.toFixed(2)}` : ''\n }${useStopLoss ? ` with stop loss at $${calculatedStopPrice?.toFixed(2)}` : ''}${\n useTakeProfit ? ` with take profit at $${calculatedTakeProfitPrice?.toFixed(2)}` : ''\n }${extendedHours ? ' (extended hours)' : ''}`;\n\n this.log(logMessage, {\n symbol,\n });\n\n return this.makeRequest<AlpacaOrder>('/orders', 'POST', orderData, '', {\n action: 'Create equities trade',\n symbol,\n });\n }\n}\n", "import * as mt from './market-time';\nimport * as ft from './format-tools';\nimport * as Types from './types';\nimport * as misc from './misc-utils';\nimport * as llm from './llm-openai';\nimport * as llmImages from './llm-images';\nimport * as deepseek from './llm-deepseek';\nimport * as openrouter from './llm-openrouter';\nimport { PerformanceTimer } from './performance-timer';\n\nimport { AlpacaTradingAPI } from './alpaca-trading-api';\nimport { AlpacaMarketDataAPI } from './alpaca-market-data-api';\nimport { getPackedSettings } from 'http2';\n\n// Re-export all types\nexport * from './types';\n\n// Export key classes directly for easier access\nexport { AlpacaTradingAPI } from './alpaca-trading-api';\nexport { AlpacaMarketDataAPI } from './alpaca-market-data-api';\nexport { supportsTemperature, uploadVisionFile } from './llm-openai';\nexport { OPENAI_IMAGE_MODELS, OPENAI_MODELS, OPENROUTER_MODELS } from './types/llm-types';\n\nexport const disco = {\n types: Types,\n alpaca: {\n TradingAPI: AlpacaTradingAPI,\n MarketDataAPI: AlpacaMarketDataAPI,\n },\n format: {\n capFirstLetter: ft.capFirstLetter,\n currency: ft.formatCurrency,\n number: ft.formatNumber,\n pct: ft.formatPercentage,\n dateTimeForGS: ft.dateTimeForGS,\n },\n llm: {\n call: llm.makeLLMCall,\n uploadVisionFile: llm.uploadVisionFile,\n seek: deepseek.makeDeepseekCall,\n images: llmImages.makeImagesCall,\n open: openrouter.makeOpenRouterCall,\n },\n time: {\n convertDateToMarketTimeZone: mt.convertDateToMarketTimeZone,\n getStartAndEndDates: mt.getStartAndEndDates,\n getMarketOpenClose: mt.getMarketOpenClose,\n getOpenCloseForTradingDay: mt.getOpenCloseForTradingDay,\n getLastFullTradingDate: mt.getLastFullTradingDate,\n getNextMarketDay: mt.getNextMarketDay,\n getPreviousMarketDay: mt.getPreviousMarketDay,\n getMarketTimePeriod: mt.getMarketTimePeriod,\n getMarketStatus: mt.getMarketStatus,\n getNYTimeZone: mt.getNYTimeZone,\n getTradingDate: mt.getTradingDate,\n getTradingStartAndEndDates: mt.getTradingStartAndEndDates,\n getTradingDaysBack: mt.getTradingDaysBack,\n isMarketDay: mt.isMarketDay,\n isWithinMarketHours: mt.isWithinMarketHours,\n countTradingDays: mt.countTradingDays,\n MARKET_TIMES: mt.MARKET_TIMES,\n },\n utils: {\n logIfDebug: misc.logIfDebug,\n fetchWithRetry: misc.fetchWithRetry,\n Timer: PerformanceTimer,\n },\n};\n", "// openai-types.ts\nimport type {\n ChatCompletionMessageParam,\n ChatCompletionTool,\n ChatCompletionMessageToolCall,\n} from 'openai/resources/chat/completions';\nimport type { ImageGenerateParams, ImageModel } from 'openai/resources/images';\nimport type { ResponseFormatTextJSONSchemaConfig, ResponseInputImage } from 'openai/resources/responses/responses';\nimport type { ZodType } from 'zod';\n\n/**\n * Represents OpenAI models\n */\nexport const OPENAI_MODELS = [\n 'gpt-5.6',\n 'gpt-5.6-sol',\n 'gpt-5.6-terra',\n 'gpt-5.6-luna',\n 'gpt-5',\n 'gpt-5-mini',\n 'gpt-5.4-mini',\n 'gpt-5.4-nano',\n 'gpt-5-nano',\n 'gpt-5.1',\n 'gpt-5.4',\n 'gpt-5.5',\n 'gpt-5.5-pro',\n 'gpt-5.2',\n 'gpt-5.2-pro',\n 'gpt-5.1-codex',\n 'gpt-5.1-codex-max',\n] as const;\n\nexport type OpenAIModel = (typeof OPENAI_MODELS)[number];\n\n/**\n * Type guard to check if a model is a supported direct OpenAI model.\n */\nexport function isOpenAIModel(model: string): model is OpenAIModel {\n return OPENAI_MODELS.includes(model as OpenAIModel);\n}\n\n/**\n * Represents OpenAI image models.\n */\nexport const OPENAI_IMAGE_MODELS = [\n 'gpt-image-2',\n 'gpt-image-2-2026-04-21',\n 'gpt-image-1.5',\n 'gpt-image-1',\n 'gpt-image-1-mini',\n 'chatgpt-image-latest',\n 'dall-e-2',\n 'dall-e-3',\n] as const satisfies readonly ImageModel[];\n\nexport type OpenAIImageModel = (typeof OPENAI_IMAGE_MODELS)[number];\n\n/**\n * Type guard to check if a model is a supported OpenAI image model.\n */\nexport function isOpenAIImageModel(model: string): model is OpenAIImageModel {\n return OPENAI_IMAGE_MODELS.includes(model as OpenAIImageModel);\n}\n\n/**\n * Represents Deepseek models\n */\nexport type DeepseekModel = 'deepseek-chat' | 'deepseek-reasoner';\n\n/**\n * Represents OpenRouter models\n */\nexport const OPENROUTER_MODELS = [\n 'openai/gpt-5',\n 'openai/gpt-5-mini',\n 'openai/gpt-5.4-mini',\n 'openai/gpt-5.4-nano',\n 'openai/gpt-5-nano',\n 'openai/gpt-5.1',\n 'openai/gpt-5.4',\n 'openai/gpt-5.4-pro',\n 'openai/gpt-5.5',\n 'openai/gpt-5.5-pro',\n 'openai/gpt-5.2',\n 'openai/gpt-5.2-pro',\n 'openai/gpt-5.1-codex',\n 'openai/gpt-5.1-codex-max',\n 'openai/gpt-oss-120b',\n 'z.ai/glm-4.5',\n 'z.ai/glm-4.5-air',\n 'google/gemini-2.5-flash',\n 'google/gemini-2.5-flash-lite',\n 'deepseek/deepseek-r1-0528',\n 'deepseek/deepseek-chat-v3-0324',\n] as const;\n\nexport type OpenRouterModel = (typeof OPENROUTER_MODELS)[number];\n\n/**\n * Represents pricing information for OpenRouter models\n */\nexport interface OpenRouterPricing {\n input: number; // Cost per 1M input tokens\n output: number; // Cost per 1M output tokens\n context?: number; // Max context tokens\n}\n\n/**\n * Represents all supported LLM models\n */\nexport type LLMModel = OpenAIModel | DeepseekModel | OpenRouterModel;\n\n/**\n * Type guard to check if a model is an OpenRouter model\n */\nexport function isOpenRouterModel(model: string): model is OpenRouterModel {\n return OPENROUTER_MODELS.includes(model as OpenRouterModel);\n}\n\n/**\n * Represents the usage of the LLM.\n */\nexport interface LLMUsage {\n prompt_tokens: number;\n completion_tokens: number;\n reasoning_tokens?: number;\n provider: string;\n model: LLMModel;\n cache_hit_tokens?: number;\n cache_write_tokens?: number;\n cost: number;\n}\n\n/**\n * Represents the options for the LLM.\n */\nexport interface LLMOptions {\n model?: LLMModel;\n temperature?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n max_completion_tokens?: number;\n tools?: ChatCompletionTool[];\n developerPrompt?: string;\n context?: ChatCompletionMessageParam[];\n store?: boolean;\n reasoning_effort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';\n reasoning_mode?: 'standard' | 'pro';\n reasoning_context?: 'auto' | 'current_turn' | 'all_turns';\n metadata?: Record<string, string>;\n parallel_tool_calls?: boolean;\n service_tier?: 'auto' | 'default' | 'flex' | 'priority';\n apiKey?: string;\n}\n\n/**\n * Represents the response from the LLM.\n */\nexport interface LLMResponse<T> {\n response: T;\n usage: LLMUsage;\n tool_calls?: ChatCompletionMessageToolCall[];\n}\n\n/**\n * Represents the format of the OpenAI response.\n */\nexport type OpenAIResponseFormat = 'text' | 'json' | ResponseFormatTextJSONSchemaConfig;\n\n/**\n * Represents schema input for structured outputs in OpenAI calls.\n * Can be either a JSON Schema object or a Zod schema.\n */\nexport type OpenAISchemaInput = ResponseFormatTextJSONSchemaConfig['schema'] | ZodType;\n\n/**\n * Supported image detail levels for OpenAI Responses vision inputs.\n */\nexport type OpenAIImageDetail = ResponseInputImage['detail'];\n\n/**\n * A remote image URL to analyze.\n */\nexport interface OpenAIImageURLInput {\n url: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * A base64-encoded image to analyze.\n * If `base64` is a raw base64 string, `mimeType` is used to create a data URL.\n */\nexport interface OpenAIImageBase64Input {\n base64: string;\n mimeType?: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * A fully formed data URL to analyze.\n */\nexport interface OpenAIImageDataURLInput {\n dataUrl: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * An already-uploaded OpenAI file ID to analyze.\n */\nexport interface OpenAIImageFileIDInput {\n fileId: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * A local file path to upload for vision analysis in Node.js environments.\n */\nexport interface OpenAIImageFilePathInput {\n filePath: string;\n filename?: string;\n mimeType?: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * Vision image input accepted by the OpenAI Responses helper.\n */\nexport type OpenAIImageInput =\n | OpenAIImageURLInput\n | OpenAIImageBase64Input\n | OpenAIImageDataURLInput\n | OpenAIImageFileIDInput\n | OpenAIImageFilePathInput;\n\n/**\n * Represents the options for the OpenAI Images API.\n * Extends the official ImageGenerateParams but with more user-friendly option names.\n */\nexport interface ImageGenerationOptions {\n model?: DiscoImageModel;\n size?: ImageGenerateParams['size'];\n outputFormat?: 'jpeg' | 'png' | 'webp';\n compression?: number;\n quality?: ImageGenerateParams['quality'];\n count?: number | null;\n apiKey?: string;\n background?: ImageGenerateParams['background'];\n moderation?: ImageGenerateParams['moderation'];\n /**\n * Optional multimodal LLM to pair with image outputs (e.g., gpt-5.4).\n */\n visionModel?: LLMModel;\n}\n\nexport type DiscoImageModel = OpenAIImageModel;\n\n/**\n * Context message for conversation history\n */\nexport interface ContextMessage {\n role: 'user' | 'assistant' | 'system' | 'developer';\n content: string;\n}\n\n\n// Re-export OpenAI types for convenience\nexport type { ImageModel, ImageGenerateParams } from 'openai/resources/images';\nexport type { ImagesResponse, Image } from 'openai/resources/images';\nexport type { Tool } from 'openai/resources/responses/responses';\n", "// llm-openai.ts\n\nimport OpenAI from 'openai';\nimport { zodTextFormat } from 'openai/helpers/zod';\nimport type { ZodType } from 'zod';\n\nimport type {\n Tool,\n ResponseInput,\n EasyInputMessage,\n ResponseInputImage,\n ResponseInputText,\n} from 'openai/resources/responses/responses';\n\nimport { calculateCost, DEFAULT_MODEL } from './llm-config';\nimport { parseResponse, normalizeModelName } from './llm-utils';\nimport { isOpenAIModel } from './types';\nimport type {\n LLMResponse,\n LLMOptions,\n LLMModel,\n OpenAIResponseFormat,\n ContextMessage,\n OpenAISchemaInput,\n OpenAIImageInput,\n OpenAIImageDetail,\n} from './types';\nimport type {\n ResponseCreateParamsNonStreaming,\n ResponseOutputItem,\n ResponseFunctionToolCall,\n ResponseCodeInterpreterToolCall,\n ResponseOutputMessage,\n ResponseOutputText,\n ResponseFormatTextJSONSchemaConfig,\n} from 'openai/resources/responses/responses';\n\nexport const DEFAULT_OPTIONS: LLMOptions = {\n model: DEFAULT_MODEL,\n parallel_tool_calls: false,\n};\n\nconst DEFAULT_IMAGE_MIME_TYPE = 'image/webp';\n\n/**\n * Checks if the given direct OpenAI model supports the temperature parameter.\n * @param model The model to check.\n * @returns True if the model supports the temperature parameter, false otherwise.\n */\nexport function supportsTemperature(_model: string): boolean {\n return false;\n}\n\nfunction isZodSchema(schema: OpenAISchemaInput): schema is ZodType {\n return typeof schema === 'object' && schema !== null && 'safeParse' in schema;\n}\n\nfunction buildJsonSchemaFormat(\n schema: OpenAISchemaInput,\n schemaName: string,\n schemaDescription?: string,\n schemaStrict?: boolean\n): ResponseFormatTextJSONSchemaConfig {\n if (isZodSchema(schema)) {\n const zodFormat = zodTextFormat(\n schema,\n schemaName,\n schemaDescription\n ? {\n description: schemaDescription,\n }\n : undefined\n );\n\n return {\n type: 'json_schema',\n name: zodFormat.name,\n schema: zodFormat.schema,\n ...(zodFormat.description ? { description: zodFormat.description } : {}),\n ...(schemaStrict !== undefined ? { strict: schemaStrict } : { strict: zodFormat.strict }),\n };\n }\n\n return {\n type: 'json_schema',\n name: schemaName,\n schema,\n ...(schemaDescription ? { description: schemaDescription } : {}),\n ...(schemaStrict !== undefined ? { strict: schemaStrict } : {}),\n };\n}\n\nfunction resolveOpenAIApiKey(apiKey?: string): string {\n const resolvedApiKey = apiKey || process.env.OPENAI_API_KEY;\n\n if (!resolvedApiKey) {\n throw new Error('OpenAI API key is not provided and OPENAI_API_KEY environment variable is not set');\n }\n\n return resolvedApiKey;\n}\n\nfunction createOpenAIClient(apiKey: string): OpenAI {\n return new OpenAI({\n apiKey,\n });\n}\n\nfunction normalizeImageDataUrl(imageData: string, mimeType = DEFAULT_IMAGE_MIME_TYPE): string {\n return imageData.startsWith('data:') ? imageData : `data:${mimeType};base64,${imageData}`;\n}\n\nfunction getFilenameFromPath(filePath: string): string {\n const normalizedPath = filePath.replace(/\\\\/g, '/');\n const pathSegments = normalizedPath.split('/');\n const filename = pathSegments[pathSegments.length - 1];\n\n if (!filename) {\n throw new Error(`Could not determine a filename from file path: ${filePath}`);\n }\n\n return filename;\n}\n\nfunction inferImageMimeType(filePath: string): string | undefined {\n const normalizedPath = filePath.toLowerCase();\n\n if (normalizedPath.endsWith('.png')) {\n return 'image/png';\n }\n\n if (normalizedPath.endsWith('.jpg') || normalizedPath.endsWith('.jpeg')) {\n return 'image/jpeg';\n }\n\n if (normalizedPath.endsWith('.webp')) {\n return 'image/webp';\n }\n\n if (normalizedPath.endsWith('.gif')) {\n return 'image/gif';\n }\n\n return undefined;\n}\n\nasync function readLocalFileBytes(filePath: string): Promise<Uint8Array> {\n try {\n const dynamicImport = new Function('specifier', 'return import(specifier);') as (\n specifier: string\n ) => Promise<{ readFile: (path: string) => Promise<Uint8Array> }>;\n const { readFile } = await dynamicImport('node:fs/promises');\n\n return await readFile(filePath);\n } catch {\n throw new Error('Local image file uploads require a Node.js runtime with access to node:fs/promises');\n }\n}\n\nasync function uploadVisionFileFromPath(\n openai: OpenAI,\n filePath: string,\n filename?: string,\n mimeType?: string\n): Promise<string> {\n const fileBytes = await readLocalFileBytes(filePath);\n const resolvedFilename = filename || getFilenameFromPath(filePath);\n const resolvedMimeType = mimeType || inferImageMimeType(filePath);\n const uploadableFile = await OpenAI.toFile(\n fileBytes,\n resolvedFilename,\n resolvedMimeType ? { type: resolvedMimeType } : undefined\n );\n\n const uploadedFile = await openai.files.create({\n file: uploadableFile,\n purpose: 'vision',\n });\n\n return uploadedFile.id;\n}\n\nfunction collectImageInputs(\n image: OpenAIImageInput | undefined,\n images: OpenAIImageInput[] | undefined,\n imageBase64: string | undefined\n): OpenAIImageInput[] {\n const collectedImages: OpenAIImageInput[] = [];\n\n if (image) {\n collectedImages.push(image);\n }\n\n if (images && images.length > 0) {\n collectedImages.push(...images);\n }\n\n if (imageBase64) {\n collectedImages.push({ base64: imageBase64 });\n }\n\n return collectedImages;\n}\n\nfunction hasLocalFileImage(images: OpenAIImageInput[]): boolean {\n return images.some((image) => 'filePath' in image);\n}\n\nasync function buildImageContentPart(\n image: OpenAIImageInput,\n defaultDetail: OpenAIImageDetail,\n openai?: OpenAI\n): Promise<ResponseInputImage> {\n const detail = image.detail ?? defaultDetail;\n\n if ('url' in image) {\n return {\n type: 'input_image',\n detail,\n image_url: image.url,\n };\n }\n\n if ('dataUrl' in image) {\n return {\n type: 'input_image',\n detail,\n image_url: image.dataUrl,\n };\n }\n\n if ('base64' in image) {\n return {\n type: 'input_image',\n detail,\n image_url: normalizeImageDataUrl(image.base64, image.mimeType),\n };\n }\n\n if ('fileId' in image) {\n return {\n type: 'input_image',\n detail,\n file_id: image.fileId,\n };\n }\n\n if (!openai) {\n throw new Error('A local image file path was provided, but no OpenAI client is available to upload it');\n }\n\n const fileId = await uploadVisionFileFromPath(openai, image.filePath, image.filename, image.mimeType);\n return {\n type: 'input_image',\n detail,\n file_id: fileId,\n };\n}\n\nasync function buildPromptContent(\n input: string,\n imageInputs: OpenAIImageInput[],\n imageDetail: OpenAIImageDetail,\n openai?: OpenAI\n): Promise<string | Array<ResponseInputText | ResponseInputImage>> {\n if (imageInputs.length === 0) {\n return input;\n }\n\n const imageContent = await Promise.all(imageInputs.map((image) => buildImageContentPart(image, imageDetail, openai)));\n\n return [{ type: 'input_text', text: input }, ...imageContent];\n}\n\nexport async function uploadVisionFile(\n filePath: string,\n options: {\n apiKey?: string;\n filename?: string;\n mimeType?: string;\n } = {}\n): Promise<string> {\n const resolvedApiKey = resolveOpenAIApiKey(options.apiKey);\n const openai = createOpenAIClient(resolvedApiKey);\n\n return await uploadVisionFileFromPath(openai, filePath, options.filename, options.mimeType);\n}\n\n/**\n * Makes a call to OpenAI's Responses API for more advanced use cases with built-in tools.\n *\n * This function provides access to the Responses API which supports:\n * - Built-in tools (web search, file search, computer use, code interpreter, image generation)\n * - Background processing\n * - Conversation state management\n * - GPT-5 reasoning controls\n *\n * @example\n * // Basic text response\n * const response = await makeResponsesAPICall('What is the weather like?');\n *\n * @example\n * // With web search tool\n * const response = await makeResponsesAPICall('Latest news about AI', {\n * tools: [{ type: 'web_search_preview' }]\n * });\n *\n * @param input - The input content. Can be:\n * - A string for simple text prompts\n * - An array of input items for complex/multi-modal content\n * @param options - Configuration options for the Responses API\n * @returns Promise<LLMResponse<T>> - The response in the same format as makeLLMCall\n * @throws Error if the API call fails\n */\nexport const makeResponsesAPICall = async <T = string>(\n input: string | ResponseCreateParamsNonStreaming['input'],\n options: Omit<ResponseCreateParamsNonStreaming, 'input' | 'model'> & {\n apiKey?: string;\n model?: string;\n } = {}\n): Promise<LLMResponse<T>> => {\n const normalizedModel = normalizeModelName(options.model || DEFAULT_MODEL);\n if (!isOpenAIModel(normalizedModel)) {\n throw new Error(`Unsupported OpenAI model: ${normalizedModel}. Please use a supported GPT-5 model.`);\n }\n\n const apiKey = resolveOpenAIApiKey(options.apiKey);\n const openai = createOpenAIClient(apiKey);\n\n // Remove apiKey from options before creating request body\n const { apiKey: _, model: __, ...cleanOptions } = options;\n\n const requestBody: ResponseCreateParamsNonStreaming = {\n model: normalizedModel,\n input,\n ...cleanOptions,\n };\n\n // Make the API call to the Responses endpoint\n const response = await openai.responses.create(requestBody);\n const cacheHitTokens = response.usage?.input_tokens_details?.cached_tokens || 0;\n const cacheWriteTokens = response.usage?.input_tokens_details?.cache_write_tokens || 0;\n\n // Extract tool calls from the output\n const toolCalls = response.output\n ?.filter((item: ResponseOutputItem): item is ResponseFunctionToolCall => item.type === 'function_call')\n .map((toolCall: ResponseFunctionToolCall) => ({\n id: toolCall.call_id,\n type: 'function' as const,\n function: {\n name: toolCall.name,\n arguments: toolCall.arguments,\n },\n }));\n\n // Extract code interpreter outputs if present\n const codeInterpreterCalls = response.output?.filter(\n (item: ResponseOutputItem): item is ResponseCodeInterpreterToolCall => item.type === 'code_interpreter_call'\n );\n let codeInterpreterOutputs: ResponseCodeInterpreterToolCall['outputs'] | undefined = undefined;\n if (codeInterpreterCalls && codeInterpreterCalls.length > 0) {\n // Each code_interpreter_call has an 'outputs' array property\n codeInterpreterOutputs = codeInterpreterCalls.flatMap((ci) => {\n // Return outputs if present, otherwise empty array\n if (ci.outputs) return ci.outputs;\n return [];\n });\n }\n\n // Handle tool calls differently\n if (toolCalls && toolCalls.length > 0) {\n return {\n response: {\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n arguments: JSON.parse(tc.function.arguments),\n })),\n } as T,\n usage: {\n prompt_tokens: response.usage?.input_tokens || 0,\n completion_tokens: response.usage?.output_tokens || 0,\n reasoning_tokens: response.usage?.output_tokens_details?.reasoning_tokens || 0,\n provider: 'openai',\n model: normalizedModel,\n cache_hit_tokens: cacheHitTokens,\n cache_write_tokens: cacheWriteTokens,\n cost: calculateCost(\n 'openai',\n normalizedModel,\n response.usage?.input_tokens || 0,\n response.usage?.output_tokens || 0,\n response.usage?.output_tokens_details?.reasoning_tokens || 0,\n cacheHitTokens,\n cacheWriteTokens\n ),\n },\n tool_calls: toolCalls,\n ...(codeInterpreterOutputs ? { code_interpreter_outputs: codeInterpreterOutputs } : {}),\n };\n }\n\n // Extract text content from the response output\n const textContent =\n response.output\n ?.filter((item: ResponseOutputItem): item is ResponseOutputMessage => item.type === 'message')\n .map((item: ResponseOutputMessage) =>\n item.content\n .filter((content): content is ResponseOutputText => content.type === 'output_text')\n .map((content) => content.text)\n .join('')\n )\n .join('') || '';\n\n // Determine the format for parsing the response\n let parsingFormat: OpenAIResponseFormat = 'text';\n const requestedFormat = requestBody.text?.format;\n if (requestedFormat?.type === 'json_object') {\n parsingFormat = 'json';\n } else if (requestedFormat?.type === 'json_schema') {\n parsingFormat = requestedFormat;\n }\n\n // Handle regular responses\n const parsedResponse = await parseResponse<T>(textContent, parsingFormat);\n if (parsedResponse === null) {\n throw new Error('Failed to parse response from Responses API');\n }\n\n return {\n response: parsedResponse,\n usage: {\n prompt_tokens: response.usage?.input_tokens || 0,\n completion_tokens: response.usage?.output_tokens || 0,\n reasoning_tokens: response.usage?.output_tokens_details?.reasoning_tokens || 0,\n provider: 'openai',\n model: normalizedModel,\n cache_hit_tokens: cacheHitTokens,\n cache_write_tokens: cacheWriteTokens,\n cost: calculateCost(\n 'openai',\n normalizedModel,\n response.usage?.input_tokens || 0,\n response.usage?.output_tokens || 0,\n response.usage?.output_tokens_details?.reasoning_tokens || 0,\n cacheHitTokens,\n cacheWriteTokens\n ),\n },\n tool_calls: toolCalls,\n ...(codeInterpreterOutputs ? { code_interpreter_outputs: codeInterpreterOutputs } : {}),\n };\n};\n\n/**\n * Makes a call to the OpenAI Responses API for advanced use cases with built-in tools.\n *\n * @param input The text prompt to send to the model (e.g., \"What's in this image?\")\n * @param options The options for the Responses API call, including optional image data and context.\n * @return A promise that resolves to the response from the Responses API.\n *\n * @example\n * // With conversation context\n * const response = await makeLLMCall(\"What did I ask about earlier?\", {\n * context: [\n * { role: 'user', content: 'What is the capital of France?' },\n * { role: 'assistant', content: 'The capital of France is Paris.' }\n * ]\n * });\n */\nexport async function makeLLMCall<T = string>(\n input: string,\n options: {\n apiKey?: string;\n model?: LLMModel;\n responseFormat?: OpenAIResponseFormat;\n schema?: OpenAISchemaInput;\n schemaName?: string;\n schemaDescription?: string;\n schemaStrict?: boolean;\n tools?: Tool[];\n useCodeInterpreter?: boolean;\n useWebSearch?: boolean;\n image?: OpenAIImageInput;\n images?: OpenAIImageInput[];\n imageBase64?: string;\n imageDetail?: OpenAIImageDetail;\n context?: ContextMessage[];\n reasoningEffort?: LLMOptions['reasoning_effort'];\n reasoningMode?: LLMOptions['reasoning_mode'];\n reasoningContext?: LLMOptions['reasoning_context'];\n } = {}\n): Promise<LLMResponse<T>> {\n const {\n apiKey,\n model = DEFAULT_MODEL,\n responseFormat = 'text',\n schema,\n schemaName = 'response',\n schemaDescription,\n schemaStrict,\n tools,\n useCodeInterpreter = false,\n useWebSearch = false,\n image,\n images,\n imageBase64,\n imageDetail = 'high',\n context,\n reasoningEffort,\n reasoningMode,\n reasoningContext,\n } = options;\n\n // Validate model\n const normalizedModel = normalizeModelName(model);\n if (!isOpenAIModel(normalizedModel)) {\n throw new Error(`Unsupported OpenAI model: ${normalizedModel}. Please use a supported GPT-5 model.`);\n }\n\n const resolvedApiKey = resolveOpenAIApiKey(apiKey);\n const imageInputs = collectImageInputs(image, images, imageBase64);\n const openai = hasLocalFileImage(imageInputs) ? createOpenAIClient(resolvedApiKey) : undefined;\n const promptContent = await buildPromptContent(input, imageInputs, imageDetail, openai);\n\n // Process input for conversation context and image analysis\n let processedInput: string | ResponseInput;\n\n if (context && context.length > 0) {\n // Build conversation array with context\n const conversationMessages: EasyInputMessage[] = [];\n\n // Add context messages\n for (const contextMsg of context) {\n conversationMessages.push({\n role: contextMsg.role,\n content: contextMsg.content,\n type: 'message',\n });\n }\n\n // Add current input message\n if (imageInputs.length > 0) {\n // Current message includes text and one or more images\n conversationMessages.push({\n role: 'user',\n content: promptContent,\n type: 'message',\n });\n } else {\n // Current message is just text\n conversationMessages.push({\n role: 'user',\n content: input,\n type: 'message',\n });\n }\n\n processedInput = conversationMessages;\n } else if (imageInputs.length > 0) {\n // No context, but has image(s)\n processedInput = [\n {\n role: 'user',\n content: promptContent,\n type: 'message',\n },\n ];\n } else {\n // No context, no image - simple string input\n processedInput = input;\n }\n\n // Build the options object for makeResponsesAPICall\n let responsesOptions: Parameters<typeof makeResponsesAPICall>[1] = {\n apiKey: resolvedApiKey,\n model: normalizedModel,\n parallel_tool_calls: false,\n tools,\n };\n\n // Only include temperature if the model supports it\n if (supportsTemperature(normalizedModel)) {\n responsesOptions.temperature = 0.2;\n }\n\n if (reasoningEffort || reasoningMode || reasoningContext) {\n responsesOptions.reasoning = {\n ...(reasoningEffort ? { effort: reasoningEffort } : {}),\n ...(reasoningMode ? { mode: reasoningMode } : {}),\n ...(reasoningContext ? { context: reasoningContext } : {}),\n };\n }\n\n // Configure response format\n if (schema) {\n responsesOptions.text = {\n format: buildJsonSchemaFormat(schema, schemaName, schemaDescription, schemaStrict),\n };\n } else if (responseFormat === 'json') {\n responsesOptions.text = { format: { type: 'json_object' } };\n } else if (typeof responseFormat === 'object' && responseFormat.type === 'json_schema') {\n responsesOptions.text = { format: responseFormat };\n }\n\n // Configure built-in tools\n if (useCodeInterpreter) {\n responsesOptions.tools = [{ type: 'code_interpreter', container: { type: 'auto' } }];\n responsesOptions.include = ['code_interpreter_call.outputs'];\n }\n\n if (useWebSearch) {\n responsesOptions.tools = [{ type: 'web_search_preview' }];\n }\n\n return await makeResponsesAPICall<T>(processedInput, responsesOptions);\n}\n", "// llm-openai-config.ts\nimport type { ImageGenerateParams } from 'openai/resources/images';\nimport type { OpenAIImageModel, OpenAIModel } from './types/llm-types';\n\nexport const DEFAULT_MODEL: OpenAIModel = 'gpt-5.6-luna';\n\nexport const DEFAULT_DEVELOPER_PROMPT = `\n You are a highly experienced coding, business analyst, and financial analyst associate.\n Help with coding, business process design and analysis, data generation and refinement, content creation, financial analysis, and more.\n When presented with a coding problem, logic problem, or other problem benefiting from systematic thinking, think through it step by step before giving your final answer.\n Present complete, high-confidence, final answers only. Do not rephrase to be more brief or omit parts of answers.\n Respond only with final content (e.g. code, a json or yaml object, a formatted string, or a markdown document) and nothing else. Do not reply with a preamble, introduction, or conclusion.\n`;\n\ninterface AIModelCosts {\n [modelName: string]: {\n inputCost: number;\n outputCost: number;\n cacheHitCost?: number;\n cacheWriteCost?: number;\n };\n}\n\nconst GPT_5_HIGH_CONTEXT_THRESHOLD_TOKENS = 272_000;\nconst GPT_5_HIGH_CONTEXT_INPUT_MULTIPLIER = 2;\nconst GPT_5_HIGH_CONTEXT_OUTPUT_MULTIPLIER = 1.5;\n\n/** Token costs in USD per 1M tokens. Last updated July 2026 from the OpenAI API pricing page. */\nexport const openAiModelCosts: AIModelCosts = {\n 'gpt-5.6': {\n inputCost: 5 / 1_000_000,\n cacheHitCost: 0.5 / 1_000_000,\n cacheWriteCost: 6.25 / 1_000_000,\n outputCost: 30 / 1_000_000,\n },\n 'gpt-5.6-sol': {\n inputCost: 5 / 1_000_000,\n cacheHitCost: 0.5 / 1_000_000,\n cacheWriteCost: 6.25 / 1_000_000,\n outputCost: 30 / 1_000_000,\n },\n 'gpt-5.6-terra': {\n inputCost: 2.5 / 1_000_000,\n cacheHitCost: 0.25 / 1_000_000,\n cacheWriteCost: 3.125 / 1_000_000,\n outputCost: 15 / 1_000_000,\n },\n 'gpt-5.6-luna': {\n inputCost: 1 / 1_000_000,\n cacheHitCost: 0.1 / 1_000_000,\n cacheWriteCost: 1.25 / 1_000_000,\n outputCost: 6 / 1_000_000,\n },\n 'gpt-5': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n 'gpt-5-mini': {\n inputCost: 0.25 / 1_000_000,\n cacheHitCost: 0.025 / 1_000_000,\n outputCost: 2 / 1_000_000,\n },\n 'gpt-5.4-mini': {\n inputCost: 0.75 / 1_000_000,\n cacheHitCost: 0.075 / 1_000_000,\n outputCost: 4.5 / 1_000_000,\n },\n 'gpt-5.4-nano': {\n inputCost: 0.2 / 1_000_000,\n cacheHitCost: 0.02 / 1_000_000,\n outputCost: 1.25 / 1_000_000,\n },\n 'gpt-5-nano': {\n inputCost: 0.05 / 1_000_000,\n cacheHitCost: 0.005 / 1_000_000,\n outputCost: 0.4 / 1_000_000,\n },\n 'gpt-5.1': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n 'gpt-5.4': {\n inputCost: 2.5 / 1_000_000,\n cacheHitCost: 0.25 / 1_000_000,\n outputCost: 15 / 1_000_000,\n },\n 'gpt-5.5': {\n inputCost: 5 / 1_000_000,\n cacheHitCost: 0.5 / 1_000_000,\n outputCost: 30 / 1_000_000,\n },\n 'gpt-5.5-pro': {\n inputCost: 30 / 1_000_000,\n outputCost: 180 / 1_000_000,\n },\n 'gpt-5.2': {\n inputCost: 1.75 / 1_000_000,\n cacheHitCost: 0.175 / 1_000_000,\n outputCost: 14 / 1_000_000,\n },\n 'gpt-5.2-pro': {\n inputCost: 21 / 1_000_000,\n outputCost: 168 / 1_000_000,\n },\n 'gpt-5.1-codex': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n 'gpt-5.1-codex-max': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n};\n\nexport const deepseekModelCosts: AIModelCosts = {\n 'deepseek-chat': {\n inputCost: 0.27 / 1_000_000, // $0.27 per 1M tokens (Cache miss price)\n cacheHitCost: 0.07 / 1_000_000, // $0.07 per 1M tokens (Cache hit price)\n outputCost: 1.1 / 1_000_000, // $1.10 per 1M tokens\n },\n 'deepseek-reasoner': {\n inputCost: 0.55 / 1_000_000, // $0.55 per 1M tokens (Cache miss price)\n cacheHitCost: 0.14 / 1_000_000, // $0.14 per 1M tokens (Cache hit price)\n outputCost: 2.19 / 1_000_000, // $2.19 per 1M tokens\n },\n};\n\nfunction shouldUseGPT5HighContextPricing(model: string, inputTokens: number): boolean {\n return (\n (model === 'gpt-5.4' || model === 'gpt-5.5' || model === 'gpt-5.6' || model === 'gpt-5.6-sol' || model === 'gpt-5.6-terra' || model === 'gpt-5.6-luna') &&\n inputTokens > GPT_5_HIGH_CONTEXT_THRESHOLD_TOKENS\n );\n}\n\nexport type PricedOpenAIImageModel =\n | 'gpt-image-2'\n | 'gpt-image-2-2026-04-21'\n | 'gpt-image-1.5'\n | 'gpt-image-1'\n | 'gpt-image-1-mini';\nexport type OpenAIImagePricingQuality = 'low' | 'medium' | 'high';\nexport type OpenAIImagePricingSize = '1024x1024' | '1024x1536' | '1536x1024';\n\nexport const DEFAULT_IMAGE_PRICING_QUALITY: OpenAIImagePricingQuality = 'high';\nexport const DEFAULT_IMAGE_PRICING_SIZE: OpenAIImagePricingSize = '1024x1024';\n\nconst PRICED_OPENAI_IMAGE_MODELS: readonly PricedOpenAIImageModel[] = [\n 'gpt-image-2',\n 'gpt-image-2-2026-04-21',\n 'gpt-image-1.5',\n 'gpt-image-1',\n 'gpt-image-1-mini',\n];\nconst OPENAI_IMAGE_PRICING_SIZES: readonly OpenAIImagePricingSize[] = ['1024x1024', '1024x1536', '1536x1024'];\n\n/**\n * Estimated image output costs in USD per image for common GPT Image sizes.\n * Last updated May 2026 from the OpenAI image generation guide. Text and image\n * input token costs for prompts and edit inputs are not included.\n */\nexport const openAiImageCostByQualityAndSize: Record<\n PricedOpenAIImageModel,\n Record<OpenAIImagePricingQuality, Record<OpenAIImagePricingSize, number>>\n> = {\n 'gpt-image-2': {\n low: {\n '1024x1024': 0.006,\n '1024x1536': 0.005,\n '1536x1024': 0.005,\n },\n medium: {\n '1024x1024': 0.053,\n '1024x1536': 0.041,\n '1536x1024': 0.041,\n },\n high: {\n '1024x1024': 0.211,\n '1024x1536': 0.165,\n '1536x1024': 0.165,\n },\n },\n 'gpt-image-2-2026-04-21': {\n low: {\n '1024x1024': 0.006,\n '1024x1536': 0.005,\n '1536x1024': 0.005,\n },\n medium: {\n '1024x1024': 0.053,\n '1024x1536': 0.041,\n '1536x1024': 0.041,\n },\n high: {\n '1024x1024': 0.211,\n '1024x1536': 0.165,\n '1536x1024': 0.165,\n },\n },\n 'gpt-image-1.5': {\n low: {\n '1024x1024': 0.009,\n '1024x1536': 0.013,\n '1536x1024': 0.013,\n },\n medium: {\n '1024x1024': 0.034,\n '1024x1536': 0.05,\n '1536x1024': 0.05,\n },\n high: {\n '1024x1024': 0.133,\n '1024x1536': 0.2,\n '1536x1024': 0.2,\n },\n },\n 'gpt-image-1': {\n low: {\n '1024x1024': 0.011,\n '1024x1536': 0.016,\n '1536x1024': 0.016,\n },\n medium: {\n '1024x1024': 0.042,\n '1024x1536': 0.063,\n '1536x1024': 0.063,\n },\n high: {\n '1024x1024': 0.167,\n '1024x1536': 0.25,\n '1536x1024': 0.25,\n },\n },\n 'gpt-image-1-mini': {\n low: {\n '1024x1024': 0.005,\n '1024x1536': 0.006,\n '1536x1024': 0.006,\n },\n medium: {\n '1024x1024': 0.011,\n '1024x1536': 0.015,\n '1536x1024': 0.015,\n },\n high: {\n '1024x1024': 0.036,\n '1024x1536': 0.052,\n '1536x1024': 0.052,\n },\n },\n};\n\n/** Default image output costs in USD per image for legacy callers. */\nexport const openAiImageCosts: Record<PricedOpenAIImageModel, number> = {\n 'gpt-image-2':\n openAiImageCostByQualityAndSize['gpt-image-2'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n 'gpt-image-2-2026-04-21':\n openAiImageCostByQualityAndSize['gpt-image-2-2026-04-21'][DEFAULT_IMAGE_PRICING_QUALITY][\n DEFAULT_IMAGE_PRICING_SIZE\n ],\n 'gpt-image-1.5':\n openAiImageCostByQualityAndSize['gpt-image-1.5'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n 'gpt-image-1':\n openAiImageCostByQualityAndSize['gpt-image-1'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n 'gpt-image-1-mini':\n openAiImageCostByQualityAndSize['gpt-image-1-mini'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n};\n\nfunction isPricedOpenAIImageModel(model: string): model is PricedOpenAIImageModel {\n return PRICED_OPENAI_IMAGE_MODELS.includes(model as PricedOpenAIImageModel);\n}\n\nfunction isOpenAIImagePricingSize(size: string): size is OpenAIImagePricingSize {\n return OPENAI_IMAGE_PRICING_SIZES.includes(size as OpenAIImagePricingSize);\n}\n\nfunction resolveImagePricingQuality(quality?: ImageGenerateParams['quality']): OpenAIImagePricingQuality {\n if (quality === 'low' || quality === 'medium' || quality === 'high') {\n return quality;\n }\n\n return DEFAULT_IMAGE_PRICING_QUALITY;\n}\n\nfunction resolveImagePricingSize(size?: ImageGenerateParams['size']): OpenAIImagePricingSize {\n if (typeof size === 'string' && isOpenAIImagePricingSize(size)) {\n return size;\n }\n\n return DEFAULT_IMAGE_PRICING_SIZE;\n}\n\n/**\n * Calculates the cost of generating images using OpenAI's Images API.\n *\n * @param model The image generation model name.\n * @param imageCount The number of images generated.\n * @param quality The requested image quality.\n * @param size The requested image size.\n * @returns The cost of generating the images in USD.\n */\nexport function calculateImageCost(\n model: OpenAIImageModel | string,\n imageCount: number,\n quality?: ImageGenerateParams['quality'],\n size?: ImageGenerateParams['size']\n): number {\n if (typeof model !== 'string' || typeof imageCount !== 'number' || imageCount <= 0) {\n return 0;\n }\n\n if (!isPricedOpenAIImageModel(model)) return 0;\n\n const pricingQuality = resolveImagePricingQuality(quality);\n const pricingSize = resolveImagePricingSize(size);\n const costPerImage = openAiImageCostByQualityAndSize[model][pricingQuality][pricingSize];\n\n return imageCount * costPerImage;\n}\n\n/**\n * Calculates the cost of calling a language model in USD based on the provider and model, tokens, and given costs per 1M tokens.\n *\n * @param provider The provider of the language model. Supported providers are 'openai' and 'deepseek'.\n * @param model The name of the language model. Supported models are listed in the `openAiModelCosts` and `deepseekModelCosts` objects.\n * @param inputTokens The number of input tokens passed to the language model.\n * @param outputTokens The number of output tokens generated by the language model.\n * @param reasoningTokens The number of output tokens generated by the language model for reasoning.\n * @param cacheHitTokens The number of input tokens billed at cached-input rates.\n * @param cacheWriteTokens The number of input tokens billed at cache-write rates.\n * @returns The cost of calling the language model in USD.\n */\nexport function calculateCost(\n provider: string,\n model: string,\n inputTokens: number,\n outputTokens: number,\n reasoningTokens?: number,\n cacheHitTokens?: number,\n cacheWriteTokens?: number\n): number {\n if (\n typeof provider !== 'string' ||\n typeof model !== 'string' ||\n typeof inputTokens !== 'number' ||\n typeof outputTokens !== 'number' ||\n (reasoningTokens !== undefined && typeof reasoningTokens !== 'number') ||\n (cacheHitTokens !== undefined && typeof cacheHitTokens !== 'number') ||\n (cacheWriteTokens !== undefined && typeof cacheWriteTokens !== 'number')\n ) {\n return 0;\n }\n\n const modelCosts = provider === 'deepseek' ? deepseekModelCosts[model] : openAiModelCosts[model];\n\n if (!modelCosts) return 0;\n\n const boundedCacheHitTokens = Math.min(Math.max(cacheHitTokens || 0, 0), inputTokens);\n const boundedCacheWriteTokens = Math.min(Math.max(cacheWriteTokens || 0, 0), inputTokens - boundedCacheHitTokens);\n const uncachedInputTokens = inputTokens - boundedCacheHitTokens - boundedCacheWriteTokens;\n const inputCost =\n uncachedInputTokens * modelCosts.inputCost +\n boundedCacheHitTokens * (modelCosts.cacheHitCost || modelCosts.inputCost) +\n boundedCacheWriteTokens * (modelCosts.cacheWriteCost || modelCosts.inputCost);\n\n let outputCost = outputTokens * modelCosts.outputCost;\n let reasoningCost = (reasoningTokens || 0) * modelCosts.outputCost;\n\n if (provider === 'openai' && shouldUseGPT5HighContextPricing(model, inputTokens)) {\n return (\n inputCost * GPT_5_HIGH_CONTEXT_INPUT_MULTIPLIER +\n outputCost * GPT_5_HIGH_CONTEXT_OUTPUT_MULTIPLIER +\n reasoningCost * GPT_5_HIGH_CONTEXT_OUTPUT_MULTIPLIER\n );\n }\n\n return inputCost + outputCost + reasoningCost;\n}\n", "import OpenAI from 'openai';\nimport { DEFAULT_MODEL } from './llm-config';\n/**\n * Fix a broken JSON string by attempting to extract and parse valid JSON content. This function is very lenient and will attempt to fix many types of JSON errors, including unbalanced brackets, missing or extra commas, improperly escaped $ signs, unquoted strings, trailing commas, missing closing brackets or braces, etc.\n * @param {string} jsonStr - The broken JSON string to fix\n * @returns {JsonValue} - The parsed JSON value\n */\nexport function fixBrokenJson(jsonStr: string): JsonValue {\n // Pre-process: Fix improperly escaped $ signs\n jsonStr = jsonStr.replace(/\\\\\\$/g, '$');\n\n let index = 0;\n\n function parse(): JsonValue {\n const results: JsonValue[] = [];\n while (index < jsonStr.length) {\n skipWhitespace();\n const value = parseValue();\n if (value !== undefined) {\n results.push(value);\n } else {\n index++; // Skip invalid character\n }\n }\n return results.length === 1 ? results[0] : results;\n }\n\n function parseValue(): JsonValue | undefined {\n skipWhitespace();\n const char = getChar();\n if (!char) return undefined;\n if (char === '{') return parseObject();\n if (char === '[') return parseArray();\n if (char === '\"' || char === \"'\") return parseString();\n if (char === 't' && jsonStr.slice(index, index + 4).toLowerCase() === 'true') {\n index += 4;\n return true;\n }\n if (char === 'f' && jsonStr.slice(index, index + 5).toLowerCase() === 'false') {\n index += 5;\n return false;\n }\n if (char === 'n' && jsonStr.slice(index, index + 4).toLowerCase() === 'null') {\n index += 4;\n return null;\n }\n if (/[a-zA-Z]/.test(char)) return parseString(); // Unquoted string\n if (char === '-' || char === '.' || /\\d/.test(char)) return parseNumber();\n return undefined; // Unknown character\n }\n\n function parseObject(): JsonObject {\n const obj: JsonObject = {};\n index++; // Skip opening brace\n skipWhitespace();\n while (index < jsonStr.length && getChar() !== '}') {\n skipWhitespace();\n const key = parseString();\n if (key === undefined) {\n console.warn(`Expected key at position ${index}`);\n index++;\n continue;\n }\n skipWhitespace();\n if (getChar() === ':') {\n index++; // Skip colon\n } else {\n console.warn(`Missing colon after key \"${key}\" at position ${index}`);\n }\n skipWhitespace();\n const value = parseValue();\n if (value === undefined) {\n console.warn(`Expected value for key \"${key}\" at position ${index}`);\n index++;\n continue;\n }\n obj[key] = value;\n skipWhitespace();\n if (getChar() === ',') {\n index++; // Skip comma\n } else {\n break;\n }\n skipWhitespace();\n }\n if (getChar() === '}') {\n index++; // Skip closing brace\n } else {\n // Add a closing brace if it's missing\n jsonStr += '}';\n }\n return obj;\n }\n\n function parseArray(): JsonArray {\n const arr: JsonArray = [];\n index++; // Skip opening bracket\n skipWhitespace();\n while (index < jsonStr.length && getChar() !== ']') {\n const value = parseValue();\n if (value === undefined) {\n console.warn(`Expected value at position ${index}`);\n index++;\n } else {\n arr.push(value);\n }\n skipWhitespace();\n if (getChar() === ',') {\n index++; // Skip comma\n } else {\n break;\n }\n skipWhitespace();\n }\n if (getChar() === ']') {\n index++; // Skip closing bracket\n } else {\n console.warn(`Missing closing bracket for array at position ${index}`);\n }\n return arr;\n }\n\n function parseString(): string {\n const startChar = getChar();\n let result = '';\n let isQuoted = false;\n let delimiter = '';\n\n if (startChar === '\"' || startChar === \"'\") {\n isQuoted = true;\n delimiter = startChar;\n index++; // Skip opening quote\n }\n\n while (index < jsonStr.length) {\n const char = getChar();\n if (isQuoted) {\n if (char === delimiter) {\n index++; // Skip closing quote\n return result;\n } else if (char === '\\\\') {\n index++;\n const escapeChar = getChar();\n const escapeSequences: { [key: string]: string } = {\n n: '\\n',\n r: '\\r',\n t: '\\t',\n b: '\\b',\n f: '\\f',\n '\\\\': '\\\\',\n '/': '/',\n '\"': '\"',\n \"'\": \"'\",\n $: '$',\n };\n result += escapeSequences[escapeChar] || escapeChar;\n } else {\n result += char;\n }\n index++;\n } else {\n if (/\\s|,|}|]|\\:/.test(char)) {\n return result;\n } else {\n result += char;\n index++;\n }\n }\n }\n if (isQuoted) {\n console.warn(`Missing closing quote for string starting at position ${index}`);\n }\n return result;\n }\n\n function parseNumber(): number | undefined {\n const numberRegex = /^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?/;\n const match = numberRegex.exec(jsonStr.slice(index));\n if (match) {\n index += match[0].length;\n return parseFloat(match[0]);\n } else {\n console.warn(`Invalid number at position ${index}`);\n index++;\n return undefined;\n }\n }\n\n function getChar(): string {\n return jsonStr[index];\n }\n\n function skipWhitespace(): void {\n while (/\\s/.test(getChar())) index++;\n }\n\n try {\n return parse();\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n console.error(`Error parsing JSON at position ${index}: ${msg}`);\n return null;\n }\n}\n\n/**\n * Returns true if the given JSON string is valid, false otherwise.\n *\n * This function simply attempts to parse the given string as JSON and returns true if successful, or false if an error is thrown.\n *\n * @param {string} jsonString The JSON string to validate.\n * @returns {boolean} True if the JSON string is valid, false otherwise.\n */\nexport function isValidJson(jsonString: string): boolean {\n try {\n JSON.parse(jsonString);\n return true;\n } catch {\n return false;\n }\n}\n\n// Types just for fixing JSON with AI\ninterface JsonObject {\n [key: string]: JsonValue;\n}\ntype JsonArray = JsonValue[];\ntype JsonValue = string | number | boolean | null | JsonObject | JsonArray;\n\nlet openai: OpenAI;\n\n/**\n * Initializes an instance of the OpenAI client, using the provided API key or the value of the OPENAI_API_KEY environment variable if no key is provided.\n * @param apiKey - the API key to use, or undefined to use the value of the OPENAI_API_KEY environment variable\n * @returns an instance of the OpenAI client\n * @throws an error if the API key is not provided and the OPENAI_API_KEY environment variable is not set\n */\nfunction initializeOpenAI(apiKey?: string): OpenAI {\n const key = apiKey || process.env.OPENAI_API_KEY;\n if (!key) {\n throw new Error('OpenAI API key is not provided and OPENAI_API_KEY environment variable is not set');\n }\n return new OpenAI({\n apiKey: key,\n defaultHeaders: { 'User-Agent': 'My Server-side Application (compatible; OpenAI API Client)' },\n });\n}\n\n/**\n * Fixes broken JSON by sending it to OpenAI to fix it.\n * If the model fails to return valid JSON, an error is thrown.\n * @param jsonStr - the broken JSON to fix\n * @param apiKey - the OpenAI API key to use, or undefined to use the value of the OPENAI_API_KEY environment variable\n * @returns the fixed JSON\n * @throws an error if the model fails to return valid JSON\n */\nexport async function fixJsonWithAI(jsonStr: string, apiKey?: string): Promise<JsonValue> {\n try {\n if (!openai) {\n openai = initializeOpenAI();\n }\n\n const completion = await openai.chat.completions.create({\n model: DEFAULT_MODEL,\n messages: [\n {\n role: 'system',\n content: 'You are a JSON fixer. Return only valid JSON without any additional text or explanation.',\n },\n {\n role: 'user',\n content: `Fix this broken JSON:\\n${jsonStr}`,\n },\n ],\n response_format: { type: 'json_object' },\n });\n\n const fixedJson = completion.choices[0]?.message?.content;\n\n if (fixedJson && isValidJson(fixedJson)) {\n return JSON.parse(fixedJson);\n }\n throw new Error('Failed to fix JSON with AI');\n } catch (err: unknown) {\n const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';\n throw new Error(`Error fixing JSON with AI: ${errorMessage}`);\n }\n}\n", "import OpenAI from 'openai';\nimport { ImageGenerationOptions, LLMModel, DiscoImageModel, OPENAI_MODELS } from './types';\nimport { calculateImageCost } from './llm-config';\nimport { ImageGenerateParams, ImagesResponse } from 'openai/resources/images';\n\n/**\n * Enhanced ImagesResponse that includes cost calculation\n */\nexport interface ImageResponseWithUsage extends ImagesResponse {\n usage?: ImagesResponse['usage'] & {\n provider: string;\n model: DiscoImageModel;\n cost: number;\n visionModel?: LLMModel;\n };\n}\n\nexport const DEFAULT_IMAGE_MODEL: DiscoImageModel = 'gpt-image-2';\n\nexport const resolveImageModel = (model?: DiscoImageModel): DiscoImageModel => model ?? DEFAULT_IMAGE_MODEL;\n\nconst MULTIMODAL_VISION_MODELS: ReadonlySet<LLMModel> = new Set(OPENAI_MODELS);\n\n/**\n * Makes a call to the OpenAI Images API to generate images based on a text prompt.\n *\n * This function provides access to OpenAI's image generation capabilities with support for:\n * - Different output formats (JPEG, PNG, WebP)\n * - Various image sizes and quality settings\n * - Multiple image generation in a single call\n * - Base64 encoded image data return\n *\n * @example\n * // Basic image generation\n * const response = await makeImagesCall('A beautiful sunset over mountains');\n *\n * @example\n * // Custom options\n * const response = await makeImagesCall('A birthday cake', {\n * size: '1024x1024',\n * outputFormat: 'png',\n * quality: 'high',\n * count: 2\n * });\n *\n * @param prompt - The text prompt describing the image to generate\n * @param options - Configuration options for image generation. Includes:\n * - size: Image dimensions (uses OpenAI's size options)\n * - outputFormat: Image format ('jpeg', 'png', 'webp') - defaults to 'webp'\n * - compression: Compression level (number) - defaults to 50\n * - quality: Quality setting (uses OpenAI's quality options) - defaults to 'high'\n * - count: Number of images to generate - defaults to 1\n * - background: Background setting for transparency support\n * - moderation: Content moderation level\n * - apiKey: OpenAI API key (optional, falls back to environment variable)\n * @returns Promise<ImageResponseWithUsage> - The image generation response with cost information\n * @throws Error if the API call fails or invalid parameters are provided\n */\nexport async function makeImagesCall(\n prompt: string,\n options: ImageGenerationOptions = {}\n): Promise<ImageResponseWithUsage> {\n const {\n model,\n size = 'auto',\n outputFormat = 'webp',\n compression = 50,\n quality = 'high',\n count = 1,\n background = 'auto',\n moderation = 'auto',\n apiKey,\n visionModel,\n } = options;\n const imageModel = resolveImageModel(model);\n const supportedVisionModel = visionModel && MULTIMODAL_VISION_MODELS.has(visionModel) ? visionModel : undefined;\n if (visionModel && !supportedVisionModel) {\n console.warn(\n `Vision model ${visionModel} is not recognized as a multimodal OpenAI model. Ignoring for image usage metadata.`\n );\n }\n\n // Get API key\n const effectiveApiKey = apiKey || process.env.OPENAI_API_KEY;\n if (!effectiveApiKey) {\n throw new Error('OpenAI API key is not provided and OPENAI_API_KEY environment variable is not set');\n }\n\n // Validate inputs\n if (!prompt || typeof prompt !== 'string') {\n throw new Error('Prompt must be a non-empty string');\n }\n\n if (count && (count < 1 || count > 10)) {\n throw new Error('Count must be between 1 and 10');\n }\n\n if (compression && (compression < 0 || compression > 100)) {\n throw new Error('Compression must be between 0 and 100');\n }\n\n const openai = new OpenAI({\n apiKey: effectiveApiKey,\n });\n\n // Build the request parameters using OpenAI's type\n const requestParams: ImageGenerateParams = {\n model: imageModel,\n prompt,\n n: count || 1,\n size: size || 'auto',\n quality: quality || 'auto',\n background: background || 'auto',\n moderation: moderation || 'auto',\n };\n\n // Add output format if specified\n if (outputFormat) {\n requestParams.output_format = outputFormat;\n }\n\n // Add compression if specified\n if (compression !== undefined) {\n requestParams.output_compression = compression;\n }\n\n try {\n // Make the API call\n const response = await openai.images.generate(requestParams);\n\n // Validate response\n if (!response.data || response.data.length === 0) {\n throw new Error('No images returned from OpenAI Images API');\n }\n\n // Calculate cost\n const cost = calculateImageCost(imageModel, count || 1, quality, size);\n\n // Return the response with enhanced usage information\n const enhancedResponse: ImageResponseWithUsage = {\n ...response,\n usage: {\n // OpenAI Images response may not include usage details per image; preserve if present\n ...(response.usage ?? {\n input_tokens: 0,\n input_tokens_details: { image_tokens: 0, text_tokens: 0 },\n output_tokens: 0,\n total_tokens: 0,\n }),\n provider: 'openai',\n model: imageModel,\n cost,\n ...(supportedVisionModel ? { visionModel: supportedVisionModel } : {}),\n },\n };\n\n return enhancedResponse;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n throw new Error(`OpenAI Images API call failed: ${message}`);\n }\n} \n", "import OpenAI from 'openai';\nimport {\n ChatCompletionContentPart,\n ChatCompletionMessageParam,\n ChatCompletionCreateParams,\n} from 'openai/resources/chat';\n\nimport { calculateCost } from './llm-config';\nimport { parseResponse, normalizeModelName } from './llm-utils';\nimport { LLMResponse, LLMOptions, OpenAIModel, OpenAIResponseFormat, DeepseekModel, LLMModel } from './types';\n\n/**\n * Default options for Deepseek API calls\n */\nconst DEFAULT_DEEPSEEK_OPTIONS = {\n defaultModel: 'deepseek-chat' as DeepseekModel,\n};\n\n/**\n * Checks if the given model is a supported Deepseek model\n * @param model The model to check\n * @returns True if the model is supported, false otherwise\n */\nconst isSupportedDeepseekModel = (model: string): model is DeepseekModel => {\n return ['deepseek-chat', 'deepseek-reasoner'].includes(model);\n};\n\n/**\n * Checks if the given Deepseek model supports JSON output format\n * @param model The model to check\n * @returns True if JSON output is supported, false otherwise\n */\nconst supportsJsonOutput = (model: string): boolean => {\n return model === 'deepseek-chat';\n};\n\n/**\n * Checks if the given Deepseek model supports tool calling\n * @param model The model to check\n * @returns True if tool calling is supported, false otherwise\n */\nconst supportsToolCalling = (model: string): boolean => {\n return model === 'deepseek-chat';\n};\n\n/**\n * Gets the appropriate response format option for Deepseek API\n * \n * @param responseFormat The desired response format\n * @param model The model being used\n * @returns Object representing the Deepseek response format option\n */\nfunction getDeepseekResponseFormatOption(responseFormat: OpenAIResponseFormat, model: string): { type: 'text' } | { type: 'json_object' } {\n // Check if the model supports JSON output\n if (responseFormat !== 'text' && !supportsJsonOutput(model)) {\n console.warn(`Model ${model} does not support JSON output. Using text format instead.`);\n return { type: 'text' };\n }\n\n if (responseFormat === 'text') {\n return { type: 'text' };\n }\n if (responseFormat === 'json' || (typeof responseFormat === 'object' && responseFormat.type === 'json_schema')) {\n return { type: 'json_object' };\n }\n return { type: 'text' };\n}\n\n/**\n * Creates a completion using the Deepseek API\n * \n * @param content The content to pass to the API\n * @param responseFormat The desired format of the response\n * @param options Additional options for the API call\n * @returns Promise resolving to the API response\n */\nasync function createDeepseekCompletion(\n content: string | ChatCompletionContentPart[],\n responseFormat: OpenAIResponseFormat,\n options: LLMOptions = {}\n) {\n // Extract the model or use default\n const modelOption = options.model || DEFAULT_DEEPSEEK_OPTIONS.defaultModel;\n const normalizedModel = normalizeModelName(modelOption);\n \n // Validate model\n if (!isSupportedDeepseekModel(normalizedModel)) {\n throw new Error(`Unsupported Deepseek model: ${normalizedModel}. Please use 'deepseek-chat' or 'deepseek-reasoner'.`);\n }\n\n // Check if tools are requested with a model that doesn't support them\n if (options.tools && options.tools.length > 0 && !supportsToolCalling(normalizedModel)) {\n throw new Error(`Model ${normalizedModel} does not support tool calling.`);\n }\n\n const apiKey = options.apiKey || process.env.DEEPSEEK_API_KEY;\n if (!apiKey) {\n throw new Error('Deepseek API key is not provided and DEEPSEEK_API_KEY environment variable is not set');\n }\n\n // Initialize OpenAI client with Deepseek API URL\n const openai = new OpenAI({\n apiKey,\n baseURL: 'https://api.deepseek.com',\n });\n\n const messages: ChatCompletionMessageParam[] = [];\n\n // Add system message with developer prompt if present\n if (options.developerPrompt) {\n messages.push({\n role: 'system',\n content: options.developerPrompt,\n });\n }\n\n // Add context if present\n if (options.context) {\n messages.push(...options.context);\n }\n\n // Add user content\n if (typeof content === 'string') {\n messages.push({\n role: 'user',\n content,\n });\n } else {\n messages.push({\n role: 'user',\n content,\n });\n }\n\n // If JSON response format, include a hint in the system prompt\n if ((responseFormat === 'json' || (typeof responseFormat === 'object' && responseFormat.type === 'json_schema')) \n && supportsJsonOutput(normalizedModel)) {\n // If there's no system message yet, add one\n if (!messages.some(m => m.role === 'system')) {\n messages.unshift({\n role: 'system',\n content: 'Please respond in valid JSON format.',\n });\n } else {\n // Append to existing system message\n const systemMsgIndex = messages.findIndex(m => m.role === 'system');\n const systemMsg = messages[systemMsgIndex];\n if (typeof systemMsg.content === 'string') {\n messages[systemMsgIndex] = {\n ...systemMsg,\n content: `${systemMsg.content} Please respond in valid JSON format.`,\n };\n }\n }\n }\n\n const queryOptions: ChatCompletionCreateParams = {\n model: normalizedModel,\n messages,\n response_format: getDeepseekResponseFormatOption(responseFormat, normalizedModel),\n temperature: options.temperature,\n top_p: options.top_p,\n frequency_penalty: options.frequency_penalty,\n presence_penalty: options.presence_penalty,\n max_tokens: options.max_completion_tokens,\n };\n\n // Only add tools if the model supports them\n if (options.tools && supportsToolCalling(normalizedModel)) {\n queryOptions.tools = options.tools;\n }\n\n try {\n const completion = await openai.chat.completions.create(queryOptions);\n\n return {\n id: completion.id,\n content: completion.choices[0]?.message?.content || '',\n tool_calls: completion.choices[0]?.message?.tool_calls,\n usage: completion.usage || {\n prompt_tokens: 0,\n completion_tokens: 0,\n total_tokens: 0,\n },\n system_fingerprint: completion.system_fingerprint,\n provider: 'deepseek',\n model: normalizedModel as DeepseekModel,\n };\n } catch (error) {\n console.error('Error calling Deepseek API:', error);\n throw error;\n }\n}\n\n/**\n * Makes a call to the Deepseek AI API.\n *\n * @param content The content to pass to the LLM. Can be a string or an array of content parts.\n * @param responseFormat The format of the response. Defaults to 'json'.\n * @param options Configuration options including model ('deepseek-chat' or 'deepseek-reasoner'), tools, and apiKey.\n * @return A promise that resolves to the response from the Deepseek API.\n */\nexport const makeDeepseekCall = async <T = string>(\n content: string | ChatCompletionContentPart[],\n responseFormat: OpenAIResponseFormat = 'json',\n options: LLMOptions = {}\n): Promise<LLMResponse<T>> => {\n // Set default model if not provided\n const mergedOptions = {\n ...options,\n };\n\n if (!mergedOptions.model) {\n mergedOptions.model = DEFAULT_DEEPSEEK_OPTIONS.defaultModel;\n }\n\n const modelName = normalizeModelName(mergedOptions.model as string);\n \n // Check if the requested response format is compatible with the model\n if (responseFormat !== 'text' && !supportsJsonOutput(modelName)) {\n console.warn(`Model ${modelName} does not support JSON output. Will return error in the response.`);\n return {\n response: {\n error: `Model ${modelName} does not support JSON output format.`\n } as unknown as T,\n usage: {\n prompt_tokens: 0,\n completion_tokens: 0,\n reasoning_tokens: 0,\n provider: 'deepseek',\n model: modelName as DeepseekModel,\n cache_hit_tokens: 0,\n cost: 0,\n },\n tool_calls: undefined,\n };\n }\n\n // Check if tools are requested with a model that doesn't support them\n if (mergedOptions.tools && mergedOptions.tools.length > 0 && !supportsToolCalling(modelName)) {\n console.warn(`Model ${modelName} does not support tool calling. Will return error in the response.`);\n return {\n response: {\n error: `Model ${modelName} does not support tool calling.`\n } as unknown as T,\n usage: {\n prompt_tokens: 0,\n completion_tokens: 0,\n reasoning_tokens: 0,\n provider: 'deepseek',\n model: modelName as DeepseekModel,\n cache_hit_tokens: 0,\n cost: 0,\n },\n tool_calls: undefined,\n };\n }\n\n try {\n const completion = await createDeepseekCompletion(content, responseFormat, mergedOptions);\n\n // Handle tool calls similarly to OpenAI\n if (completion.tool_calls && completion.tool_calls.length > 0) {\n const fnCalls = completion.tool_calls\n .filter((tc) => tc.type === 'function')\n .map((tc) => ({\n id: tc.id,\n name: (tc as Extract<typeof tc, { type: 'function' }>).function.name,\n arguments: JSON.parse((tc as Extract<typeof tc, { type: 'function' }>).function.arguments),\n }));\n return {\n response: { tool_calls: fnCalls } as T,\n usage: {\n prompt_tokens: completion.usage.prompt_tokens,\n completion_tokens: completion.usage.completion_tokens,\n reasoning_tokens: 0, // Deepseek doesn't provide reasoning tokens separately\n provider: 'deepseek',\n model: completion.model,\n cache_hit_tokens: 0, // Not provided directly in API response\n cost: calculateCost(\n 'deepseek',\n completion.model,\n completion.usage.prompt_tokens,\n completion.usage.completion_tokens,\n 0,\n 0 // Cache hit tokens (not provided in the response)\n ),\n },\n tool_calls: completion.tool_calls,\n };\n }\n\n // Handle regular responses\n const parsedResponse = await parseResponse<T>(completion.content, responseFormat);\n if (parsedResponse === null) {\n throw new Error('Failed to parse Deepseek response');\n }\n\n return {\n response: parsedResponse,\n usage: {\n prompt_tokens: completion.usage.prompt_tokens,\n completion_tokens: completion.usage.completion_tokens,\n reasoning_tokens: 0, // Deepseek doesn't provide reasoning tokens separately\n provider: 'deepseek',\n model: completion.model,\n cache_hit_tokens: 0, // Not provided directly in API response\n cost: calculateCost(\n 'deepseek',\n completion.model,\n completion.usage.prompt_tokens,\n completion.usage.completion_tokens,\n 0,\n 0 // Cache hit tokens (not provided in the response)\n ),\n },\n tool_calls: completion.tool_calls,\n };\n } catch (error) {\n // If there's an error due to incompatible features, return a structured error\n console.error('Error in Deepseek API call:', error);\n return {\n response: {\n error: error instanceof Error ? error.message : 'Unknown error'\n } as unknown as T,\n usage: {\n prompt_tokens: 0,\n completion_tokens: 0,\n reasoning_tokens: 0,\n provider: 'deepseek',\n model: modelName as DeepseekModel,\n cache_hit_tokens: 0,\n cost: 0,\n },\n tool_calls: undefined,\n };\n }\n};\n", "// llm-openrouter.ts\n\nimport OpenAI from 'openai';\nimport type {\n ChatCompletionMessageParam,\n ChatCompletionMessageToolCall,\n ChatCompletionTool,\n ChatCompletionToolChoiceOption,\n} from 'openai/resources/chat/completions';\n\nimport { calculateCost, DEFAULT_MODEL } from './llm-config';\nimport { parseResponse, normalizeModelName } from './llm-utils';\nimport type {\n LLMResponse,\n ContextMessage,\n OpenAIResponseFormat,\n LLMModel,\n OpenAIModel,\n DeepseekModel,\n OpenRouterModel,\n} from './types/llm-types';\nimport { isOpenRouterModel } from './types/llm-types';\n\n// Use the SDK's tool choice type, compatible with OpenRouter\ntype ToolChoice = ChatCompletionToolChoiceOption;\n\n// Map our ContextMessage to OpenAI chat message\nfunction mapContextToMessages(context: ContextMessage[]): ChatCompletionMessageParam[] {\n return context.map((msg) => {\n const role = msg.role === 'developer' ? 'system' : msg.role;\n return { role, content: msg.content } as ChatCompletionMessageParam;\n });\n}\n\nfunction toOpenRouterModel(model?: string): string {\n if (model && model.includes('/')) return model;\n const base = normalizeModelName(model || DEFAULT_MODEL);\n return `openai/${base}`;\n}\n\n// Normalize model name for pricing\nfunction normalizeModelForPricing(model: string | undefined): { provider: 'openai' | 'deepseek'; coreModel: string } {\n if (!model) return { provider: 'openai', coreModel: normalizeModelName(DEFAULT_MODEL) };\n const [maybeProvider, maybeModel] = model.includes('/') ? model.split('/') : ['openai', model];\n const provider = (maybeProvider === 'deepseek' ? 'deepseek' : 'openai') as 'openai' | 'deepseek';\n const coreModel = normalizeModelName(maybeModel || model);\n return { provider, coreModel };\n}\n\nexport interface OpenRouterCallOptions {\n apiKey?: string;\n model?: OpenRouterModel | string; // OpenRouter model id (e.g., \"openai/gpt-5-mini\") or plain (\"gpt-5-mini\")\n responseFormat?: 'text' | 'json' | OpenAIResponseFormat;\n tools?: ChatCompletionTool[];\n toolChoice?: ToolChoice;\n context?: ContextMessage[];\n developerPrompt?: string;\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n stop?: string | string[];\n seed?: number;\n // Optional headers for OpenRouter ranking\n referer?: string;\n title?: string;\n}\n\n/**\n * Make a call through OpenRouter using the OpenAI Chat Completions-compatible API.\n * Supports: JSON mode, model selection, message history, and tools.\n */\nexport async function makeOpenRouterCall<T = string>(\n input: string,\n options: OpenRouterCallOptions = {}\n): Promise<LLMResponse<T>> {\n const {\n apiKey = process.env.OPENROUTER_API_KEY,\n model,\n responseFormat = 'text',\n tools,\n toolChoice,\n context,\n developerPrompt,\n temperature = 0.2,\n max_tokens,\n top_p,\n frequency_penalty,\n presence_penalty,\n stop,\n seed,\n referer = process.env.OPENROUTER_SITE_URL,\n title = process.env.OPENROUTER_SITE_NAME,\n } = options;\n\n if (!apiKey) {\n throw new Error('OpenRouter API key is not provided and OPENROUTER_API_KEY is not set');\n }\n\n const client = new OpenAI({\n apiKey,\n baseURL: 'https://openrouter.ai/api/v1',\n defaultHeaders: {\n ...(referer ? { 'HTTP-Referer': referer } : {}),\n ...(title ? { 'X-Title': title } : {}),\n },\n });\n\n const messages: ChatCompletionMessageParam[] = [];\n if (developerPrompt && developerPrompt.trim()) {\n messages.push({ role: 'system', content: developerPrompt });\n }\n if (context && context.length > 0) {\n messages.push(...mapContextToMessages(context));\n }\n messages.push({ role: 'user', content: input });\n\n // Configure response_format\n let response_format: { type: 'json_object' } | undefined;\n let parsingFormat: OpenAIResponseFormat = 'text';\n if (responseFormat === 'json') {\n response_format = { type: 'json_object' };\n parsingFormat = 'json';\n } else if (typeof responseFormat === 'object') {\n response_format = { type: 'json_object' };\n parsingFormat = responseFormat;\n }\n\n const modelId = toOpenRouterModel(model);\n\n const completion = await client.chat.completions.create({\n model: modelId,\n messages,\n response_format,\n tools,\n tool_choice: toolChoice,\n temperature,\n max_tokens,\n top_p,\n frequency_penalty,\n presence_penalty,\n stop,\n seed,\n });\n\n const choice = completion.choices && completion.choices.length > 0 ? completion.choices[0] : undefined;\n const message = (choice && 'message' in choice ? choice.message : undefined) as\n | { content: string | null; role: string; tool_calls?: ChatCompletionMessageToolCall[] }\n | undefined;\n\n const { provider: pricingProvider, coreModel } = normalizeModelForPricing(modelId);\n const promptTokens = completion.usage?.prompt_tokens ?? 0;\n const completionTokens = completion.usage?.completion_tokens ?? 0;\n const cost = calculateCost(pricingProvider, coreModel, promptTokens, completionTokens);\n\n // Tool calls branch: return empty string response and expose tool_calls on LLMResponse\n const hasToolCalls = Array.isArray(message?.tool_calls) && message!.tool_calls!.length > 0;\n if (hasToolCalls) {\n const usageModel: LLMModel = isOpenRouterModel(modelId) ? modelId : (DEFAULT_MODEL as LLMModel);\n return {\n response: '' as T,\n usage: {\n prompt_tokens: promptTokens,\n completion_tokens: completionTokens,\n provider: 'openrouter',\n model: usageModel,\n cost,\n },\n tool_calls: message!.tool_calls as ChatCompletionMessageToolCall[],\n };\n }\n\n const rawText = typeof message?.content === 'string' ? message.content : '';\n const parsed = await parseResponse<T>(rawText, parsingFormat);\n if (parsed === null) {\n throw new Error('Failed to parse OpenRouter response');\n }\n\n // Ensure the model value conforms to LLMModel; otherwise fall back to DEFAULT_MODEL\n const usageModel: LLMModel = isOpenRouterModel(modelId) ? modelId : (DEFAULT_MODEL as LLMModel);\n\n return {\n response: parsed,\n usage: {\n prompt_tokens: promptTokens,\n completion_tokens: completionTokens,\n provider: 'openrouter',\n model: usageModel,\n cost,\n },\n ...(hasToolCalls ? { tool_calls: message!.tool_calls as ChatCompletionMessageToolCall[] } : {}),\n };\n}\n\nexport default makeOpenRouterCall;\n", "// Test file for context functionality\n\nimport {\n disco,\n isOpenAIImageModel,\n isOpenAIModel,\n isOpenRouterModel,\n OPENAI_IMAGE_MODELS,\n OPENAI_MODELS,\n OPENROUTER_MODELS,\n} from './index';\nimport { log as baseLog } from './logging';\nimport { LogOptions } from './types/logging-types';\nimport { AlpacaMarketDataAPI } from './alpaca-market-data-api';\nimport { AlpacaTradingAPI } from './alpaca-trading-api';\nimport { DEFAULT_IMAGE_MODEL, resolveImageModel } from './llm-images';\nimport { calculateCost, calculateImageCost, DEFAULT_MODEL, openAiImageCostByQualityAndSize, openAiImageCosts } from './llm-config';\nimport { supportsTemperature } from './llm-openai';\nimport { z } from 'zod';\n\n// test LLM functionality: test disco.llm.call functions with GPT-5 models and basic calls, json calls, and tool calls\nimport type { LLMModel, ContextMessage, OpenRouterModel, DiscoImageModel } from './types/llm-types';\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport type { AlpacaCredentials, AlpacaAccountType } from './types/alpaca-types';\n\nconst DEBUG_LOGGING = process.env['DEBUG'] === 'true' || false;\n\nconst log = (message: string, options: LogOptions = { type: 'info' }) => {\n if (!DEBUG_LOGGING && options.type === 'debug') {\n return;\n }\n baseLog(message, { ...options, source: 'Test' });\n};\n\nfunction assertNear(actual: number, expected: number, label: string): void {\n const tolerance = 0.000000000001;\n if (Math.abs(actual - expected) > tolerance) {\n throw new Error(`${label} expected ${expected}, received ${actual}`);\n }\n}\n\nfunction testOpenAIModelRegistryAndPricing(): void {\n const directModel: LLMModel = 'gpt-5.6-terra';\n const openRouterModel: OpenRouterModel = 'openai/gpt-5.4-nano';\n\n const gpt56Models: LLMModel[] = ['gpt-5.6', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'];\n for (const model of gpt56Models) {\n if (!isOpenAIModel(model) || !OPENAI_MODELS.includes(model)) {\n throw new Error(`${model} is missing from direct OpenAI model exports`);\n }\n }\n\n if (!isOpenRouterModel(openRouterModel) || !OPENROUTER_MODELS.includes(openRouterModel)) {\n throw new Error(`${openRouterModel} is missing from OpenRouter model exports`);\n }\n\n assertNear(calculateCost('openai', directModel, 100_000, 0), 0.25, 'gpt-5.6-terra input pricing');\n assertNear(calculateCost('openai', directModel, 100_000, 0, 0, 100_000), 0.025, 'gpt-5.6-terra cached input pricing');\n assertNear(calculateCost('openai', directModel, 0, 1_000_000), 15, 'gpt-5.6-terra output pricing');\n assertNear(calculateCost('openai', directModel, 100_000, 0, 0, 0, 100_000), 0.3125, 'gpt-5.6-terra cache-write pricing');\n assertNear(calculateCost('openai', 'gpt-5.6-luna', 100_000, 100_000), 0.7, 'gpt-5.6-luna pricing');\n assertNear(calculateCost('openai', directModel, 1_000_000, 0), 5, 'gpt-5.6-terra long-context input pricing');\n assertNear(calculateCost('openai', 'gpt-5.4-mini', 1_000_000, 1_000_000), 5.25, 'gpt-5.4-mini pricing');\n\n if (DEFAULT_MODEL !== 'gpt-5.6-luna') {\n throw new Error(`Expected gpt-5.6-luna as the default model, received ${DEFAULT_MODEL}`);\n }\n\n log(`${directModel} registry and pricing test passed`);\n}\n\nfunction testGetTradingStartAndEndDates() {\n const testCases = [\n {\n label: 'During market hours',\n endDate: '2025-07-10T09:45:00-04:00',\n days: 1,\n expected: {\n start: '2025-07-09T09:30:00-04:00',\n end: '2025-07-09T16:00:00-04:00',\n },\n },\n {\n label: 'After market close',\n endDate: '2025-07-10T17:00:00-04:00',\n days: 1,\n expected: {\n start: '2025-07-10T09:30:00-04:00',\n end: '2025-07-10T16:00:00-04:00',\n },\n },\n {\n label: 'after extended hours, 3 days',\n endDate: '2025-07-10T20:30:00-04:00',\n days: 3,\n expected: {\n start: '2025-07-08T09:30:00-04:00',\n end: '2025-07-10T16:00:00-04:00',\n },\n },\n {\n label: 'Before market open',\n endDate: '2025-07-11T07:00:00-04:00',\n days: 1,\n expected: {\n start: '2025-07-10T09:30:00-04:00',\n end: '2025-07-10T16:00:00-04:00',\n },\n },\n {\n label: 'Weekend (Saturday)',\n endDate: '2025-07-12T12:00:00-04:00',\n days: 1,\n expected: {\n start: '2025-07-11T09:30:00-04:00',\n end: '2025-07-11T16:00:00-04:00',\n },\n },\n {\n label: 'Multiple trading days (3 days, ending during market hours)',\n endDate: '2025-07-10T10:00:00-04:00',\n days: 3,\n expected: {\n start: '2025-07-08T09:30:00-04:00',\n end: '2025-07-10T16:00:00-04:00',\n },\n },\n {\n label: 'Multiple trading days (3 days, ending after market close)',\n endDate: '2025-07-10T18:00:00-04:00',\n days: 3,\n expected: {\n start: '2025-07-08T09:30:00-04:00',\n end: '2025-07-10T16:00:00-04:00',\n },\n },\n {\n label: '4 days',\n endDate: '2025-07-06T12:00:00-04:00',\n days: 4,\n expected: {\n start: '2025-06-30T09:30:00-04:00',\n end: '2025-07-03T13:00:00-04:00', // Early close\n },\n },\n {\n label: '5 days, skipping weekend and independence day',\n endDate: '2025-07-05T12:00:00-04:00',\n days: 5,\n expected: {\n start: '2025-06-27T09:30:00-04:00',\n end: '2025-07-03T13:00:00-04:00', // Early close\n },\n },\n {\n label: '6 days, skipping weekend and independence day',\n endDate: '2025-07-04T12:00:00-04:00',\n days: 6,\n expected: {\n start: '2025-06-26T09:30:00-04:00',\n end: '2025-07-03T13:00:00-04:00', // Early close\n },\n },\n ];\n\n function formatNY(dt: Date) {\n // Use NY time zone regardless of local system\n const localeStr = dt\n .toLocaleString('en-US', {\n timeZone: 'America/New_York',\n hour12: false,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n })\n .replace(',', '');\n // localeStr: 'MM/DD/YYYY HH:MM:SS'\n const [datePart, timePart] = localeStr.split(' ');\n const [mm, dd, yyyy] = datePart.split('/');\n const [hh, min, ss] = timePart.split(':');\n // Always use -04:00 for July (EDT)\n return `${yyyy}-${mm}-${dd}T${hh}:${min}:${ss}-04:00`;\n }\n\n for (const { label, endDate, days, expected } of testCases) {\n const opts = { endDate: new Date(endDate), days };\n const { startDate, endDate: resultEndDate } = disco.time.getTradingStartAndEndDates(opts);\n const startStr = formatNY(startDate);\n const endStr = formatNY(resultEndDate);\n const pass = startStr === expected.start && endStr === expected.end;\n console.log(`\\nTest: ${label}`);\n console.log(` Input endDate: ${endDate}, days: ${days}`);\n console.log(` Result startDate: ${startStr} ${pass ? '\u2713' : `\u2717 (expected ${expected.start})`}`);\n console.log(` Result endDate: ${endStr} ${pass ? '\u2713' : `\u2717 (expected ${expected.end})`}`);\n }\n}\n\nfunction testGetLastFullTradingDate() {\n const testCases = [\n {\n label: 'During market hours (mid-morning)',\n input: '2025-07-10T10:00:00-04:00',\n expected: '2025-07-09T16:00:00-04:00',\n },\n {\n label: 'During market hours (near market open)',\n input: '2025-07-10T09:35:00-04:00',\n expected: '2025-07-09T16:00:00-04:00',\n },\n {\n label: 'During market hours (near market close)',\n input: '2025-07-10T15:55:00-04:00',\n expected: '2025-07-09T16:00:00-04:00',\n },\n {\n label: 'At exact market open',\n input: '2025-07-10T09:30:00-04:00',\n expected: '2025-07-09T16:00:00-04:00',\n },\n {\n label: 'One minute before market close',\n input: '2025-07-10T15:59:00-04:00',\n expected: '2025-07-09T16:00:00-04:00',\n },\n {\n label: 'At exact market close',\n input: '2025-07-10T16:00:00-04:00',\n expected: '2025-07-10T16:00:00-04:00',\n },\n {\n label: 'After market close (early evening)',\n input: '2025-07-10T17:00:00-04:00',\n expected: '2025-07-10T16:00:00-04:00',\n },\n {\n label: 'After market close (late evening)',\n input: '2025-07-10T23:00:00-04:00',\n expected: '2025-07-10T16:00:00-04:00',\n },\n {\n label: 'Before market open (early morning)',\n input: '2025-07-11T07:00:00-04:00',\n expected: '2025-07-10T16:00:00-04:00',\n },\n {\n label: 'Before market open (very early morning)',\n input: '2025-07-11T02:00:00-04:00',\n expected: '2025-07-10T16:00:00-04:00',\n },\n {\n label: 'During pre-market hours',\n input: '2025-07-11T08:00:00-04:00',\n expected: '2025-07-10T16:00:00-04:00',\n },\n {\n label: 'During after-hours trading',\n input: '2025-07-10T18:30:00-04:00',\n expected: '2025-07-10T16:00:00-04:00',\n },\n {\n label: 'Weekend (Saturday morning)',\n input: '2025-07-12T10:00:00-04:00',\n expected: '2025-07-11T16:00:00-04:00',\n },\n {\n label: 'Weekend (Sunday evening)',\n input: '2025-07-13T20:00:00-04:00',\n expected: '2025-07-11T16:00:00-04:00', // Friday, not Saturday\n },\n {\n label: 'Monday after weekend (before open)',\n input: '2025-07-14T08:00:00-04:00',\n expected: '2025-07-11T16:00:00-04:00',\n },\n {\n label: 'Holiday (Independence Day)',\n input: '2025-07-04T12:00:00-04:00',\n expected: '2025-07-03T13:00:00-04:00', // Early close\n },\n {\n label: 'Day before early close (during market)',\n input: '2025-07-03T11:00:00-04:00',\n expected: '2025-07-02T16:00:00-04:00',\n },\n {\n label: 'Early close day at 12:30 PM (before early close)',\n input: '2025-07-03T12:30:00-04:00',\n expected: '2025-07-02T16:00:00-04:00',\n },\n {\n label: 'Early close day at 1:00 PM (at early close)',\n input: '2025-07-03T13:00:00-04:00',\n expected: '2025-07-03T13:00:00-04:00',\n },\n {\n label: 'Early close day at 2:00 PM (after early close)',\n input: '2025-07-03T14:00:00-04:00',\n expected: '2025-07-03T13:00:00-04:00',\n },\n {\n label: 'After extended hours (late night)',\n input: '2025-07-10T20:30:00-04:00',\n expected: '2025-07-10T16:00:00-04:00',\n },\n {\n label: 'Friday after close',\n input: '2025-07-11T18:00:00-04:00',\n expected: '2025-07-11T16:00:00-04:00',\n },\n {\n label: 'Sunday late evening (end of weekend)',\n input: '2025-07-13T23:59:00-04:00',\n expected: '2025-07-11T16:00:00-04:00', // Friday, not Saturday\n },\n {\n label: 'New Year holiday (Jan 1, 2025)',\n input: '2025-01-01T12:00:00-05:00',\n expected: '2024-12-31T16:00:00-05:00', // Dec 31, 2024 is a regular close day\n },\n {\n label: 'Day after New Year',\n input: '2025-01-02T10:00:00-05:00',\n expected: '2024-12-31T16:00:00-05:00', // Dec 31, 2024 is a regular close day\n },\n {\n label: 'Right now (current time)',\n input: null, // Will use current time\n expected: null, // Will be calculated\n },\n ];\n\n function formatNY(dt: Date) {\n const localeStr = dt\n .toLocaleString('en-US', {\n timeZone: 'America/New_York',\n hour12: false,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n })\n .replace(',', '');\n const [datePart, timePart] = localeStr.split(' ');\n const [mm, dd, yyyy] = datePart.split('/');\n const [hh, min, ss] = timePart.split(':');\n // Determine offset based on month (EDT -04:00 or EST -05:00)\n const month = parseInt(mm, 10);\n const isDST = month >= 3 && month <= 11; // March through November (rough approximation)\n const offset = isDST ? '-04:00' : '-05:00';\n return `${yyyy}-${mm}-${dd}T${hh}:${min}:${ss}${offset}`;\n }\n\n console.log('\\n=== Testing getLastFullTradingDate ===\\n');\n\n for (const { label, input, expected } of testCases) {\n // Handle the current time test case\n if (input === null) {\n const now = new Date();\n const result = disco.time.getLastFullTradingDate();\n const resultStr = formatNY(result);\n const nowStr = now.toLocaleString('en-US', { timeZone: 'America/New_York' });\n console.log(`\\nTest: ${label}`);\n console.log(` Input: now (${nowStr})`);\n console.log(` Result: ${resultStr}`);\n console.log(' Note: Cannot validate expected value for current time, but function executed successfully');\n continue;\n }\n\n const result = disco.time.getLastFullTradingDate(new Date(input));\n const resultStr = formatNY(result);\n const pass = resultStr === expected;\n console.log(`\\nTest: ${label}`);\n console.log(` Input: ${input}`);\n console.log(` Result: ${resultStr} ${pass ? '\u2713' : `\u2717 (expected ${expected})`}`);\n if (!pass) {\n console.error(` FAILED: Expected ${expected}, got ${resultStr}`);\n }\n }\n\n const totalTests = testCases.length;\n const passedTests = testCases.filter((tc) => {\n if (tc.input === null) return true; // Current time test always passes\n const result = disco.time.getLastFullTradingDate(new Date(tc.input));\n return formatNY(result) === tc.expected;\n }).length;\n\n console.log(`\\n=== Summary: ${passedTests}/${totalTests} tests passed ===\\n`);\n}\n\n// Test getMarketStatus with various scenarios\n\nfunction testGetMarketStatus() {\n const testCases = [\n {\n label: 'Weekend (Saturday, market closed)',\n date: '2025-07-12T12:00:00-04:00',\n expected: {\n status: 'closed',\n nextStatus: 'extended hours',\n marketPeriod: 'closed',\n },\n },\n // do before preMarket\n {\n label: 'Before pre-market (market closed)',\n date: '2025-07-10T03:00:00-04:00',\n expected: {\n status: 'closed',\n nextStatus: 'extended hours',\n marketPeriod: 'closed',\n },\n },\n {\n label: 'Pre-market (before open)',\n date: '2025-07-10T08:00:00-04:00', // 8am EDT\n expected: {\n status: 'extended hours',\n nextStatus: 'open',\n marketPeriod: 'preMarket',\n },\n },\n {\n label: 'Extended hours (pre-market)',\n date: '2025-07-10T05:00:00-04:00',\n expected: {\n status: 'extended hours',\n nextStatus: 'open',\n marketPeriod: 'preMarket',\n },\n },\n {\n label: 'Market open (regular)',\n date: '2025-07-10T10:00:00-04:00',\n expected: {\n status: 'open',\n nextStatus: 'extended hours',\n marketPeriod: 'regularMarket',\n },\n },\n {\n label: 'Market open (early market)',\n date: '2025-07-03T09:45:00-04:00', // Early close day\n expected: {\n status: 'open',\n nextStatus: 'extended hours',\n marketPeriod: 'earlyMarket',\n },\n },\n {\n label: 'After market close (extended hours)',\n date: '2025-07-10T17:00:00-04:00',\n expected: {\n status: 'extended hours',\n nextStatus: 'closed',\n marketPeriod: 'afterMarket',\n },\n },\n {\n label: 'After extended hours (market closed)',\n date: '2025-07-10T21:00:00-04:00',\n expected: {\n status: 'closed',\n nextStatus: 'extended hours',\n marketPeriod: 'closed',\n },\n },\n ];\n\n for (const { label, date, expected } of testCases) {\n const result = disco.time.getMarketStatus({ date: new Date(date) });\n const pass =\n result.status === expected.status &&\n result.nextStatus === expected.nextStatus &&\n result.marketPeriod === expected.marketPeriod;\n console.log(`\\nTest: ${label}`);\n console.log(` Input date: ${date}`);\n console.log(` Status: ${result.status} ${pass ? '\u2713' : `\u2717 (expected ${expected.status})`}`);\n console.log(` NextStatus: ${result.nextStatus} ${pass ? '\u2713' : `\u2717 (expected ${expected.nextStatus})`}`);\n console.log(` MarketPeriod: ${result.marketPeriod} ${pass ? '\u2713' : `\u2717 (expected ${expected.marketPeriod})`}`);\n const nextStatusTimeDifferenceMs = result.nextStatusTimeDifference;\n // convert that to a string in the form 'xxh xxm'\n const nextStatusTimeDifferenceStr = `${Math.floor(nextStatusTimeDifferenceMs / (1000 * 60 * 60))}h ${Math.floor(\n (nextStatusTimeDifferenceMs % (1000 * 60 * 60)) / (1000 * 60),\n )}m`;\n console.log(\n ` Next market status: ${result.nextStatus} at ${result.nextStatusTime.toLocaleString('en-US', {\n timeZone: 'America/New_York',\n })} in ${nextStatusTimeDifferenceStr}`,\n );\n if (!pass) {\n console.error(\n ` FAILED: Expected status=${expected.status}, nextStatus=${expected.nextStatus}, marketPeriod=${expected.marketPeriod}, got status=${result.status}, nextStatus=${result.nextStatus}, marketPeriod=${result.marketPeriod}`,\n );\n }\n }\n}\n\n//testGetMarketStatus();\n\n// Test getTradingDate for grouping data\n\nfunction testGetTradingDate() {\n const testCases = [\n {\n label: 'Market day (regular)',\n input: '2025-07-10T10:00:00-04:00',\n expected: '2025-07-10',\n },\n {\n label: 'Weekend (Saturday, should return it anyway )',\n input: '2025-07-12T12:00:00-04:00',\n expected: '2025-07-12',\n },\n {\n label: 'Holiday (Independence Day, should return it anyway)',\n input: '2025-07-04T12:00:00-04:00',\n expected: '2025-07-04',\n },\n {\n label: 'Input as Date object',\n input: new Date('2025-07-10T10:00:00-04:00'),\n expected: '2025-07-10',\n },\n {\n label: 'Input as timestamp (number)',\n input: new Date('2025-07-10T10:00:00-04:00').getTime(),\n expected: '2025-07-10',\n },\n {\n label: 'Input as ISO string',\n input: '2025-07-10T10:00:00-04:00',\n expected: '2025-07-10',\n },\n {\n label: 'Edge case (Jan 24, 2026, early morning EST)',\n input: '2026-01-24T00:30:00-05:00',\n expected: '2026-01-24',\n },\n {\n label: 'Edge case (Jan 24, 2026, late night EST)',\n input: '2026-01-24T23:59:59-05:00',\n expected: '2026-01-24',\n },\n {\n label: 'Edge case (Jan 25, 2026, start of day EST)',\n input: '2026-01-25T00:00:00-05:00',\n expected: '2026-01-25',\n },\n {\n label: 'Edge case (Jan 25, 2026, late night EST)',\n input: '2026-01-25T23:59:59-05:00',\n expected: '2026-01-25',\n },\n {\n label: 'Edge case (Jan 26, 2026, start of day EST)',\n input: '2026-01-26T00:00:00-05:00',\n expected: '2026-01-26',\n },\n {\n label: 'Edge case (Jan 26, 2026, 02:00Z = Jan 25, 21:00 EST)',\n input: '2026-01-26T02:00:00Z',\n expected: '2026-01-25',\n },\n {\n label: 'Edge case (Jan 26, 2026, 04:59:59Z = Jan 25, 23:59:59 EST)',\n input: '2026-01-26T04:59:59Z',\n expected: '2026-01-25',\n },\n {\n label: 'Edge case (Jan 26, 2026, 05:00:00Z = Jan 26, 00:00:00 EST)',\n input: '2026-01-26T05:00:00Z',\n expected: '2026-01-26',\n },\n {\n label: 'Edge case (Jan 24, 2026, timestamp input EST)',\n input: new Date('2026-01-24T12:00:00-05:00').getTime(),\n expected: '2026-01-24',\n },\n ];\n\n for (const { label, input, expected } of testCases) {\n const result = disco.time.getTradingDate(input);\n const pass = result === expected;\n console.log(`\\nTest: ${label}`);\n console.log(` Input: ${input instanceof Date ? input.toISOString() : input}`);\n console.log(` Result: ${result} ${pass ? '\u2713' : `\u2717 (expected ${expected})`}`);\n if (!pass) {\n console.error(` FAILED: Expected ${expected}, got ${result}`);\n }\n }\n}\n\n// Test getMarketOpenClose for various scenarios\n\nfunction testGetMarketOpenClose() {\n const testCases = [\n {\n label: 'Regular market day',\n date: '2025-07-10T10:00:00-04:00',\n expected: {\n marketOpen: true,\n open: '2025-07-10T13:30:00.000Z',\n close: '2025-07-10T20:00:00.000Z',\n },\n },\n {\n label: 'Weekend (Saturday, market closed)',\n date: '2025-07-12T12:00:00-04:00',\n expected: {\n marketOpen: false,\n open: null,\n close: null,\n },\n },\n {\n label: 'Holiday (Independence Day, market closed)',\n date: '2025-07-04T12:00:00-04:00',\n expected: {\n marketOpen: false,\n open: null,\n close: null,\n },\n },\n {\n label: 'Early close day',\n date: '2025-07-03T10:00:00-04:00',\n expected: {\n marketOpen: true,\n open: '2025-07-03T13:30:00.000Z',\n close: '2025-07-03T17:00:00.000Z',\n },\n },\n ];\n\n for (const { label, date, expected } of testCases) {\n const result = disco.time.getMarketOpenClose({ date: new Date(date) });\n const openStr = result.open ? result.open.toISOString() : null;\n const closeStr = result.close ? result.close.toISOString() : null;\n const pass =\n result.marketOpen === expected.marketOpen &&\n (expected.open === null || openStr === expected.open) &&\n (expected.close === null || closeStr === expected.close);\n console.log(`\\nTest: ${label}`);\n console.log(` Input date: ${date}`);\n console.log(` marketOpen: ${result.marketOpen} ${pass ? '\u2713' : `\u2717 (expected ${expected.marketOpen})`}`);\n console.log(` open: ${openStr} ${expected.open === null ? '' : pass ? '\u2713' : `\u2717 (expected ${expected.open})`}`);\n console.log(` close: ${closeStr} ${expected.close === null ? '' : pass ? '\u2713' : `\u2717 (expected ${expected.close})`}`);\n if (!pass) {\n console.error(\n ` FAILED: Expected marketOpen=${expected.marketOpen}, open=${expected.open}, close=${expected.close}, got marketOpen=${result.marketOpen}, open=${openStr}, close=${closeStr}`,\n );\n }\n }\n}\n\n// Test getNYTimeZone for various dates\nfunction testGetNYTimeZone() {\n const { getNYTimeZone } = disco.time;\n const testCases = [\n { label: 'Winter (EST)', date: '2025-01-15T12:00:00-05:00', expected: '-05:00' },\n { label: 'Summer (EDT)', date: '2025-07-15T12:00:00-04:00', expected: '-04:00' },\n { label: 'DST Start (March)', date: '2025-03-10T12:00:00-05:00', expected: '-05:00' },\n { label: 'DST End (November)', date: '2025-11-10T12:00:00-05:00', expected: '-05:00' },\n { label: 'DST Active (June)', date: '2025-06-10T12:00:00-04:00', expected: '-04:00' },\n ];\n for (const { label, date, expected } of testCases) {\n const result = getNYTimeZone(new Date(date));\n const pass = result === expected;\n console.log(`\\nTest: ${label}`);\n console.log(` Input date: ${date}`);\n console.log(` NY Timezone: ${result} ${pass ? '\u2713' : `\u2717 (expected ${expected})`}`);\n if (!pass) {\n console.error(` FAILED: Expected ${expected}, got ${result}`);\n }\n }\n}\n\n// Test getNextMarketDay for various scenarios\nfunction testGetNextMarketDay() {\n const testCases = [\n {\n label: 'Weekday (Wednesday)',\n date: '2025-07-09T12:00:00-04:00',\n expected: '2025-07-10',\n },\n {\n label: 'Weekend (Saturday, should skip to Monday)',\n date: '2025-07-12T12:00:00-04:00',\n expected: '2025-07-14',\n },\n {\n label: 'Holiday (Independence Day, should skip to next market day)',\n date: '2025-07-04T12:00:00-04:00',\n expected: '2025-07-07',\n },\n {\n label: 'Extended hours after 2pm on 3 july',\n date: '2025-07-03T15:00:00-04:00',\n expected: '2025-07-07', // Should skip to next market day\n },\n // Late on 3 July, should skip to next market day\n {\n label: 'Late on 3 July (after early close)',\n date: '2025-07-03T18:00:00-04:00',\n expected: '2025-07-07', // Should skip to next market day\n },\n // during 3 july market hours, should return next monday\n {\n label: 'During 3 July market hours',\n date: '2025-07-03T10:00:00-04:00',\n expected: '2025-07-07', // Should skip to next market day\n },\n // saturday morning, should return next monday\n {\n label: 'Saturday morning',\n date: '2025-07-12T09:00:00-04:00',\n expected: '2025-07-14', // Should skip to next market day\n },\n ];\n for (const { label, date, expected } of testCases) {\n const result = disco.time.getNextMarketDay({ referenceDate: new Date(date) });\n const yyyymmdd = result.yyyymmdd;\n const pass = yyyymmdd === expected;\n console.log(`\\nTest: ${label}`);\n console.log(` Input date: ${date}`);\n console.log(` Next market day: ${yyyymmdd} ${pass ? '\u2713' : `\u2717 (expected ${expected})`}`);\n if (!pass) {\n console.error(` FAILED: Expected ${expected}, got ${yyyymmdd}`);\n }\n }\n}\nfunction testGetPreviousMarketDay() {\n const testCases = [\n {\n label: 'Weekday (Wednesday), midnight',\n date: '2025-07-09T12:00:00-04:00',\n expected: '2025-07-08',\n },\n {\n label: 'Weekend (Monday, previous is Friday)',\n date: '2025-07-14T12:00:00-04:00',\n expected: '2025-07-11',\n },\n // tuesday at 10:30am, previous is monday\n {\n label: 'Tuesday (10:30am), previous is Monday',\n date: '2025-07-08T10:30:00-04:00',\n expected: '2025-07-07',\n },\n {\n label: 'Holiday (Monday 7 July, previous is Friday 3 July, as 4 July is holiday)',\n date: '2025-07-07T12:00:00-04:00',\n expected: '2025-07-03',\n },\n //sunday july 5\n {\n label: 'Sunday (July 6), previous is Thursday (July 3), because of holiday on July 4',\n date: '2025-07-06T12:00:00-04:00',\n expected: '2025-07-03',\n },\n {\n label: 'After extended hours on Monday, previous is 3 July',\n date: '2025-07-07T21:00:00-04:00',\n expected: '2025-07-03',\n },\n\n {\n label: 'Early close (July 3), previous is July 2',\n date: '2025-07-03T15:00:00-04:00',\n expected: '2025-07-02',\n },\n // late on july 3, previous is july 2\n {\n label: 'Late on July 3 (after early close), previous is July 2',\n date: '2025-07-03T18:00:00-04:00',\n expected: '2025-07-02',\n },\n ];\n for (const { label, date, expected } of testCases) {\n const result = disco.time.getPreviousMarketDay({ referenceDate: new Date(date) });\n const yyyymmdd = result.yyyymmdd;\n const pass = yyyymmdd === expected;\n console.log(`\\nTest: ${label}`);\n console.log(` Input date: ${date}`);\n console.log(` Previous market day: ${yyyymmdd} ${pass ? '\u2713' : `\u2717 (expected ${expected})`}`);\n if (!pass) {\n console.error(` FAILED: Expected ${expected}, got ${yyyymmdd}`);\n }\n }\n}\n\nfunction testCountTradingDays() {\n const testCases = [\n {\n label: 'Same day: 12pm to 9am (before market open)',\n startDate: '2025-07-10T12:00:00-04:00',\n endDate: '2025-07-10T09:00:00-04:00',\n expectedError: true,\n },\n {\n label: 'Same day: 12pm to 3:30pm (3.5 hours)',\n startDate: '2025-07-10T12:00:00-04:00',\n endDate: '2025-07-10T15:30:00-04:00',\n expected: {\n hours: 3.5,\n minutes: 210,\n days: 0.54, // 3.5 / 6.5\n },\n },\n {\n label: 'Same day: 9:30am to 4pm (full trading day)',\n startDate: '2025-07-10T09:30:00-04:00',\n endDate: '2025-07-10T16:00:00-04:00',\n expected: {\n hours: 6.5,\n minutes: 390,\n days: 1,\n },\n },\n {\n label: 'Two trading days: 10am to 2pm next day',\n startDate: '2025-07-10T10:00:00-04:00',\n endDate: '2025-07-11T14:00:00-04:00',\n expected: {\n hours: 10.5, // 6 hours first day (10am-4pm) + 4.5 hours second day (9:30am-2pm)\n minutes: 630,\n days: 1.62, // 630 / 390\n },\n },\n {\n label: 'Skip weekend: Friday 2pm to Monday 2pm',\n startDate: '2025-07-11T14:00:00-04:00',\n endDate: '2025-07-14T14:00:00-04:00',\n expected: {\n hours: 6.5, // Friday 2 hours (2pm-4pm) + Monday 4.5 hours (9:30am-2pm)\n minutes: 390,\n days: 1,\n },\n },\n {\n label: 'Skip holiday: July 3 (early close) to July 7',\n startDate: '2025-07-03T10:00:00-04:00',\n endDate: '2025-07-07T10:00:00-04:00',\n expected: {\n hours: 3.5, // 3 hours on July 3 (10am-1pm) + 0.5 hours on July 7 (9:30-10am)\n minutes: 210,\n days: 0.54,\n },\n },\n {\n label: 'Before market open to after market close',\n startDate: '2025-07-10T08:00:00-04:00',\n endDate: '2025-07-10T17:00:00-04:00',\n expected: {\n hours: 6.5, // Only market hours count (9:30am-4pm)\n minutes: 390,\n days: 1,\n },\n },\n ];\n\n for (const { label, startDate, endDate, expected, expectedError } of testCases) {\n try {\n const result = disco.time.countTradingDays(new Date(startDate), new Date(endDate));\n\n if (expectedError) {\n console.log(`\\nTest: ${label}`);\n console.log(` Expected error but got result: ${JSON.stringify(result)} \u2717`);\n continue;\n }\n\n const hoursPass = Math.abs(result.hours - expected!.hours) < 0.01;\n const minutesPass = Math.abs(result.minutes - expected!.minutes) < 0.01;\n const daysPass = Math.abs(result.days - expected!.days) < 0.01;\n const pass = hoursPass && minutesPass && daysPass;\n\n console.log(`\\nTest: ${label}`);\n console.log(` Start: ${startDate}, End: ${endDate}`);\n console.log(` Hours: ${result.hours} ${hoursPass ? '\u2713' : `\u2717 (expected ${expected!.hours})`}`);\n console.log(` Minutes: ${result.minutes} ${minutesPass ? '\u2713' : `\u2717 (expected ${expected!.minutes})`}`);\n console.log(` Days: ${result.days} ${daysPass ? '\u2713' : `\u2717 (expected ${expected!.days})`}`);\n\n if (!pass) {\n console.error(\n ` FAILED: Expected hours=${expected!.hours}, minutes=${expected!.minutes}, days=${expected!.days}`,\n );\n console.error(` Got hours=${result.hours}, minutes=${result.minutes}, days=${result.days}`);\n }\n } catch (error) {\n if (expectedError) {\n console.log(`\\nTest: ${label}`);\n console.log(` Expected error: ${(error as Error).message} \u2713`);\n } else {\n console.log(`\\nTest: ${label}`);\n console.log(` Unexpected error: ${(error as Error).message} \u2717`);\n }\n }\n }\n}\n\nasync function testLLM() {\n if (!process.env.OPENAI_API_KEY) {\n console.log('Skipping OpenAI LLM tests: OPENAI_API_KEY not set');\n return;\n }\n\n const models: LLMModel[] = [DEFAULT_MODEL];\n\n for (const model of models) {\n console.log(`\\nTesting model: ${model}`);\n\n // 1. Basic call\n const basic = await disco.llm.call('What is the capital of France? Respond with only the city name.', { model });\n if (!basic.response || !basic.response.toLowerCase().includes('paris')) {\n throw new Error(`Expected Paris from basic LLM response, received: ${basic.response}`);\n }\n console.log(`Response: ${basic.response}`);\n\n // 2. JSON call\n type CapitalJsonResponse = {\n country: string;\n capital: string;\n };\n const jsonPrompt = 'Return a JSON object with keys country and capital for France.';\n const json = await disco.llm.call<CapitalJsonResponse>(jsonPrompt, { model, responseFormat: 'json' });\n if (json.response.country.toLowerCase() !== 'france' || json.response.capital.toLowerCase() !== 'paris') {\n throw new Error(`Unexpected JSON response from LLM: ${JSON.stringify(json.response)}`);\n }\n console.log(`Response: ${JSON.stringify(json.response)}`);\n\n // 3. Web search\n const searchPrompt = `Use web search to identify the official OpenAI model ID for ${model}. Respond with the model ID only.`;\n const tool = await disco.llm.call(searchPrompt, { model, useWebSearch: true });\n if (!tool.response || !tool.response.includes(model)) {\n throw new Error(`Expected web search response to include ${model}, received: ${tool.response}`);\n }\n console.log(`Response: ${tool.response}`);\n }\n}\n\nasync function testLLMVisionInputs() {\n if (!process.env.OPENAI_API_KEY) {\n console.log('Skipping OpenAI vision input tests: OPENAI_API_KEY not set');\n return;\n }\n\n const imageUrl = 'https://openai-documentation.vercel.app/images/cat_and_otter.png';\n const prompt = 'Name one animal visible in this image. Respond with one lowercase word only.';\n const model: LLMModel = DEFAULT_MODEL;\n\n const httpResponse = await fetch(imageUrl);\n if (!httpResponse.ok) {\n throw new Error(`Failed to fetch test image: ${httpResponse.status} ${httpResponse.statusText}`);\n }\n\n const imageBytes = Buffer.from(await httpResponse.arrayBuffer());\n const dynamicImport = new Function('specifier', 'return import(specifier);') as (specifier: string) => Promise<{\n tmpdir?: () => string;\n writeFile?: (path: string, data: Uint8Array) => Promise<void>;\n rm?: (path: string, options?: { force?: boolean }) => Promise<void>;\n }>;\n const { tmpdir } = await dynamicImport('node:os');\n const { writeFile, rm } = await dynamicImport('node:fs/promises');\n\n if (!tmpdir || !writeFile || !rm) {\n throw new Error('Node.js filesystem helpers are not available for vision input tests');\n }\n\n const tempImagePath = `${tmpdir()}/disco-vision-${Date.now()}.png`;\n await writeFile(tempImagePath, imageBytes);\n\n const isRecognizedAnimal = (value: string): boolean => {\n const normalized = value.toLowerCase().replace(/[^a-z]/g, '');\n return normalized.includes('cat') || normalized.includes('otter');\n };\n\n try {\n const base64Result = await disco.llm.call(prompt, {\n model,\n image: {\n base64: imageBytes.toString('base64'),\n mimeType: 'image/png',\n detail: 'low',\n },\n });\n\n if (!isRecognizedAnimal(base64Result.response)) {\n throw new Error(`Unexpected base64 vision response: ${base64Result.response}`);\n }\n\n const fileResult = await disco.llm.call(prompt, {\n model,\n image: {\n filePath: tempImagePath,\n detail: 'low',\n },\n });\n\n if (!isRecognizedAnimal(fileResult.response)) {\n throw new Error(`Unexpected file vision response: ${fileResult.response}`);\n }\n\n console.log('\\n[OpenAI] Vision input test');\n console.log(' Model:', model);\n console.log(' Base64 response:', base64Result.response);\n console.log(' File response:', fileResult.response);\n } finally {\n await rm(tempImagePath, { force: true });\n }\n}\n\n// OpenRouter tests (requires OPENROUTER_API_KEY)\nasync function testOpenRouter() {\n if (!process.env.OPENROUTER_API_KEY) {\n console.log('Skipping OpenRouter tests: OPENROUTER_API_KEY not set');\n return;\n }\n\n const models: OpenRouterModel[] = [\n 'openai/gpt-5-nano', // inexpensive, tool-capable\n 'google/gemini-2.5-flash-lite',\n 'deepseek/deepseek-chat-v3-0324',\n ];\n\n for (const model of models) {\n console.log(`\\n--- Testing OpenRouter model: ${model} ---`);\n\n // 1) JSON mode\n try {\n const prompt = 'Return a JSON object with keys country and capital for France.';\n const jsonRes = await disco.llm.open(prompt, { model, responseFormat: 'json' });\n console.log('\\n[OpenRouter] JSON mode test');\n console.log(' Response:', jsonRes.response);\n console.log(' Usage:', jsonRes.usage);\n } catch (e) {\n console.error(' OpenRouter JSON mode error:', e);\n }\n\n // 2) Model history (context)\n try {\n const context: ContextMessage[] = [\n { role: 'user', content: 'What is the capital of Germany?' },\n { role: 'assistant', content: 'Berlin.' },\n ];\n const followup = 'Remind me what you said earlier in one word.';\n const histRes = await disco.llm.open(followup, { model, context });\n console.log('\\n[OpenRouter] History test');\n console.log(' Response:', histRes.response);\n } catch (e) {\n console.error(' OpenRouter history error:', e);\n }\n\n // 3) Tool calling\n try {\n const tools: ChatCompletionTool[] = [\n {\n type: 'function',\n function: {\n name: 'add',\n description: 'Add two integers and return the sum',\n parameters: {\n type: 'object',\n properties: {\n a: { type: 'integer' },\n b: { type: 'integer' },\n },\n required: ['a', 'b'],\n },\n },\n },\n ];\n const toolPrompt = 'Please add 2 and 3. If tools are available, call the add function.';\n const toolRes = await disco.llm.open(toolPrompt, { model, tools, toolChoice: 'auto' });\n console.log('\\n[OpenRouter] Tools test');\n if (toolRes.tool_calls && toolRes.tool_calls.length > 0) {\n const summarized = toolRes.tool_calls\n .filter((tc) => tc.type === 'function')\n .map((tc) => ({\n id: tc.id,\n name: (tc as Extract<typeof tc, { type: 'function' }>).function.name,\n arguments: (tc as Extract<typeof tc, { type: 'function' }>).function.arguments,\n }));\n console.log(' Tool calls:', summarized);\n } else {\n console.log(' No tool calls. Model replied:', toolRes.response);\n }\n } catch (e) {\n console.error(' OpenRouter tools error:', e);\n }\n }\n}\n\nasync function testGetPortfolioDailyHistory() {\n console.log('\\n--- Testing getPortfolioDailyHistory with Real API, using paper account credentials ---');\n\n const log = (message: string, options: LogOptions = { type: 'info' }) => {\n baseLog(message, { ...options, source: 'Test' });\n };\n\n if (\n !process.env.ALPACA_TRADING_API_KEY ||\n !process.env.ALPACA_TRADING_SECRET_KEY ||\n !process.env.ALPACA_TRADING_ACCOUNT_TYPE\n ) {\n console.log(\n 'Skipping Alpaca tests: Missing environment variables (ALPACA_TRADING_API_KEY, ALPACA_TRADING_SECRET_KEY, ALPACA_TRADING_ACCOUNT_TYPE)',\n );\n return;\n }\n\n try {\n // Create real Alpaca API instance with credentials from .env\n const { AlpacaTradingAPI } = await import('./alpaca-trading-api');\n\n const credentials = {\n accountName: 'vandelay_industries',\n apiKey: process.env.ALPACA_TRADING_API_KEY!,\n apiSecret: process.env.ALPACA_TRADING_SECRET_KEY!,\n type: process.env.ALPACA_TRADING_ACCOUNT_TYPE! as 'PAPER' | 'LIVE',\n orderType: 'limit' as const,\n engine: 'brain' as const,\n };\n\n const alpacaAPI = new AlpacaTradingAPI(credentials);\n log('Created Alpaca Trading API instance');\n\n // Test getPortfolioDailyHistory with a short period to get recent data\n log('Calling getPortfolioHistory...');\n const rawHistoryResult = await alpacaAPI.getPortfolioHistory({\n period: '7D', // Last 7 days\n timeframe: '1D',\n });\n log(`Received ${rawHistoryResult.equity.length} days of portfolio history`);\n\n console.log(`Raw raw data:`, rawHistoryResult);\n\n // Create combined portfolio history table\n const portfolioTableRaw = rawHistoryResult.timestamp.map((ts, index) => ({\n 'Date number:': ts,\n 'Raw date': new Date(ts * 1000).toISOString(),\n Date: new Date(ts * 1000).toISOString().split('T')[0],\n 'Trading Date': disco.time.getTradingDate(new Date(ts * 1000)),\n Equity: rawHistoryResult.equity[index],\n 'Profit/Loss': rawHistoryResult.profit_loss[index],\n 'Profit/Loss %': rawHistoryResult.profit_loss_pct[index],\n }));\n\n console.table(portfolioTableRaw);\n\n log('Calling getPortfolioDailyHistory...');\n\n const dailyHistoryResult = await alpacaAPI.getPortfolioDailyHistory({\n period: '7D', // Last 7 days\n });\n log(`Received ${dailyHistoryResult.equity.length} days of portfolio history`);\n\n console.log(`Raw daily data:`, dailyHistoryResult);\n\n // Create combined portfolio history table\n const portfolioTableDaily = dailyHistoryResult.timestamp.map((ts, index) => ({\n 'Date number:': ts,\n 'Raw date': new Date(ts * 1000).toISOString(),\n Date: new Date(ts * 1000).toISOString().split('T')[0],\n 'Trading Date': disco.time.getTradingDate(new Date(ts * 1000)),\n Equity: dailyHistoryResult.equity[index],\n 'Profit/Loss': dailyHistoryResult.profit_loss[index],\n 'Profit/Loss %': dailyHistoryResult.profit_loss_pct[index],\n }));\n\n console.table(portfolioTableDaily);\n } catch (error) {\n console.error('\u2717 Test failed:', error);\n if (error instanceof Error) {\n console.error('Error message:', error.message);\n console.error('Stack trace:', error.stack);\n }\n }\n}\n\nasync function testCryptoMarketData() {\n console.log('\\n--- Testing Crypto Market Data API ---');\n\n const log = (message: string, options: LogOptions = { type: 'info' }) => {\n baseLog(message, { ...options, source: 'Test' });\n };\n\n if (!process.env.ALPACA_API_KEY || !process.env.ALPACA_SECRET_KEY) {\n console.log('Skipping Alpaca crypto tests: Missing environment variables (ALPACA_API_KEY, ALPACA_SECRET_KEY)');\n return;\n }\n\n try {\n const { marketDataAPI } = await import('./alpaca-market-data-api');\n const { ALPACA_CRYPTO_PAIRS } = await import('./types/alpaca-crypto-pairs');\n\n // Test symbols - using popular crypto pairs\n const testSymbols = ['BTC/USD', 'ETH/USD', 'DOGE/USD'];\n log(`Testing with crypto symbols: ${testSymbols.join(', ')}`);\n\n // 1. Test latest crypto bars\n console.log('\\n[Crypto] Testing latest bars...');\n try {\n const latestBars = await marketDataAPI.getCryptoLatestBars(testSymbols);\n console.log(`\u2713 Retrieved latest bars for ${Object.keys(latestBars.bars).length} symbols`);\n\n // Show sample data for first symbol\n const firstSymbol = Object.keys(latestBars.bars)[0];\n if (firstSymbol) {\n const bar = latestBars.bars[firstSymbol];\n console.log(\n ` ${firstSymbol}: Open=$${bar.o.toFixed(4)}, Close=$${bar.c.toFixed(4)}, Volume=${bar.v.toLocaleString()}`,\n );\n }\n } catch (error) {\n console.error('\u2717 Latest bars test failed:', error);\n }\n\n // 2. Test latest crypto quotes\n console.log('\\n[Crypto] Testing latest quotes...');\n try {\n const latestQuotes = await marketDataAPI.getCryptoLatestQuotes(testSymbols);\n console.log(`\u2713 Retrieved latest quotes for ${Object.keys(latestQuotes.quotes).length} symbols`);\n\n // Show sample data for first symbol\n const firstSymbol = Object.keys(latestQuotes.quotes)[0];\n if (firstSymbol) {\n const quote = latestQuotes.quotes[firstSymbol];\n console.log(\n ` ${firstSymbol}: Bid=$${quote.bp.toFixed(4)}, Ask=$${quote.ap.toFixed(4)}, Spread=$${(\n quote.ap - quote.bp\n ).toFixed(4)}`,\n );\n }\n } catch (error) {\n console.error('\u2717 Latest quotes test failed:', error);\n }\n\n // 3. Test latest crypto trades\n console.log('\\n[Crypto] Testing latest trades...');\n try {\n const latestTrades = await marketDataAPI.getCryptoLatestTrades(testSymbols);\n console.log(`\u2713 Retrieved latest trades for ${Object.keys(latestTrades.trades).length} symbols`);\n\n // Show sample data for first symbol\n const firstSymbol = Object.keys(latestTrades.trades)[0];\n if (firstSymbol) {\n const trade = latestTrades.trades[firstSymbol];\n console.log(\n ` ${firstSymbol}: Price=$${trade.p.toFixed(4)}, Size=${trade.s.toLocaleString()}, Taker=${trade.tks}`,\n );\n }\n } catch (error) {\n console.error('\u2717 Latest trades test failed:', error);\n }\n\n // 4. Test crypto snapshots\n console.log('\\n[Crypto] Testing snapshots...');\n try {\n const snapshots = await marketDataAPI.getCryptoSnapshots(testSymbols);\n console.log(`\u2713 Retrieved snapshots for ${Object.keys(snapshots.snapshots).length} symbols`);\n\n // Show sample data for first symbol\n const firstSymbol = Object.keys(snapshots.snapshots)[0];\n if (firstSymbol) {\n const snapshot = snapshots.snapshots[firstSymbol];\n console.log(` ${firstSymbol} snapshot:`);\n if (snapshot.latestTrade) {\n console.log(` Latest trade: $${snapshot.latestTrade.p.toFixed(4)}`);\n }\n if (snapshot.latestQuote) {\n console.log(\n ` Latest quote: $${snapshot.latestQuote.bp.toFixed(4)} x $${snapshot.latestQuote.ap.toFixed(4)}`,\n );\n }\n if (snapshot.dailyBar) {\n console.log(\n ` Daily bar: Open=$${snapshot.dailyBar.o.toFixed(4)}, Close=$${snapshot.dailyBar.c.toFixed(4)}`,\n );\n }\n }\n } catch (error) {\n console.error('\u2717 Snapshots test failed:', error);\n }\n\n // 5. Test crypto orderbooks\n console.log('\\n[Crypto] Testing orderbooks...');\n try {\n const orderbooks = await marketDataAPI.getCryptoLatestOrderbooks(testSymbols);\n console.log(`\u2713 Retrieved orderbooks for ${Object.keys(orderbooks.orderbooks).length} symbols`);\n\n // Show sample data for first symbol\n const firstSymbol = Object.keys(orderbooks.orderbooks)[0];\n if (firstSymbol) {\n const orderbook = orderbooks.orderbooks[firstSymbol];\n console.log(` ${firstSymbol} orderbook:`);\n console.log(` Best bid: $${orderbook.b[0]?.p.toFixed(4)} (size: ${orderbook.b[0]?.s.toLocaleString()})`);\n console.log(` Best ask: $${orderbook.a[0]?.p.toFixed(4)} (size: ${orderbook.a[0]?.s.toLocaleString()})`);\n console.log(` Bid depth: ${orderbook.b.length} levels, Ask depth: ${orderbook.a.length} levels`);\n }\n } catch (error) {\n console.error('\u2717 Orderbooks test failed:', error);\n }\n\n // 6. Test historical crypto bars (small sample)\n console.log('\\n[Crypto] Testing historical bars...');\n try {\n const endDate = new Date();\n const startDate = new Date(endDate.getTime() - 24 * 60 * 60 * 1000); // 24 hours ago\n\n const historicalBars = await marketDataAPI.getCryptoHistoricalBars({\n symbols: ['BTC/USD'], // Just test one symbol to avoid too much data\n timeframe: '1Hour',\n start: startDate.toISOString(),\n end: endDate.toISOString(),\n limit: 10,\n });\n\n console.log(`\u2713 Retrieved historical bars for ${Object.keys(historicalBars.bars).length} symbols`);\n\n const btcBars = historicalBars.bars['BTC/USD'];\n if (btcBars && btcBars.length > 0) {\n console.log(` BTC/USD: ${btcBars.length} bars retrieved`);\n const { AlpacaMarketDataAPI } = await import('./alpaca-market-data-api');\n const analysis = AlpacaMarketDataAPI.analyzeCryptoBars(btcBars);\n console.log(` Analysis: ${analysis}`);\n }\n } catch (error) {\n console.error('\u2717 Historical bars test failed:', error);\n }\n\n // 7. Test historical crypto quotes (small sample)\n console.log('\\n[Crypto] Testing historical quotes...');\n try {\n const endDate = new Date();\n const startDate = new Date(endDate.getTime() - 2 * 60 * 60 * 1000); // 2 hours ago\n\n const historicalQuotes = await marketDataAPI.getCryptoHistoricalQuotes({\n symbols: ['ETH/USD'], // Just test one symbol\n start: startDate.toISOString(),\n end: endDate.toISOString(),\n limit: 10,\n });\n\n console.log(`\u2713 Retrieved historical quotes for ${Object.keys(historicalQuotes.quotes).length} symbols`);\n\n const ethQuotes = historicalQuotes.quotes['ETH/USD'];\n if (ethQuotes && ethQuotes.length > 0) {\n console.log(` ETH/USD: ${ethQuotes.length} quotes retrieved`);\n const firstQuote = ethQuotes[0];\n const lastQuote = ethQuotes[ethQuotes.length - 1];\n console.log(` First quote: Bid=$${firstQuote.bp.toFixed(4)}, Ask=$${firstQuote.ap.toFixed(4)}`);\n console.log(` Last quote: Bid=$${lastQuote.bp.toFixed(4)}, Ask=$${lastQuote.ap.toFixed(4)}`);\n }\n } catch (error) {\n console.error('\u2717 Historical quotes test failed:', error);\n }\n\n // 8. Test historical crypto trades (small sample)\n console.log('\\n[Crypto] Testing historical trades...');\n try {\n const endDate = new Date();\n const startDate = new Date(endDate.getTime() - 2 * 60 * 60 * 1000); // 2 hours ago\n\n const historicalTrades = await marketDataAPI.getCryptoHistoricalTrades({\n symbols: ['DOGE/USD'], // Just test one symbol\n start: startDate.toISOString(),\n end: endDate.toISOString(),\n limit: 10,\n });\n\n console.log(`\u2713 Retrieved historical trades for ${Object.keys(historicalTrades.trades).length} symbols`);\n\n const dogeTrades = historicalTrades.trades['DOGE/USD'];\n if (dogeTrades && dogeTrades.length > 0) {\n console.log(` DOGE/USD: ${dogeTrades.length} trades retrieved`);\n const totalVolume = dogeTrades.reduce((sum, trade) => sum + trade.s, 0);\n const avgPrice = dogeTrades.reduce((sum, trade) => sum + trade.p, 0) / dogeTrades.length;\n console.log(` Total volume: ${totalVolume.toLocaleString()}, Avg price: $${avgPrice.toFixed(6)}`);\n }\n } catch (error) {\n console.error('\u2717 Historical trades test failed:', error);\n }\n\n // 9. Test with available crypto pairs from our types\n console.log('\\n[Crypto] Testing with available crypto pairs...');\n try {\n const availablePairs = ALPACA_CRYPTO_PAIRS.slice(0, 5).map((pair) => pair.symbol); // Test first 5 pairs\n console.log(`Testing with pairs: ${availablePairs.join(', ')}`);\n\n const pairsBars = await marketDataAPI.getCryptoLatestBars(availablePairs);\n console.log(`\u2713 Retrieved latest bars for ${Object.keys(pairsBars.bars).length} pairs from ALPACA_CRYPTO_PAIRS`);\n\n // Show info about each pair\n availablePairs.forEach((symbol) => {\n const pair = ALPACA_CRYPTO_PAIRS.find((p) => p.symbol === symbol);\n const bar = pairsBars.bars[symbol];\n if (pair && bar) {\n console.log(` ${pair.name}: $${bar.c.toFixed(6)} (min order: ${pair.min_order_size})`);\n }\n });\n } catch (error) {\n console.error('\u2717 Available crypto pairs test failed:', error);\n }\n\n console.log('\\n\u2713 All crypto market data tests completed!');\n } catch (error) {\n console.error('\u2717 Crypto tests setup failed:', error);\n if (error instanceof Error) {\n console.error('Error message:', error.message);\n }\n }\n}\n\nasync function testWebSocketConnectAndDisconnect() {\n console.log('\\n--- Testing WebSocket Connect and Disconnect ---');\n const log = (message: string, options: LogOptions = { type: 'info' }) => {\n baseLog(message, { ...options, source: 'Test' });\n };\n\n // Ensure market data env vars are populated from TRADING_* if needed\n if (!process.env.ALPACA_API_KEY && process.env.ALPACA_TRADING_API_KEY) {\n process.env.ALPACA_API_KEY = process.env.ALPACA_TRADING_API_KEY;\n }\n if (!process.env.ALPACA_SECRET_KEY && process.env.ALPACA_TRADING_SECRET_KEY) {\n process.env.ALPACA_SECRET_KEY = process.env.ALPACA_TRADING_SECRET_KEY;\n }\n if (!process.env.ALPACA_ACCOUNT_TYPE && process.env.ALPACA_TRADING_ACCOUNT_TYPE) {\n process.env.ALPACA_ACCOUNT_TYPE = process.env.ALPACA_TRADING_ACCOUNT_TYPE;\n }\n\n const apiKey = process.env.ALPACA_API_KEY;\n const secretKey = process.env.ALPACA_SECRET_KEY;\n if (!apiKey || !secretKey) {\n console.error('Missing Alpaca API credentials. Check .env ALPACA_TRADING_API_KEY/SECRET or ALPACA_API_KEY/SECRET.');\n return;\n }\n\n const md = AlpacaMarketDataAPI.getInstance();\n const symbols: string[] = ['SPY', 'TSLA', 'AAPL'];\n\n // Track received minute bars per symbol\n const barCounts: Record<string, number> = Object.fromEntries(symbols.map((s) => [s, 0]));\n const firstSeenAt: Record<string, string> = {};\n\n // Connect and subscribe to minute bars\n log(`Connecting stock stream and subscribing to minute bars for ${symbols.join(', ')}`);\n md.connectStockStream();\n md.subscribe('stock', { bars: symbols });\n\n const formatNY = (d: Date): string => d.toLocaleString('en-US', { timeZone: 'America/New_York' });\n\n const onBar = (msg: import('./types/alpaca-types').AlpacaBarStream) => {\n if (!symbols.includes(msg.S)) return;\n barCounts[msg.S] += 1;\n if (!firstSeenAt[msg.S]) {\n firstSeenAt[msg.S] = formatNY(new Date(msg.t));\n }\n log(\n `Bar ${msg.S} o=${msg.o.toFixed(2)} h=${msg.h.toFixed(2)} l=${msg.l.toFixed(2)} c=${msg.c.toFixed(2)} @ ${formatNY(\n new Date(msg.t),\n )}`,\n { type: 'debug', symbol: msg.S },\n );\n };\n\n md.on('stock-b', onBar);\n\n // Wait until we have at least 2 bars per symbol, or timeout after 3 minutes\n const minBarsPerSymbol = 2;\n const timeoutMs = 3 * 60 * 1000;\n\n const done = await new Promise<boolean>((resolve) => {\n const startedAt = Date.now();\n const interval = setInterval(() => {\n const hasAll = symbols.every((s) => barCounts[s] >= minBarsPerSymbol);\n const elapsed = Date.now() - startedAt;\n if (hasAll) {\n clearInterval(interval);\n resolve(true);\n } else if (elapsed >= timeoutMs) {\n clearInterval(interval);\n resolve(false);\n }\n }, 1000);\n });\n\n // Unsubscribe and disconnect\n md.unsubscribe('stock', { bars: symbols });\n md.disconnectStockStream();\n md.removeListener('stock-b', onBar);\n\n // Report results\n const nowNY = formatNY(new Date());\n console.log('\\nStock bars summary:');\n symbols.forEach((s) => {\n console.log(` ${s}: ${barCounts[s]} bars (first at ${firstSeenAt[s] ?? 'n/a'}; finished at ${nowNY})`);\n });\n if (done) {\n console.log('\u2713 Received minimum bars for all symbols and disconnected.');\n } else {\n console.warn('Completed with timeout before receiving minimum bars for all symbols.');\n }\n}\n\nasync function testGetAssetsShortableFilter() {\n console.log('\\n--- Testing getAssets params and shortable filter ---');\n\n const log = (message: string, options: LogOptions = { type: 'info' }) => {\n baseLog(message, { ...options, source: 'Test' });\n };\n\n if (!process.env.ALPACA_API_KEY || !process.env.ALPACA_SECRET_KEY) {\n console.log('Skipping getAssets test: Missing environment variables (ALPACA_API_KEY, ALPACA_SECRET_KEY)');\n return;\n }\n\n try {\n const { marketDataAPI } = await import('./alpaca-market-data-api');\n\n // 1) Default call: should filter to shortable && easy_to_borrow and default to active us_equity\n log('Calling getAssets() with defaults');\n const filtered = await marketDataAPI.getAssets();\n console.log(`Received ${filtered.length} filtered assets (default params)`);\n\n const allFilteredValid = filtered.every((a) => a.shortable === true && a.easy_to_borrow === true);\n if (!allFilteredValid) {\n console.error('\u2717 Default getAssets() included assets that are not shortable and easy_to_borrow');\n } else {\n console.log('\u2713 Default getAssets() correctly filtered shortable and easy_to_borrow assets');\n }\n\n // 2) Unfiltered call: shortable=false\n log('Calling getAssets({ shortable: false })');\n const unfiltered = await marketDataAPI.getAssets({ shortable: false });\n console.log(`Received ${unfiltered.length} unfiltered assets`);\n\n if (unfiltered.length < filtered.length) {\n console.warn('Unfiltered list is smaller than filtered. This is unexpected but not fatal.');\n } else {\n console.log('\u2713 Unfiltered list length is >= filtered list length');\n }\n\n // 3) Specific constraints: inactive crypto, not asserting non-empty\n log(\"Calling getAssets({ status: 'inactive', asset_class: 'crypto', shortable: false })\");\n const inactiveCrypto = await marketDataAPI.getAssets({\n status: 'inactive',\n asset_class: 'crypto',\n shortable: false,\n });\n console.log(`Received ${inactiveCrypto.length} inactive crypto assets`);\n if (inactiveCrypto.length > 0) {\n const valid = inactiveCrypto.every((a) => a.class === 'crypto' && a.status === 'inactive');\n if (!valid) {\n console.error('\u2717 Inactive crypto request returned assets with mismatched class or status');\n } else {\n console.log('\u2713 Inactive crypto request returned only crypto with inactive status');\n }\n } else {\n console.log('No inactive crypto assets returned; skipping class/status assertions.');\n }\n } catch (error) {\n console.error('\u2717 getAssets test failed:', error);\n if (error instanceof Error) {\n console.error('Error message:', error.message);\n console.error('Stack trace:', error.stack);\n }\n }\n}\n\nasync function testMarketDataAPI() {\n console.log('\\n--- Testing Market Data API ---');\n\n const log = (message: string, options: LogOptions = { type: 'info' }) => {\n baseLog(message, { ...options, source: 'Test' });\n };\n\n if (!process.env.ALPACA_API_KEY || !process.env.ALPACA_SECRET_KEY) {\n console.log('Skipping Market Data API tests: Missing environment variables (ALPACA_API_KEY, ALPACA_SECRET_KEY)');\n return;\n }\n\n try {\n const { marketDataAPI } = await import('./alpaca-market-data-api');\n\n // Test 1: Single symbol request - verify only 1 symbol is returned\n console.log('\\n[Test 1] Single symbol historical bars');\n try {\n const testSymbol = 'AAPL';\n const endDate = new Date('2023-02-28T23:59:59.999Z');\n const startDate = new Date('2023-02-24T00:00:00.000Z');\n\n const response = await marketDataAPI.getHistoricalBars({\n symbols: [testSymbol],\n timeframe: '1Min',\n start: startDate.toISOString(),\n end: endDate.toISOString(),\n });\n\n const symbolsInResponse = Object.keys(response.bars);\n const barsCount = response.bars[testSymbol]?.length || 0;\n\n console.log(` Requested symbols: 1 (${testSymbol})`);\n console.log(` Symbols in response: ${symbolsInResponse.length} (${symbolsInResponse.join(', ')})`);\n console.log(` Bars for ${testSymbol}: ${barsCount}`);\n\n if (symbolsInResponse.length !== 1) {\n console.error(` \u2717 FAILED: Expected 1 symbol in response, got ${symbolsInResponse.length}`);\n } else if (symbolsInResponse[0] !== testSymbol) {\n console.error(` \u2717 FAILED: Expected symbol ${testSymbol}, got ${symbolsInResponse[0]}`);\n } else {\n console.log(` \u2713 Single symbol request correctly returned 1 symbol`);\n }\n } catch (error) {\n console.error(' \u2717 Test 1 failed:', error);\n }\n\n // Test 2: Multiple symbols request - verify correct count\n console.log('\\n[Test 2] Multiple symbols (3) historical bars');\n try {\n const testSymbols = ['AAPL', 'MSFT', 'GOOGL'];\n const endDate = new Date('2023-02-28T23:59:59.999Z');\n const startDate = new Date('2023-02-24T00:00:00.000Z');\n\n const response = await marketDataAPI.getHistoricalBars({\n symbols: testSymbols,\n timeframe: '1Min',\n start: startDate.toISOString(),\n end: endDate.toISOString(),\n });\n\n const symbolsInResponse = Object.keys(response.bars);\n const totalBars = Object.values(response.bars).reduce((sum, bars) => sum + bars.length, 0);\n\n console.log(` Requested symbols: ${testSymbols.length} (${testSymbols.join(', ')})`);\n console.log(` Symbols in response: ${symbolsInResponse.length} (${symbolsInResponse.join(', ')})`);\n console.log(` Total bars: ${totalBars}`);\n\n // Check each requested symbol\n const missingSymbols = testSymbols.filter((s) => !symbolsInResponse.includes(s));\n const extraSymbols = symbolsInResponse.filter((s) => !testSymbols.includes(s));\n\n if (missingSymbols.length > 0) {\n console.error(` \u2717 FAILED: Missing symbols: ${missingSymbols.join(', ')}`);\n }\n if (extraSymbols.length > 0) {\n console.error(` \u2717 FAILED: Extra symbols not requested: ${extraSymbols.join(', ')}`);\n }\n if (symbolsInResponse.length !== testSymbols.length) {\n console.error(\n ` \u2717 FAILED: Expected ${testSymbols.length} symbols in response, got ${symbolsInResponse.length}`,\n );\n } else if (missingSymbols.length === 0 && extraSymbols.length === 0) {\n console.log(` \u2713 Multiple symbols request correctly returned ${testSymbols.length} symbols`);\n }\n\n // Show bars per symbol\n testSymbols.forEach((symbol) => {\n const count = response.bars[symbol]?.length || 0;\n console.log(` ${symbol}: ${count} bars`);\n });\n } catch (error) {\n console.error(' \u2717 Test 2 failed:', error);\n }\n\n // Test 3: Latest bars - single symbol\n console.log('\\n[Test 3] Latest bars for single symbol');\n try {\n const testSymbol = 'TSLA';\n const response = await marketDataAPI.getLatestBars([testSymbol]);\n\n const symbolsInResponse = Object.keys(response.bars);\n\n console.log(` Requested symbols: 1 (${testSymbol})`);\n console.log(` Symbols in response: ${symbolsInResponse.length} (${symbolsInResponse.join(', ')})`);\n\n if (symbolsInResponse.length !== 1) {\n console.error(` \u2717 FAILED: Expected 1 symbol in response, got ${symbolsInResponse.length}`);\n } else if (symbolsInResponse[0] !== testSymbol) {\n console.error(` \u2717 FAILED: Expected symbol ${testSymbol}, got ${symbolsInResponse[0]}`);\n } else {\n console.log(` \u2713 Latest bars correctly returned 1 symbol`);\n }\n } catch (error) {\n console.error(' \u2717 Test 3 failed:', error);\n }\n\n // Test 4: Latest bars - multiple symbols\n console.log('\\n[Test 4] Latest bars for multiple symbols');\n try {\n const testSymbols = ['SPY', 'QQQ', 'IWM', 'DIA'];\n const response = await marketDataAPI.getLatestBars(testSymbols);\n\n const symbolsInResponse = Object.keys(response.bars);\n\n console.log(` Requested symbols: ${testSymbols.length} (${testSymbols.join(', ')})`);\n console.log(` Symbols in response: ${symbolsInResponse.length} (${symbolsInResponse.join(', ')})`);\n\n const missingSymbols = testSymbols.filter((s) => !symbolsInResponse.includes(s));\n const extraSymbols = symbolsInResponse.filter((s) => !testSymbols.includes(s));\n\n if (missingSymbols.length > 0) {\n console.error(` \u2717 FAILED: Missing symbols: ${missingSymbols.join(', ')}`);\n }\n if (extraSymbols.length > 0) {\n console.error(` \u2717 FAILED: Extra symbols not requested: ${extraSymbols.join(', ')}`);\n }\n if (symbolsInResponse.length !== testSymbols.length) {\n console.error(\n ` \u2717 FAILED: Expected ${testSymbols.length} symbols in response, got ${symbolsInResponse.length}`,\n );\n } else if (missingSymbols.length === 0 && extraSymbols.length === 0) {\n console.log(` \u2713 Latest bars correctly returned ${testSymbols.length} symbols`);\n }\n } catch (error) {\n console.error(' \u2717 Test 4 failed:', error);\n }\n\n // Test 5: Latest quotes - verify symbol count\n console.log('\\n[Test 5] Latest quotes for multiple symbols');\n try {\n const testSymbols = ['AAPL', 'NVDA', 'AMD'];\n const response = await marketDataAPI.getLatestQuotes(testSymbols);\n\n const symbolsInResponse = Object.keys(response.quotes);\n\n console.log(` Requested symbols: ${testSymbols.length} (${testSymbols.join(', ')})`);\n console.log(` Symbols in response: ${symbolsInResponse.length} (${symbolsInResponse.join(', ')})`);\n\n const missingSymbols = testSymbols.filter((s) => !symbolsInResponse.includes(s));\n const extraSymbols = symbolsInResponse.filter((s) => !testSymbols.includes(s));\n\n if (missingSymbols.length > 0) {\n console.error(` \u2717 FAILED: Missing symbols: ${missingSymbols.join(', ')}`);\n }\n if (extraSymbols.length > 0) {\n console.error(` \u2717 FAILED: Extra symbols not requested: ${extraSymbols.join(', ')}`);\n }\n if (symbolsInResponse.length !== testSymbols.length) {\n console.error(\n ` \u2717 FAILED: Expected ${testSymbols.length} symbols in response, got ${symbolsInResponse.length}`,\n );\n } else if (missingSymbols.length === 0 && extraSymbols.length === 0) {\n console.log(` \u2713 Latest quotes correctly returned ${testSymbols.length} symbols`);\n }\n } catch (error) {\n console.error(' \u2717 Test 5 failed:', error);\n }\n\n // Test 6: Latest trades - verify symbol count\n console.log('\\n[Test 6] Latest trades for multiple symbols');\n try {\n const testSymbols = ['META', 'AMZN'];\n const response = await marketDataAPI.getLatestTrades(testSymbols);\n\n const symbolsInResponse = Object.keys(response.trades);\n\n console.log(` Requested symbols: ${testSymbols.length} (${testSymbols.join(', ')})`);\n console.log(` Symbols in response: ${symbolsInResponse.length} (${symbolsInResponse.join(', ')})`);\n\n const missingSymbols = testSymbols.filter((s) => !symbolsInResponse.includes(s));\n const extraSymbols = symbolsInResponse.filter((s) => !testSymbols.includes(s));\n\n if (missingSymbols.length > 0) {\n console.error(` \u2717 FAILED: Missing symbols: ${missingSymbols.join(', ')}`);\n }\n if (extraSymbols.length > 0) {\n console.error(` \u2717 FAILED: Extra symbols not requested: ${extraSymbols.join(', ')}`);\n }\n if (symbolsInResponse.length !== testSymbols.length) {\n console.error(\n ` \u2717 FAILED: Expected ${testSymbols.length} symbols in response, got ${symbolsInResponse.length}`,\n );\n } else if (missingSymbols.length === 0 && extraSymbols.length === 0) {\n console.log(` \u2713 Latest trades correctly returned ${testSymbols.length} symbols`);\n }\n } catch (error) {\n console.error(' \u2717 Test 6 failed:', error);\n }\n\n // Test 7: Empty symbols array\n console.log('\\n[Test 7] Empty symbols array handling');\n try {\n const response = await marketDataAPI.getLatestQuotes([]);\n\n const symbolsInResponse = Object.keys(response.quotes);\n\n console.log(` Requested symbols: 0 (empty array)`);\n console.log(` Symbols in response: ${symbolsInResponse.length}`);\n\n if (symbolsInResponse.length === 0) {\n console.log(` \u2713 Empty symbols array correctly returned empty response`);\n } else {\n console.error(` \u2717 FAILED: Expected 0 symbols in response, got ${symbolsInResponse.length}`);\n }\n } catch (error) {\n console.error(' \u2717 Test 7 failed:', error);\n }\n\n // Test 8: Historical bars with date range that spans multiple pages\n console.log('\\n[Test 8] Historical bars with pagination (longer date range)');\n try {\n const testSymbols = ['SPY'];\n const endDate = new Date('2023-03-15T23:59:59.999Z');\n const startDate = new Date('2023-03-01T01:00:00.000Z');\n\n const response = await marketDataAPI.getHistoricalBars({\n symbols: testSymbols,\n timeframe: '1Min',\n start: startDate.toISOString(),\n end: endDate.toISOString(),\n });\n\n const symbolsInResponse = Object.keys(response.bars);\n const totalBars = Object.values(response.bars).reduce((sum, bars) => sum + bars.length, 0);\n\n console.log(` Requested symbols: ${testSymbols.length} (${testSymbols.join(', ')})`);\n console.log(` Symbols in response: ${symbolsInResponse.length} (${symbolsInResponse.join(', ')})`);\n console.log(` Total bars: ${totalBars}`);\n\n const missingSymbols = testSymbols.filter((s) => !symbolsInResponse.includes(s));\n const extraSymbols = symbolsInResponse.filter((s) => !testSymbols.includes(s));\n\n if (missingSymbols.length > 0) {\n console.error(` \u2717 FAILED: Missing symbols: ${missingSymbols.join(', ')}`);\n }\n if (extraSymbols.length > 0) {\n console.error(` \u2717 FAILED: Extra symbols not requested: ${extraSymbols.join(', ')}`);\n }\n if (symbolsInResponse.length !== testSymbols.length) {\n console.error(\n ` \u2717 FAILED: Expected ${testSymbols.length} symbols in response, got ${symbolsInResponse.length}`,\n );\n } else if (missingSymbols.length === 0 && extraSymbols.length === 0) {\n console.log(` \u2713 Paginated request correctly returned ${testSymbols.length} symbols`);\n }\n } catch (error) {\n console.error(' \u2717 Test 8 failed:', error);\n }\n\n // Test 9: Check for duplicate bars across pagination\n console.log('\\n[Test 9] Check for duplicate bars in paginated response');\n try {\n const testSymbol = 'AAPL';\n const endDate = new Date('2023-02-28T23:59:59.999Z');\n const startDate = new Date('2023-02-24T00:00:00.000Z');\n\n const response = await marketDataAPI.getHistoricalBars({\n symbols: [testSymbol],\n timeframe: '1Min',\n start: startDate.toISOString(),\n end: endDate.toISOString(),\n });\n\n const bars = response.bars[testSymbol] || [];\n const timestamps = bars.map((bar) => bar.t);\n const uniqueTimestamps = new Set(timestamps);\n\n console.log(` Total bars: ${bars.length}`);\n console.log(` Unique timestamps: ${uniqueTimestamps.size}`);\n\n if (bars.length !== uniqueTimestamps.size) {\n const duplicateCount = bars.length - uniqueTimestamps.size;\n console.error(` \u2717 FAILED: Found ${duplicateCount} duplicate bars`);\n\n // Show some duplicate examples\n const timestampCounts = new Map<string, number>();\n timestamps.forEach((ts) => {\n timestampCounts.set(ts, (timestampCounts.get(ts) || 0) + 1);\n });\n const duplicates = Array.from(timestampCounts.entries())\n .filter(([_, count]) => count > 1)\n .slice(0, 5);\n if (duplicates.length > 0) {\n console.error(` Examples of duplicates:`);\n duplicates.forEach(([ts, count]) => {\n console.error(` ${ts}: ${count} occurrences`);\n });\n }\n } else {\n console.log(` \u2713 No duplicate bars found`);\n }\n } catch (error) {\n console.error(' \u2717 Test 9 failed:', error);\n }\n\n // Test 10: Verify logging accuracy - track what logs say vs actual data\n console.log('\\n[Test 10] Verify logging accuracy');\n try {\n const testSymbols = ['AAPL', 'MSFT', 'GOOGL'];\n\n // Capture logs\n const originalLog = console.log;\n const logs: string[] = [];\n console.log = (...args: any[]) => {\n logs.push(args.join(' '));\n originalLog(...args);\n };\n\n const response = await marketDataAPI.getHistoricalBars({\n symbols: testSymbols,\n timeframe: '5Min',\n start: new Date('2023-02-27T09:30:00.000Z').toISOString(),\n end: new Date('2023-02-27T16:00:00.000Z').toISOString(),\n });\n\n console.log = originalLog;\n\n const symbolsInResponse = Object.keys(response.bars);\n\n console.log(` Requested symbols: ${testSymbols.length}`);\n console.log(` Actual symbols in response: ${symbolsInResponse.length}`);\n\n // Check if any logs mention incorrect symbol counts\n const logLines = logs.filter(\n (log) => log.includes('symbols') && (log.includes('Starting') || log.includes('complete')),\n );\n logLines.forEach((line) => {\n console.log(` Log: ${line}`);\n });\n\n if (symbolsInResponse.length === testSymbols.length) {\n console.log(` \u2713 Response contains correct number of symbols`);\n } else {\n console.error(\n ` \u2717 FAILED: Expected ${testSymbols.length} symbols, got ${symbolsInResponse.length} (${symbolsInResponse.join(', ')})`,\n );\n }\n } catch (error) {\n console.error(' \u2717 Test 10 failed:', error);\n }\n\n console.log('\\n\u2713 All Market Data API tests completed!');\n } catch (error) {\n console.error('\u2717 Market Data API test setup failed:', error);\n if (error instanceof Error) {\n console.error('Error message:', error.message);\n console.error('Stack trace:', error.stack);\n }\n }\n}\n\nfunction testImageModelDefaults() {\n const log = (message: string, options: LogOptions = { type: 'info' }) => {\n baseLog(message, { ...options, source: 'Test' });\n };\n\n log('Testing GPT image model defaults');\n\n const expectedDefault: DiscoImageModel = 'gpt-image-2';\n const defaultResolved = resolveImageModel();\n if (defaultResolved === expectedDefault && DEFAULT_IMAGE_MODEL === expectedDefault) {\n console.log(` \u2713 Default image model resolves to ${expectedDefault}`);\n } else {\n console.error(\n ` \u2717 Default image model mismatch (expected ${expectedDefault}, resolved ${defaultResolved}, constant ${DEFAULT_IMAGE_MODEL})`,\n );\n }\n\n if (isOpenAIImageModel(expectedDefault) && OPENAI_IMAGE_MODELS.includes(expectedDefault)) {\n console.log(` \u2713 ${expectedDefault} is exported in OPENAI_IMAGE_MODELS`);\n } else {\n console.error(` \u2717 ${expectedDefault} is missing from OPENAI_IMAGE_MODELS`);\n }\n\n const overrideModel: DiscoImageModel = 'gpt-image-1';\n const overrideResolved = resolveImageModel(overrideModel);\n if (overrideResolved === overrideModel) {\n console.log(` \u2713 Custom model ${overrideModel} is respected`);\n } else {\n console.error(` \u2717 Custom model ${overrideModel} resolved to ${overrideResolved}`);\n }\n\n const pricing = openAiImageCosts[expectedDefault];\n if (typeof pricing === 'number' && pricing > 0) {\n console.log(` \u2713 Pricing configured for ${expectedDefault}: $${pricing.toFixed(4)} per image`);\n } else {\n console.error(` \u2717 Missing pricing config for ${expectedDefault}`);\n }\n\n const highSquarePrice = openAiImageCostByQualityAndSize[expectedDefault].high['1024x1024'];\n const calculatedPrice = calculateImageCost(expectedDefault, 2, 'high', '1024x1024');\n if (calculatedPrice === highSquarePrice * 2) {\n console.log(` \u2713 Cost calculation uses quality and size pricing for ${expectedDefault}`);\n } else {\n console.error(` \u2717 Cost calculation mismatch (expected ${highSquarePrice * 2}, received ${calculatedPrice})`);\n }\n}\n\nfunction testGetTradingDaysBack() {\n const testCases = [\n {\n label: '1 day back from Friday after close',\n referenceDate: '2025-07-11T18:00:00-04:00',\n days: 1,\n expected: {\n date: '2025-07-11',\n marketOpenISO: '2025-07-11T13:30:00.000Z',\n },\n },\n {\n label: '1 day back from Friday during market',\n referenceDate: '2025-07-11T10:00:00-04:00',\n days: 1,\n expected: {\n date: '2025-07-10',\n marketOpenISO: '2025-07-10T13:30:00.000Z',\n },\n },\n {\n label: '2 days back from Friday after close',\n referenceDate: '2025-07-11T18:00:00-04:00',\n days: 2,\n expected: {\n date: '2025-07-10',\n marketOpenISO: '2025-07-10T13:30:00.000Z',\n },\n },\n {\n label: '5 days back from Friday after close',\n referenceDate: '2025-07-11T18:00:00-04:00',\n days: 5,\n expected: {\n date: '2025-07-07',\n marketOpenISO: '2025-07-07T13:30:00.000Z',\n },\n },\n {\n label: '6 days back from Friday after close (skips weekend and July 4)',\n referenceDate: '2025-07-11T18:00:00-04:00',\n days: 6,\n expected: {\n date: '2025-07-03',\n marketOpenISO: '2025-07-03T13:30:00.000Z',\n },\n },\n {\n label: '1 day back from Monday after close (should be Monday)',\n referenceDate: '2025-07-14T18:00:00-04:00',\n days: 1,\n expected: {\n date: '2025-07-14',\n marketOpenISO: '2025-07-14T13:30:00.000Z',\n },\n },\n {\n label: '1 day back from Saturday (should be Friday)',\n referenceDate: '2025-07-12T12:00:00-04:00',\n days: 1,\n expected: {\n date: '2025-07-11',\n marketOpenISO: '2025-07-11T13:30:00.000Z',\n },\n },\n {\n label: '3 days back from Monday (skips weekend)',\n referenceDate: '2025-07-14T18:00:00-04:00',\n days: 3,\n expected: {\n date: '2025-07-10',\n marketOpenISO: '2025-07-10T13:30:00.000Z',\n },\n },\n {\n label: '1 day back from day after holiday (July 7, after July 4)',\n referenceDate: '2025-07-07T18:00:00-04:00',\n days: 1,\n expected: {\n date: '2025-07-07',\n marketOpenISO: '2025-07-07T13:30:00.000Z',\n },\n },\n {\n label: '2 days back from day after holiday (skips July 4)',\n referenceDate: '2025-07-07T18:00:00-04:00',\n days: 2,\n expected: {\n date: '2025-07-03',\n marketOpenISO: '2025-07-03T13:30:00.000Z',\n },\n },\n {\n label: 'Early close day (July 3) - 1 day back from July 7',\n referenceDate: '2025-07-07T18:00:00-04:00',\n days: 2,\n expected: {\n date: '2025-07-03',\n marketOpenISO: '2025-07-03T13:30:00.000Z', // Still opens at normal time\n },\n },\n {\n label: '1 day back from Friday after close (exclude most recent full day)',\n referenceDate: '2025-07-11T18:00:00-04:00',\n days: 1,\n includeMostRecentFullDay: false,\n expected: {\n date: '2025-07-10',\n marketOpenISO: '2025-07-10T13:30:00.000Z',\n },\n },\n {\n label: '3 days back from Monday after close (exclude most recent full day)',\n referenceDate: '2025-07-14T18:00:00-04:00',\n days: 3,\n includeMostRecentFullDay: false,\n expected: {\n date: '2025-07-09',\n marketOpenISO: '2025-07-09T13:30:00.000Z',\n },\n },\n ];\n\n console.log('\\n=== Testing getTradingDaysBack ===\\n');\n\n for (const { label, referenceDate, days, includeMostRecentFullDay, expected } of testCases) {\n try {\n const refDate = new Date(referenceDate);\n const result = disco.time.getTradingDaysBack({ referenceDate: refDate, days, includeMostRecentFullDay });\n\n const dateMatches = result.date === expected.date;\n const isoMatches = result.marketOpenISO === expected.marketOpenISO;\n const unixValid = typeof result.unixTimestamp === 'number' && result.unixTimestamp > 0;\n\n // Verify unix timestamp matches ISO\n const dateFromUnix = new Date(result.unixTimestamp * 1000).toISOString();\n const unixMatches = dateFromUnix === result.marketOpenISO;\n\n const allPass = dateMatches && isoMatches && unixValid && unixMatches;\n\n console.log(`${allPass ? '\u2705' : '\u274C'} ${label}`);\n if (!allPass) {\n console.log(` Expected: ${JSON.stringify(expected)}`);\n console.log(` Got: ${JSON.stringify(result)}`);\n if (!dateMatches) console.log(` \u274C Date mismatch`);\n if (!isoMatches) console.log(` \u274C ISO mismatch`);\n if (!unixValid) console.log(` \u274C Unix timestamp invalid`);\n if (!unixMatches) console.log(` \u274C Unix timestamp doesn't match ISO`);\n }\n } catch (error) {\n console.log(`\u274C ${label}`);\n console.log(` Error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n const totalTests = testCases.length;\n const passedTests = testCases.filter((tc) => {\n try {\n const refDate = new Date(tc.referenceDate);\n const result = disco.time.getTradingDaysBack({\n referenceDate: refDate,\n days: tc.days,\n includeMostRecentFullDay: tc.includeMostRecentFullDay,\n });\n return result.date === tc.expected.date && result.marketOpenISO === tc.expected.marketOpenISO;\n } catch {\n return false;\n }\n }).length;\n\n console.log(`\\n=== Summary: ${passedTests}/${totalTests} tests passed ===\\n`);\n}\n\nasync function danaIsBung() {\n console.log('This is just to keep Dana humble.');\n}\n\nasync function testMOOAndMOCOrders() {\n console.log('\\n--- Testing Market on Open and Market on Close Orders ---');\n console.log('NOTE: MOO orders must be submitted after 7:00pm ET and before 9:28am ET');\n console.log('NOTE: MOC orders must be submitted after 7:00pm ET and before 3:50pm ET');\n console.log('Orders submitted outside these windows will be rejected.\\n');\n\n const log = (message: string, options: LogOptions = { type: 'info' }) => {\n baseLog(message, { ...options, source: 'Test' });\n };\n\n if (\n !process.env.ALPACA_TRADING_API_KEY ||\n !process.env.ALPACA_TRADING_SECRET_KEY ||\n !process.env.ALPACA_TRADING_ACCOUNT_TYPE\n ) {\n log('Missing required ALPACA_TRADING_* environment variables', { type: 'error' });\n return;\n }\n\n const credentials: AlpacaCredentials = {\n accountName: 'Test Account',\n apiKey: process.env.ALPACA_TRADING_API_KEY,\n apiSecret: process.env.ALPACA_TRADING_SECRET_KEY,\n type: process.env.ALPACA_TRADING_ACCOUNT_TYPE as AlpacaAccountType,\n orderType: 'limit',\n engine: 'quant',\n };\n\n const tradingAPI = AlpacaTradingAPI.getInstance(credentials);\n\n try {\n // Test creating a Market on Open order\n log('Creating Market on Open (MOO) order for SPY...');\n const mooOrder = await tradingAPI.createMOOOrder('SPY', 1, 'buy', 'buy_to_open', 'test-moo-order');\n log(`MOO order created successfully: ${mooOrder.id}`);\n log(` Symbol: ${mooOrder.symbol}`);\n log(` Qty: ${mooOrder.qty}`);\n log(` Side: ${mooOrder.side}`);\n log(` Type: ${mooOrder.type}`);\n log(` Time in Force: ${mooOrder.time_in_force}`);\n log(` Status: ${mooOrder.status}`);\n\n // Wait a moment before canceling\n await new Promise((resolve) => setTimeout(resolve, 1000));\n\n // Cancel the MOO order\n log(`Canceling MOO order ${mooOrder.id}...`);\n await tradingAPI.cancelOrder(mooOrder.id);\n log(`MOO order canceled successfully`);\n\n // Wait a moment before next order\n await new Promise((resolve) => setTimeout(resolve, 1000));\n\n // Test creating a Market on Close order\n log('Creating Market on Close (MOC) order for SPY...');\n const mocOrder = await tradingAPI.createMOCOrder('SPY', 1, 'sell', 'sell_to_open', 'test-moc-order');\n log(`MOC order created successfully: ${mocOrder.id}`);\n log(` Symbol: ${mocOrder.symbol}`);\n log(` Qty: ${mocOrder.qty}`);\n log(` Side: ${mocOrder.side}`);\n log(` Type: ${mocOrder.type}`);\n log(` Time in Force: ${mocOrder.time_in_force}`);\n log(` Status: ${mocOrder.status}`);\n\n // Wait a moment before canceling\n await new Promise((resolve) => setTimeout(resolve, 1000));\n\n // Cancel the MOC order\n log(`Canceling MOC order ${mocOrder.id}...`);\n await tradingAPI.cancelOrder(mocOrder.id);\n log(`MOC order canceled successfully`);\n\n log('\\nMOO/MOC order test completed successfully');\n } catch (error) {\n log(`Error during MOO/MOC order test: ${error instanceof Error ? error.message : 'Unknown error'}`, {\n type: 'error',\n });\n throw error;\n }\n}\n\n// testGetTradingDate();\n// testGetTradingStartAndEndDates();\n// testGetLastFullTradingDate();\n// testGetMarketOpenClose();\n// testGetNYTimeZone();\n// testGetNextMarketDay();\n// testCountTradingDays();\n// testGetPreviousMarketDay();\n// testOpenRouter();\n// testGetMarketStatus();\n// testCryptoMarketData();\n/**\n * Test market data subscription for long-running monitoring\n * This test subscribes to minute bars and logs incoming data to verify continuous stream\n * @param symbol Symbol to test (use 'FAKEPACA' for test mode)\n */\nfunction testMarketDataSubscription(symbol: string): void {\n log(`Starting market data subscription test for ${symbol}`);\n\n const marketDataAPI = AlpacaMarketDataAPI.getInstance();\n\n // If symbol is FAKEPACA, use test mode\n if (symbol === 'FAKEPACA') {\n log('Using test mode for FAKEPACA');\n marketDataAPI.setMode('test');\n } else {\n log('Using production mode');\n marketDataAPI.setMode('production');\n }\n\n let barCount = 0;\n let lastBarTime: Date | null = null;\n const startTime = new Date();\n\n // Subscribe to minute bars\n marketDataAPI.on('stock-b', (data) => {\n barCount++;\n const now = new Date();\n const barTime = new Date(data.t);\n lastBarTime = barTime;\n\n const timeSinceStart = Math.floor((now.getTime() - startTime.getTime()) / 1000);\n const minutesSinceStart = Math.floor(timeSinceStart / 60);\n const secondsSinceStart = timeSinceStart % 60;\n\n log(\n `[${minutesSinceStart}m ${secondsSinceStart}s] Bar #${barCount} for ${data.S}: ` +\n `O=$${data.o.toFixed(2)}, H=$${data.h.toFixed(2)}, L=$${data.l.toFixed(2)}, C=$${data.c.toFixed(2)}, ` +\n `V=${data.v.toLocaleString()}, Time=${barTime.toLocaleString('en-US', { timeZone: 'America/New_York' })}`,\n );\n });\n\n // Connect and subscribe\n log('Connecting to stock stream...');\n marketDataAPI.connectStockStream();\n\n // Give it a moment to connect, then subscribe\n setTimeout(() => {\n log(`Subscribing to minute bars for ${symbol}...`);\n marketDataAPI.subscribe('stock', { bars: [symbol] });\n }, 2000);\n\n // Log status every 5 minutes\n setInterval(\n () => {\n const now = new Date();\n const timeSinceStart = Math.floor((now.getTime() - startTime.getTime()) / 1000);\n const minutesSinceStart = Math.floor(timeSinceStart / 60);\n const hoursSinceStart = Math.floor(minutesSinceStart / 60);\n const remainingMinutes = minutesSinceStart % 60;\n\n const lastBarInfo = lastBarTime\n ? `Last bar: ${lastBarTime.toLocaleString('en-US', { timeZone: 'America/New_York' })}`\n : 'No bars received yet';\n\n log(\n `Status check - Runtime: ${hoursSinceStart}h ${remainingMinutes}m, ` +\n `Total bars: ${barCount}, ${lastBarInfo}`,\n { type: 'info' },\n );\n },\n 5 * 60 * 1000,\n ); // Every 5 minutes\n\n log('Market data subscription test running... (press Ctrl+C to stop)');\n}\n\n/**\n * Test the createStopOrder and createOCOOrder functions\n */\nasync function testStopAndOCOOrders() {\n const log = (message: string, options: LogOptions = { type: 'info' }) => {\n baseLog(message, { ...options, source: 'Test' });\n };\n\n log('=== Testing Stop and OCO Orders ===');\n\n const credentials: AlpacaCredentials = {\n accountName: 'Paper',\n apiKey: process.env.ALPACA_TRADING_API_KEY || '',\n apiSecret: process.env.ALPACA_TRADING_SECRET_KEY || '',\n type: 'PAPER' as AlpacaAccountType,\n orderType: 'market',\n engine: 'brain',\n };\n\n if (!credentials.apiKey || !credentials.apiSecret) {\n log('Missing Alpaca credentials in environment variables', { type: 'error' });\n return;\n }\n\n const tradingAPI = AlpacaTradingAPI.getInstance(credentials);\n\n try {\n const timestamp = Date.now();\n\n // Test 1: Create a simple stop order\n log('Test 1: Creating stop order for AAPL');\n const stopOrder = await tradingAPI.createStopOrder(\n 'AAPL',\n 1,\n 'sell',\n 145.0,\n 'sell_to_open', // Use sell_to_open since we don't have a position\n );\n log(`\u2713 Stop order created: ${stopOrder.id}, type: ${stopOrder.type}, stop_price: ${stopOrder.stop_price}`);\n\n // Test 2: Create a stop-limit order\n log('Test 2: Creating stop-limit order for TSLA');\n const stopLimitOrder = await tradingAPI.createStopOrder(\n 'TSLA',\n 1,\n 'sell',\n 200.0,\n 'sell_to_open', // Use sell_to_open since we don't have a position\n 199.5,\n `test-stop-limit-${timestamp}`,\n );\n log(\n `\u2713 Stop-limit order created: ${stopLimitOrder.id}, type: ${stopLimitOrder.type}, stop_price: ${stopLimitOrder.stop_price}, limit_price: ${stopLimitOrder.limit_price}`,\n );\n\n // Test 3: Create an OCO order (must be an exit order, so we first need to buy shares)\n log('Test 3: Creating position in MSFT and then OCO order to exit');\n\n // First check if there's an existing position and close it\n const existingPositions = await tradingAPI.getPositions();\n const msftPosition = existingPositions.find((p) => p.symbol === 'MSFT');\n if (msftPosition) {\n log(' Closing existing MSFT position...');\n await tradingAPI.closeAllPositions({ cancel_orders: true, useLimitOrders: false });\n await new Promise((resolve) => setTimeout(resolve, 2000));\n }\n\n // Buy shares to create a position\n log(' 3a: Buying 1 share of MSFT to create position...');\n const msftEntry = await tradingAPI.createMarketOrder('MSFT', 1, 'buy', 'buy_to_open');\n log(` \u2713 Entry order created: ${msftEntry.id}`);\n\n // Wait for order to fill (paper trading should be instant but let's be safe)\n await new Promise((resolve) => setTimeout(resolve, 3000));\n\n // Verify position exists\n const positions = await tradingAPI.getPositions();\n const newMsftPosition = positions.find((p) => p.symbol === 'MSFT');\n if (!newMsftPosition) {\n log(' Warning: MSFT position not found, skipping OCO test', { type: 'error' });\n } else {\n log(` \u2713 MSFT position confirmed: ${newMsftPosition.qty} shares`);\n\n // Now create OCO to exit the position\n log(' 3b: Creating OCO order to exit MSFT position...');\n const ocoOrder = await tradingAPI.createOCOOrder(\n 'MSFT',\n 1,\n 'sell', // sell to exit the long position\n 'sell_to_close', // must be sell_to_close since we're exiting\n 420.0, // limit price for exit order\n 425.0, // take profit (sell at or above this)\n 415.0, // stop loss (sell if price drops to this)\n );\n log(`\u2713 OCO order created: ${ocoOrder.id}, order_class: ${ocoOrder.order_class}`);\n if (ocoOrder.legs && ocoOrder.legs.length > 0) {\n log(` - Legs: ${ocoOrder.legs.length} orders`);\n ocoOrder.legs.forEach((leg, index) => {\n log(` Leg ${index + 1}: type=${leg.type}, limit_price=${leg.limit_price}, stop_price=${leg.stop_price}`);\n });\n }\n }\n\n // Test 4: Create another OCO order with stop-limit\n log('Test 4: Creating position in QQQ and OCO order with stop-limit');\n\n // Check existing QQQ position\n const qqqExistingPosition = existingPositions.find((p) => p.symbol === 'QQQ');\n if (qqqExistingPosition) {\n log(' Found existing QQQ position, skipping position creation');\n } else {\n log(' 4a: Buying 1 share of QQQ to create position...');\n const qqqEntry = await tradingAPI.createMarketOrder('QQQ', 1, 'buy', 'buy_to_open');\n log(` \u2713 Entry order created: ${qqqEntry.id}`);\n\n // Wait for order to fill\n await new Promise((resolve) => setTimeout(resolve, 3000));\n }\n\n // Verify position exists\n const updatedPositions = await tradingAPI.getPositions();\n const qqqPosition = updatedPositions.find((p) => p.symbol === 'QQQ');\n if (!qqqPosition) {\n log(' Warning: QQQ position not found, skipping OCO test', { type: 'error' });\n } else {\n log(` \u2713 QQQ position confirmed: ${qqqPosition.qty} shares`);\n\n log(' 4b: Creating OCO order with stop-limit for QQQ...');\n const ocoLimitOrder = await tradingAPI.createOCOOrder(\n 'QQQ',\n 1,\n 'sell', // sell to exit the long position\n 'sell_to_close', // must be sell_to_close since we're exiting\n 480.0, // limit price for exit order\n 490.0, // take profit (sell at or above this)\n 470.0, // stop loss\n 470.5, // stop loss limit\n `test-oco-limit-${timestamp}`,\n );\n log(`\u2713 OCO limit order created: ${ocoLimitOrder.id}, order_class: ${ocoLimitOrder.order_class}`);\n if (ocoLimitOrder.legs && ocoLimitOrder.legs.length > 0) {\n log(` - Legs: ${ocoLimitOrder.legs.length} orders`);\n ocoLimitOrder.legs.forEach((leg, index) => {\n log(` Leg ${index + 1}: type=${leg.type}, limit_price=${leg.limit_price}, stop_price=${leg.stop_price}`);\n });\n }\n }\n\n // Clean up: Cancel all test orders\n log('Cleaning up: Canceling all test orders...');\n await tradingAPI.cancelAllOrders();\n log('\u2713 All test orders canceled');\n\n log('=== All Stop and OCO Order Tests Passed ===');\n } catch (error) {\n log(`Error during tests: ${error}`, { type: 'error' });\n throw error;\n }\n}\n\nasync function testLLMStructuredOutputWithZod() {\n if (!process.env.OPENAI_API_KEY) {\n console.log('Skipping OpenAI structured output Zod test: OPENAI_API_KEY not set');\n return;\n }\n\n const structuredSchema = z.object({\n country: z.string(),\n capital: z.string(),\n region: z.string(),\n countryCode: z.string(),\n });\n\n type StructuredCapitalResponse = z.infer<typeof structuredSchema>;\n\n const prompt = 'Return details for France using the exact schema.';\n const result = await disco.llm.call<StructuredCapitalResponse>(prompt, {\n model: 'gpt-5.5',\n schema: structuredSchema,\n schemaName: 'capital_response',\n schemaDescription: 'Country and capital metadata',\n schemaStrict: true,\n });\n\n const response = result.response;\n\n if (!response.country || !response.capital || !response.region || !response.countryCode) {\n throw new Error(`Structured response is missing required fields: ${JSON.stringify(response)}`);\n }\n\n if (response.country.toLowerCase() !== 'france') {\n throw new Error(`Expected country to be France, received: ${response.country}`);\n }\n\n if (response.capital.toLowerCase() !== 'paris') {\n throw new Error(`Expected capital to be Paris, received: ${response.capital}`);\n }\n\n if (response.countryCode.length !== 2) {\n throw new Error(`Expected 2-letter countryCode, received: ${response.countryCode}`);\n }\n\n console.log('\\n[OpenAI] Structured output with Zod test');\n console.log(' Model:', 'gpt-5.5');\n console.log(' Response:', response);\n console.log(' Usage:', result.usage);\n}\n\n// testGetPortfolioDailyHistory();\n// testWebSocketConnectAndDisconnect();\n// testGetAssetsShortableFilter();\n// testImageModelDefaults();\n// testGetTradingDaysBack();\n// testMOOAndMOCOrders();\n\n// testMarketDataAPI();\n\n// Test market data subscription with a real symbol or FAKEPACA\n// Uncomment one of the following to test:\n// testMarketDataSubscription('SPY');\n// testMarketDataSubscription('FAKEPACA');\n// testGetTradingDate();\ntestOpenAIModelRegistryAndPricing();\n// // await testLLMVisionInputs();\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;AAWO,SAAS,IAAI,SAAiB,UAAsB,EAAE,QAAQ,OAAO,MAAM,OAAO,GAAS;AAEhG,QAAM,OAAO,oBAAI,KAAK;AACtB,QAAM,YAAY,KAAK,eAAe,SAAS,EAAE,UAAU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