@adaptic/utils 0.0.983 → 0.0.985

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.mjs CHANGED
@@ -2652,8 +2652,7 @@ const DEFAULT_ADJUSTMENT = "all";
2652
2652
  // deployments with SIP entitlements set ALPACA_MARKET_DATA_FEED=sip in their
2653
2653
  // environment to restore full data access. Per-call overrides (the optional
2654
2654
  // `feed` argument on getOptions*/getLatestBars/etc.) still win.
2655
- const DEFAULT_FEED$1 = (process.env.ALPACA_MARKET_DATA_FEED ||
2656
- "iex");
2655
+ const DEFAULT_FEED$1 = (process.env.ALPACA_MARKET_DATA_FEED || "iex");
2657
2656
  const DEFAULT_CURRENCY$1 = "USD";
2658
2657
  /**
2659
2658
  * Singleton class for interacting with Alpaca Market Data API
@@ -8521,6 +8520,11 @@ const fetchPrices = async (params, options) => {
8521
8520
  try {
8522
8521
  let allResults = [];
8523
8522
  let nextUrl = `${baseUrl}?${urlParams.toString()}`;
8523
+ // DE-006: track upstream freshness across pagination. If any page
8524
+ // reports DELAYED, the whole batch is treated as DELAYED — this is the
8525
+ // safer default for downstream latency-sensitive logic (e.g., trade
8526
+ // execution should refuse stale prices, not silently mix them).
8527
+ let aggregatedStatus = "OK";
8524
8528
  while (nextUrl) {
8525
8529
  //getLogger().info(`Debug: Fetching ${nextUrl}`);
8526
8530
  await rateLimiters.massive.acquire();
@@ -8530,6 +8534,7 @@ const fetchPrices = async (params, options) => {
8530
8534
  throw new Error(`Massive.com API responded with status: ${data.status}`);
8531
8535
  }
8532
8536
  if (data.status === "DELAYED") {
8537
+ aggregatedStatus = "DELAYED";
8533
8538
  const now = Date.now();
8534
8539
  const lastWarn = delayedWarnTimestamps.get(params.ticker) ?? 0;
8535
8540
  if (now - lastWarn > DELAYED_WARN_COOLDOWN_MS) {
@@ -8543,6 +8548,14 @@ const fetchPrices = async (params, options) => {
8543
8548
  // Check if there's a next page and append API key
8544
8549
  nextUrl = data.next_url ? `${data.next_url}&apiKey=${apiKey}` : "";
8545
8550
  }
8551
+ // DE-006: stamp each bar with the upstream freshness so downstream
8552
+ // consumers (engine pricing pipeline, performance metrics, risk gates)
8553
+ // can branch on `bar._freshness?.status === "DELAYED"`.
8554
+ const freshness = {
8555
+ status: aggregatedStatus,
8556
+ receivedAt: new Date(),
8557
+ ...(aggregatedStatus === "DELAYED" ? { delayedSince: null } : {}),
8558
+ };
8546
8559
  return allResults.map((entry) => ({
8547
8560
  date: new Date(entry.t).toLocaleString("en-US", {
8548
8561
  year: "numeric",
@@ -8563,6 +8576,7 @@ const fetchPrices = async (params, options) => {
8563
8576
  vol: entry.v,
8564
8577
  vwap: entry.vw,
8565
8578
  trades: entry.n,
8579
+ _freshness: freshness,
8566
8580
  }));
8567
8581
  }
8568
8582
  catch (error) {
@@ -8603,6 +8617,43 @@ const fetchPrices = async (params, options) => {
8603
8617
  }
8604
8618
  });
8605
8619
  };
8620
+ /**
8621
+ * Variant of {@link fetchPrices} that returns a discriminated
8622
+ * {@link MassiveResult} wrapper, surfacing the upstream feed status (`OK` vs
8623
+ * `DELAYED`) at the result level. This is the preferred entry point for new
8624
+ * code that needs to gate latency-sensitive decisions on freshness.
8625
+ *
8626
+ * The underlying bars are still stamped with `_freshness` so consumers that
8627
+ * already destructure the array can branch per-bar; the wrapper simply
8628
+ * promotes that information to the top of the result for clarity.
8629
+ *
8630
+ * DE-006: closes the loop for callers that need to know when the Massive feed
8631
+ * is on a delayed plan (e.g. free tier, market-data outage downgrade).
8632
+ *
8633
+ * @param params - Same parameters accepted by {@link fetchPrices}.
8634
+ * @param options - Same options accepted by {@link fetchPrices}.
8635
+ * @returns A {@link MassiveResult} carrying the bar array plus freshness
8636
+ * metadata.
8637
+ */
8638
+ const fetchPricesWithFreshness = async (params, options) => {
8639
+ const data = await fetchPrices(params, options);
8640
+ // Bars are stamped uniformly inside `fetchPrices`; reading the first one is
8641
+ // sufficient. If the result is empty (no bars in the requested window) we
8642
+ // default to OK with the current wall clock — there is no upstream signal
8643
+ // to contradict it.
8644
+ const sampleFreshness = data[0]?._freshness;
8645
+ const status = sampleFreshness?.status ?? "OK";
8646
+ const receivedAt = sampleFreshness?.receivedAt ?? new Date();
8647
+ if (status === "DELAYED") {
8648
+ return {
8649
+ status: "DELAYED",
8650
+ data,
8651
+ receivedAt,
8652
+ delayedSince: sampleFreshness?.delayedSince ?? null,
8653
+ };
8654
+ }
8655
+ return { status: "OK", data, receivedAt };
8656
+ };
8606
8657
  /**
8607
8658
  * Analyzes the price data for a given stock.
8608
8659
  * @param {MassivePriceData[]} priceData - The price data to analyze.
@@ -9246,7 +9297,11 @@ function getEquityValues(equityData, portfolioHistory, marketTimeUtil, period) {
9246
9297
  initialEquity = Number(validData[0].value);
9247
9298
  }
9248
9299
  return {
9249
- latestEquity: Number(latestPoint.valueOf),
9300
+ // DE-005: previously `Number(latestPoint.valueOf)`, which read the
9301
+ // un-invoked function reference and silently returned NaN. `latestPoint`
9302
+ // is already a number (see line above; sourced from `point.value` which
9303
+ // is typed `number` in EquityPoint), so use it directly.
9304
+ latestEquity: latestPoint,
9250
9305
  initialEquity,
9251
9306
  latestTimestamp: validData[validData.length - 1].time,
9252
9307
  initialTimestamp: validData[0].time,
@@ -9345,25 +9400,42 @@ async function fetchTreasuryBillRate() {
9345
9400
  return percent / 100;
9346
9401
  }
9347
9402
  /**
9348
- * Returns the current annualized risk-free rate (decimal, e.g. 0.0452 for
9349
- * 4.52%), fetching from the US Treasury Fiscal Data API and caching for 24h.
9350
- *
9351
- * Behavior:
9352
- * - If a fresh cached value exists (<24h old), returns it without a network
9353
- * round-trip.
9354
- * - If the cache is stale or empty, fetches the latest 13-week T-Bill rate,
9355
- * updates the cache, and returns it.
9356
- * - If the fetch fails, returns the last-known-good cached value (even if
9357
- * expired) or {@link DEFAULT_RISK_FREE_RATE} as a last resort, logging a
9358
- * warning in both cases.
9359
- * - Concurrent calls during a cold cache are deduplicated so only one network
9360
- * request is in flight at a time.
9361
- *
9362
- * @returns Annualized risk-free rate as a decimal.
9363
- */
9364
- async function getRiskFreeRate() {
9365
- if (isFresh(cache)) {
9366
- return cache.rate;
9403
+ * Provenance-aware variant of {@link getRiskFreeRate} that returns the rate
9404
+ * AND tells the caller where it came from. Use this in any code path that
9405
+ * publishes performance metrics (Sharpe, alpha, Sortino) so downstream
9406
+ * reports can flag computations made against a fictional fallback rate.
9407
+ *
9408
+ * Behavior is identical to {@link getRiskFreeRate} for the cache and
9409
+ * deduplication semantics; only the return shape differs:
9410
+ *
9411
+ * - Fresh cache hit: `{ source: "cached", fetchedAt: <original fetch time> }`
9412
+ * - Cold or stale cache + successful fetch: `{ source: "live", fetchedAt: <now> }`
9413
+ * - Cold or stale cache + failed fetch but cached value present:
9414
+ * `{ source: "cached", fetchedAt: <original fetch time> }` the stale
9415
+ * value is reused so existing alpha calculations keep working through a
9416
+ * transient outage. The provenance still says `cached`, not `live`.
9417
+ * - Cold cache + failed fetch + no cached value:
9418
+ * `{ source: "default", fetchedAt: <now> }` — the 2% fallback is used. This
9419
+ * is the case downstream reports MUST flag, because Sharpe / alpha computed
9420
+ * against a 2% floor that was never observed in market data is a fiction.
9421
+ *
9422
+ * DE-029: closes the silent-failure loop where a first-fetch network failure
9423
+ * propagated `DEFAULT_RISK_FREE_RATE` indistinguishable from a live
9424
+ * observation.
9425
+ *
9426
+ * @returns The annualized risk-free rate plus its provenance.
9427
+ */
9428
+ async function getRiskFreeRateWithProvenance() {
9429
+ // Snapshot the cache reference before the freshness check so the type
9430
+ // narrows correctly without a non-null assertion (the check itself uses a
9431
+ // mutable module-level variable, which TypeScript will not narrow across).
9432
+ const snapshot = cache;
9433
+ if (snapshot !== null && isFresh(snapshot)) {
9434
+ return {
9435
+ rate: snapshot.rate,
9436
+ source: "cached",
9437
+ fetchedAt: new Date(snapshot.fetchedAt),
9438
+ };
9367
9439
  }
9368
9440
  if (inflight !== null) {
9369
9441
  return inflight;
@@ -9371,17 +9443,34 @@ async function getRiskFreeRate() {
9371
9443
  inflight = (async () => {
9372
9444
  try {
9373
9445
  const rate = await fetchTreasuryBillRate();
9374
- cache = { rate, fetchedAt: Date.now() };
9375
- return rate;
9446
+ const fetchedAtMs = Date.now();
9447
+ cache = { rate, fetchedAt: fetchedAtMs };
9448
+ return {
9449
+ rate,
9450
+ source: "live",
9451
+ fetchedAt: new Date(fetchedAtMs),
9452
+ };
9376
9453
  }
9377
9454
  catch (error) {
9378
9455
  const message = error instanceof Error ? error.message : String(error);
9379
9456
  if (cache !== null) {
9380
- getLogger().warn("Failed to refresh risk-free rate; using last-known-good cached value", { error: message, cachedRate: cache.rate, cacheAgeMs: Date.now() - cache.fetchedAt });
9381
- return cache.rate;
9457
+ getLogger().warn("Failed to refresh risk-free rate; using last-known-good cached value", {
9458
+ error: message,
9459
+ cachedRate: cache.rate,
9460
+ cacheAgeMs: Date.now() - cache.fetchedAt,
9461
+ });
9462
+ return {
9463
+ rate: cache.rate,
9464
+ source: "cached",
9465
+ fetchedAt: new Date(cache.fetchedAt),
9466
+ };
9382
9467
  }
9383
9468
  getLogger().warn("Failed to fetch risk-free rate and no cached value available; falling back to DEFAULT_RISK_FREE_RATE", { error: message, fallback: DEFAULT_RISK_FREE_RATE });
9384
- return DEFAULT_RISK_FREE_RATE;
9469
+ return {
9470
+ rate: DEFAULT_RISK_FREE_RATE,
9471
+ source: "default",
9472
+ fetchedAt: new Date(),
9473
+ };
9385
9474
  }
9386
9475
  finally {
9387
9476
  inflight = null;
@@ -9389,6 +9478,31 @@ async function getRiskFreeRate() {
9389
9478
  })();
9390
9479
  return inflight;
9391
9480
  }
9481
+ /**
9482
+ * Returns the current annualized risk-free rate (decimal, e.g. 0.0452 for
9483
+ * 4.52%), fetching from the US Treasury Fiscal Data API and caching for 24h.
9484
+ *
9485
+ * Behavior:
9486
+ * - If a fresh cached value exists (<24h old), returns it without a network
9487
+ * round-trip.
9488
+ * - If the cache is stale or empty, fetches the latest 13-week T-Bill rate,
9489
+ * updates the cache, and returns it.
9490
+ * - If the fetch fails, returns the last-known-good cached value (even if
9491
+ * expired) or {@link DEFAULT_RISK_FREE_RATE} as a last resort, logging a
9492
+ * warning in both cases.
9493
+ * - Concurrent calls during a cold cache are deduplicated so only one network
9494
+ * request is in flight at a time.
9495
+ *
9496
+ * For provenance-aware callers (performance reports, audit logging) prefer
9497
+ * {@link getRiskFreeRateWithProvenance}, which returns both the rate AND
9498
+ * whether it came from a live fetch, the cache, or the fallback default.
9499
+ *
9500
+ * @returns Annualized risk-free rate as a decimal.
9501
+ */
9502
+ async function getRiskFreeRate() {
9503
+ const result = await getRiskFreeRateWithProvenance();
9504
+ return result.rate;
9505
+ }
9392
9506
  /**
9393
9507
  * Synchronous accessor that returns the most recent cached risk-free rate
9394
9508
  * without performing I/O. If the cache is stale, a background refresh is
@@ -9403,22 +9517,53 @@ async function getRiskFreeRate() {
9403
9517
  * {@link DEFAULT_RISK_FREE_RATE} if no value has been cached yet.
9404
9518
  */
9405
9519
  function getCachedRiskFreeRateSync() {
9520
+ return getCachedRiskFreeRateSyncWithProvenance().rate;
9521
+ }
9522
+ /**
9523
+ * Provenance-aware sibling of {@link getCachedRiskFreeRateSync}. Returns the
9524
+ * cached rate plus a flag indicating whether a real value has been cached
9525
+ * (`"cached"`) or whether the caller is being given the {@link DEFAULT_RISK_FREE_RATE}
9526
+ * fallback (`"default"`).
9527
+ *
9528
+ * Use this in synchronous hot paths that nonetheless need to flag computations
9529
+ * made against the fallback (e.g., real-time alpha streaming where async
9530
+ * round-trips are not viable but downstream reports must still distinguish
9531
+ * live from fictional rates).
9532
+ *
9533
+ * As with the original sync accessor, a stale cache triggers a fire-and-forget
9534
+ * background refresh so the next synchronous call sees fresh data; the call
9535
+ * itself remains synchronous and returns the last-known-good value.
9536
+ *
9537
+ * DE-029: closes the silent-failure loop where the synchronous fallback was
9538
+ * indistinguishable from a real cache hit.
9539
+ *
9540
+ * @returns A {@link RiskFreeRateResult} carrying the rate and its provenance.
9541
+ */
9542
+ function getCachedRiskFreeRateSyncWithProvenance() {
9406
9543
  if (cache === null) {
9407
9544
  // Kick off a background fetch so the next sync caller has a real number.
9408
- void getRiskFreeRate().catch(() => {
9409
- // Errors are already logged inside getRiskFreeRate; swallow here to
9410
- // keep this truly fire-and-forget.
9545
+ void getRiskFreeRateWithProvenance().catch(() => {
9546
+ // Errors are already logged inside getRiskFreeRateWithProvenance;
9547
+ // swallow here to keep this truly fire-and-forget.
9411
9548
  });
9412
- return DEFAULT_RISK_FREE_RATE;
9549
+ return {
9550
+ rate: DEFAULT_RISK_FREE_RATE,
9551
+ source: "default",
9552
+ fetchedAt: new Date(),
9553
+ };
9413
9554
  }
9414
9555
  if (!isFresh(cache)) {
9415
9556
  // Stale: trigger background refresh but still return the last-known-good
9416
9557
  // value so the call remains synchronous.
9417
- void getRiskFreeRate().catch(() => {
9418
- // Errors are already logged inside getRiskFreeRate.
9558
+ void getRiskFreeRateWithProvenance().catch(() => {
9559
+ // Errors are already logged inside getRiskFreeRateWithProvenance.
9419
9560
  });
9420
9561
  }
9421
- return cache.rate;
9562
+ return {
9563
+ rate: cache.rate,
9564
+ source: "cached",
9565
+ fetchedAt: new Date(cache.fetchedAt),
9566
+ };
9422
9567
  }
9423
9568
 
9424
9569
  // metric-calcs.ts
@@ -68576,6 +68721,7 @@ const adaptic = {
68576
68721
  fetchLastQuote: fetchLastQuote,
68577
68722
  fetchTrades: fetchTrades,
68578
68723
  fetchPrices: fetchPrices,
68724
+ fetchPricesWithFreshness: fetchPricesWithFreshness,
68579
68725
  analyseMassivePriceData: analyseMassivePriceData,
68580
68726
  formatPriceData: formatPriceData,
68581
68727
  fetchDailyOpenClose: fetchDailyOpenClose,
@@ -68642,5 +68788,5 @@ const adaptic = {
68642
68788
  };
68643
68789
  const adptc = adaptic;
68644
68790
 
68645
- export { API_RETRY_CONFIGS, AVNewsArticleSchema, AVNewsResponseSchema, AdapticUtilsError, AlpacaAccountDetailsSchema, AlpacaApiError, AlpacaBarSchema, AlpacaClient, AlpacaCryptoBarsResponseSchema, AlpacaHistoricalBarsResponseSchema, AlpacaLatestBarsResponseSchema, AlpacaLatestQuotesResponseSchema, AlpacaLatestTradesResponseSchema, AlpacaMarketDataAPI, AlpacaNewsArticleSchema, AlpacaNewsResponseSchema, AlpacaOrderSchema, AlpacaOrdersArraySchema, AlpacaPortfolioHistoryResponseSchema, AlpacaPositionSchema, AlpacaPositionsArraySchema, AlpacaQuoteSchema, AlpacaTradeSchema, AlpacaTradingAPI, AlphaVantageError, AlphaVantageQuoteResponseSchema, AssetAllocationEngine, AuthenticationError, AutonomyMode, BTC_PAIRS, BarError, CryptoDataError, CryptoOrderError, DEFAULT_CACHE_OPTIONS, DEFAULT_RISK_FREE_RATE, DEFAULT_TIMEOUTS, DEFAULT_TRADING_POLICY, DataFormatError, DecisionMemoryOutcome, DecisionOutcome, DecisionRecordStatus, HttpClientError, HttpServerError, KEEP_ALIVE_DEFAULTS, LlmProvider, MARKET_DATA_API, MassiveAggregatesResponseSchema, MassiveApiError, MassiveDailyOpenCloseSchema, MassiveErrorResponseSchema, MassiveGroupedDailyResponseSchema, MassiveLastTradeResponseSchema, MassiveTickerDetailsResponseSchema, MassiveTickerInfoSchema, MassiveTradeSchema as MassiveTradeZodSchema, MassiveTradesResponseSchema, NetworkError, NewsError, OptionStrategyError, OptionsDataError, OverlaySeverity, OverlayStatus, OverlayType, QuoteError, RISK_FREE_RATE_TTL_MS, RateLimitError, RawMassivePriceDataSchema, StampedeProtectedCache, TRADING_API, TimeoutError, TokenBucketRateLimiter, TradeError, TrailingStopValidationError, USDC_PAIRS, USDT_PAIRS, USD_PAIRS, ValidationError, ValidationResponseError, WEBSOCKET_STREAMS, WebSocketError, account, adaptic, adptc, alpaca, analyzeBars, approximateImpliedVolatility, bracketOrders, buildOCCSymbol, buildOptionSymbol, buyCryptoNotional, buyToClose, buyToOpen, buyWithStopLoss, buyWithTrailingStop, calculateMoneyness, calculateOrderValue, calculatePeriodPerformance, calculatePutCallRatio, calculateTotalFilledValue, cancelAllCryptoOrders, cancelOCOOrder, cancelOTOOrder, cancelTrailingStop, cancelTrailingStopsForSymbol, checkTradingEligibility, clearClientCache, clock, closeAllOptionPositions, closeOptionPosition, createAlpacaClient, createAlpacaMarketDataAPI, createAlpacaTradingAPI, createBracketOrder, createButterflySpread, createClientFromEnv, createCoveredCall, createCryptoLimitOrder, createCryptoMarketOrder, createCryptoOrder, createCryptoStopLimitOrder, createCryptoStopOrder, createExecutorFromTradingAPI, createIronCondor$1 as createIronCondor, createIronCondor as createIronCondorAdvanced, createMultiLegOptionOrder, createOCOOrder, createOTOOrder, createOptionOrder, createPortfolioTrailingStops, createProtectiveBracket, createStampedeProtectedCache, createStraddle$1 as createStraddle, createStraddle as createStraddleAdvanced, createStrangle$1 as createStrangle, createStrangle as createStrangleAdvanced, createStreamManager, createTimeoutSignal, createTrailingStop, createVerticalSpread$1 as createVerticalSpread, createVerticalSpread as createVerticalSpreadAdvanced, entryWithPercentStopLoss, exerciseOption, extractGreeks, filterByExpiration, filterByStrike, filterByType, filterOrdersByDateRange, findATMOptions, findATMStrikes, findNearestExpiration, findOptionsByDelta, formatOrderForLog, formatOrderSummary, generateOptimalAllocation, getAccountConfiguration, getAccountDetails, getAccountSummary, getAgentPoolStatus, getAllOrders, getAlpacaCalendar, getAlpacaClock, getAverageDailyVolume, getBars, getBuyingPower, getCachedRiskFreeRateSync, getCrypto24HourChange, getCryptoBars, getCryptoDailyPrices, getCryptoPairsByQuote, getCryptoPrice, getCryptoSnapshots, getCryptoSpread, getCryptoStreamUrl, getCryptoTrades, getCurrentPrice, getCurrentPrices, getDailyPrices, getDailyReturns, getDaysToExpiration, getDefaultRiskProfile, getEquityCurve, getExpirationDates, getFilledOrders, getGroupedOptionChain, getHistoricalOptionsBars, getHistoricalTrades, getIntradayPrices, getLatestBars, getLatestCryptoQuotes, getLatestCryptoTrades, getLatestNews, getLatestOptionsQuotes, getLatestOptionsTrades, getLatestQuote, getLatestQuotes, getLatestTrade, getLatestTrades, getLogger, getMarginInfo, getNews, getNewsForSymbols, getOCOOrderStatus, getOTOOrderStatus, getOpenCryptoOrders, getOpenOrders$1 as getOpenOrdersQuery, getOpenTrailingStops, getOptionChain, getOptionContract, getOptionContracts, getOptionSpread, getOptionsChain, getOptionsSnapshots, getOptionsStreamUrl, getOptionsTradingLevel, getOrderHistory, getOrdersBySymbol, getPDTStatus, getPopularCryptoPairs, getPortfolioHistory, getPreviousClose, getPriceRange, getRiskFreeRate, getSpread, getSpreads, getStockStreamUrl, getStrikePrices, getSupportedCryptoPairs, getSymbolSentiment, getTimeout, getTradeVolume, getTradingApiUrl, getTradingWebSocketUrl, getTrailingStopHWM, groupOrdersByStatus, groupOrdersBySymbol, hasActiveTrailingStop, hasGoodLiquidity as hasOptionLiquidity, hasGoodLiquidity$1 as hasStockLiquidity, hasSufficientVolume, httpAgent, httpsAgent, isContractTradable, isCryptoPair, isExpiringWithin, isMarginAccount, isOptionOrderCancelable, isOptionOrderTerminal, isOrderFillable, isOrderFilled, isOrderOpen, isOrderTerminal$1 as isOrderTerminalStatus, isSupportedCryptoPair, isTransientNetworkError, index$1 as legacyApi, limitBuyWithTakeProfit, ocoOrders, orderUtils, otoOrders, paginate, paginateAll, parseOCCSymbol, protectLongPosition, protectShortPosition, rateLimiters, resetLogger, resetRiskFreeRateCache, rollOptionPosition, roundPriceForAlpaca$3 as roundPriceForAlpaca, roundPriceForAlpacaNumber, safeValidateResponse, searchNews, sellAllCrypto, sellCryptoNotional, sellToClose, sellToOpen, setLogger, setRiskFreeRate, shortWithStopLoss, sortOrdersByDate, index as tradingPolicy, trailingStops, updateAccountConfiguration, updateTrailingStop, validateAlpacaCredentials, validateAlphaVantageApiKey, validateMassiveApiKey$1 as validateMassiveApiKey, validateMultiLegOrder, validateResponse, verifyFetchKeepAlive, waitForOrderFill, withRetry, withTimeout };
68791
+ export { API_RETRY_CONFIGS, AVNewsArticleSchema, AVNewsResponseSchema, AdapticUtilsError, AlpacaAccountDetailsSchema, AlpacaApiError, AlpacaBarSchema, AlpacaClient, AlpacaCryptoBarsResponseSchema, AlpacaHistoricalBarsResponseSchema, AlpacaLatestBarsResponseSchema, AlpacaLatestQuotesResponseSchema, AlpacaLatestTradesResponseSchema, AlpacaMarketDataAPI, AlpacaNewsArticleSchema, AlpacaNewsResponseSchema, AlpacaOrderSchema, AlpacaOrdersArraySchema, AlpacaPortfolioHistoryResponseSchema, AlpacaPositionSchema, AlpacaPositionsArraySchema, AlpacaQuoteSchema, AlpacaTradeSchema, AlpacaTradingAPI, AlphaVantageError, AlphaVantageQuoteResponseSchema, AssetAllocationEngine, AuthenticationError, AutonomyMode, BTC_PAIRS, BarError, CryptoDataError, CryptoOrderError, DEFAULT_CACHE_OPTIONS, DEFAULT_RISK_FREE_RATE, DEFAULT_TIMEOUTS, DEFAULT_TRADING_POLICY, DataFormatError, DecisionMemoryOutcome, DecisionOutcome, DecisionRecordStatus, HttpClientError, HttpServerError, KEEP_ALIVE_DEFAULTS, LlmProvider, MARKET_DATA_API, MassiveAggregatesResponseSchema, MassiveApiError, MassiveDailyOpenCloseSchema, MassiveErrorResponseSchema, MassiveGroupedDailyResponseSchema, MassiveLastTradeResponseSchema, MassiveTickerDetailsResponseSchema, MassiveTickerInfoSchema, MassiveTradeSchema as MassiveTradeZodSchema, MassiveTradesResponseSchema, NetworkError, NewsError, OptionStrategyError, OptionsDataError, OverlaySeverity, OverlayStatus, OverlayType, QuoteError, RISK_FREE_RATE_TTL_MS, RateLimitError, RawMassivePriceDataSchema, StampedeProtectedCache, TRADING_API, TimeoutError, TokenBucketRateLimiter, TradeError, TrailingStopValidationError, USDC_PAIRS, USDT_PAIRS, USD_PAIRS, ValidationError, ValidationResponseError, WEBSOCKET_STREAMS, WebSocketError, account, adaptic, adptc, alpaca, analyzeBars, approximateImpliedVolatility, bracketOrders, buildOCCSymbol, buildOptionSymbol, buyCryptoNotional, buyToClose, buyToOpen, buyWithStopLoss, buyWithTrailingStop, calculateMoneyness, calculateOrderValue, calculatePeriodPerformance, calculatePutCallRatio, calculateTotalFilledValue, cancelAllCryptoOrders, cancelOCOOrder, cancelOTOOrder, cancelTrailingStop, cancelTrailingStopsForSymbol, checkTradingEligibility, clearClientCache, clock, closeAllOptionPositions, closeOptionPosition, createAlpacaClient, createAlpacaMarketDataAPI, createAlpacaTradingAPI, createBracketOrder, createButterflySpread, createClientFromEnv, createCoveredCall, createCryptoLimitOrder, createCryptoMarketOrder, createCryptoOrder, createCryptoStopLimitOrder, createCryptoStopOrder, createExecutorFromTradingAPI, createIronCondor$1 as createIronCondor, createIronCondor as createIronCondorAdvanced, createMultiLegOptionOrder, createOCOOrder, createOTOOrder, createOptionOrder, createPortfolioTrailingStops, createProtectiveBracket, createStampedeProtectedCache, createStraddle$1 as createStraddle, createStraddle as createStraddleAdvanced, createStrangle$1 as createStrangle, createStrangle as createStrangleAdvanced, createStreamManager, createTimeoutSignal, createTrailingStop, createVerticalSpread$1 as createVerticalSpread, createVerticalSpread as createVerticalSpreadAdvanced, entryWithPercentStopLoss, exerciseOption, extractGreeks, filterByExpiration, filterByStrike, filterByType, filterOrdersByDateRange, findATMOptions, findATMStrikes, findNearestExpiration, findOptionsByDelta, formatOrderForLog, formatOrderSummary, generateOptimalAllocation, getAccountConfiguration, getAccountDetails, getAccountSummary, getAgentPoolStatus, getAllOrders, getAlpacaCalendar, getAlpacaClock, getAverageDailyVolume, getBars, getBuyingPower, getCachedRiskFreeRateSync, getCachedRiskFreeRateSyncWithProvenance, getCrypto24HourChange, getCryptoBars, getCryptoDailyPrices, getCryptoPairsByQuote, getCryptoPrice, getCryptoSnapshots, getCryptoSpread, getCryptoStreamUrl, getCryptoTrades, getCurrentPrice, getCurrentPrices, getDailyPrices, getDailyReturns, getDaysToExpiration, getDefaultRiskProfile, getEquityCurve, getExpirationDates, getFilledOrders, getGroupedOptionChain, getHistoricalOptionsBars, getHistoricalTrades, getIntradayPrices, getLatestBars, getLatestCryptoQuotes, getLatestCryptoTrades, getLatestNews, getLatestOptionsQuotes, getLatestOptionsTrades, getLatestQuote, getLatestQuotes, getLatestTrade, getLatestTrades, getLogger, getMarginInfo, getNews, getNewsForSymbols, getOCOOrderStatus, getOTOOrderStatus, getOpenCryptoOrders, getOpenOrders$1 as getOpenOrdersQuery, getOpenTrailingStops, getOptionChain, getOptionContract, getOptionContracts, getOptionSpread, getOptionsChain, getOptionsSnapshots, getOptionsStreamUrl, getOptionsTradingLevel, getOrderHistory, getOrdersBySymbol, getPDTStatus, getPopularCryptoPairs, getPortfolioHistory, getPreviousClose, getPriceRange, getRiskFreeRate, getRiskFreeRateWithProvenance, getSpread, getSpreads, getStockStreamUrl, getStrikePrices, getSupportedCryptoPairs, getSymbolSentiment, getTimeout, getTradeVolume, getTradingApiUrl, getTradingWebSocketUrl, getTrailingStopHWM, groupOrdersByStatus, groupOrdersBySymbol, hasActiveTrailingStop, hasGoodLiquidity as hasOptionLiquidity, hasGoodLiquidity$1 as hasStockLiquidity, hasSufficientVolume, httpAgent, httpsAgent, isContractTradable, isCryptoPair, isExpiringWithin, isMarginAccount, isOptionOrderCancelable, isOptionOrderTerminal, isOrderFillable, isOrderFilled, isOrderOpen, isOrderTerminal$1 as isOrderTerminalStatus, isSupportedCryptoPair, isTransientNetworkError, index$1 as legacyApi, limitBuyWithTakeProfit, ocoOrders, orderUtils, otoOrders, paginate, paginateAll, parseOCCSymbol, protectLongPosition, protectShortPosition, rateLimiters, resetLogger, resetRiskFreeRateCache, rollOptionPosition, roundPriceForAlpaca$3 as roundPriceForAlpaca, roundPriceForAlpacaNumber, safeValidateResponse, searchNews, sellAllCrypto, sellCryptoNotional, sellToClose, sellToOpen, setLogger, setRiskFreeRate, shortWithStopLoss, sortOrdersByDate, index as tradingPolicy, trailingStops, updateAccountConfiguration, updateTrailingStop, validateAlpacaCredentials, validateAlphaVantageApiKey, validateMassiveApiKey$1 as validateMassiveApiKey, validateMultiLegOrder, validateResponse, verifyFetchKeepAlive, waitForOrderFill, withRetry, withTimeout };
68646
68792
  //# sourceMappingURL=index.mjs.map