@adaptic/utils 0.0.981 → 0.0.983

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
@@ -9255,6 +9255,172 @@ function getEquityValues(equityData, portfolioHistory, marketTimeUtil, period) {
9255
9255
  };
9256
9256
  }
9257
9257
 
9258
+ // risk-free-rate.ts
9259
+ /**
9260
+ * Conservative fallback annual risk-free rate used when no live rate has been
9261
+ * fetched yet AND the remote source is unreachable. Chosen to roughly match the
9262
+ * longer-run (post-2000) average of the 3-month US Treasury bill yield.
9263
+ *
9264
+ * This is the rate of LAST resort. Callers that need a live number should
9265
+ * prefer {@link getRiskFreeRate} (async) and only rely on
9266
+ * {@link getCachedRiskFreeRateSync} for hot paths that cannot be made async.
9267
+ */
9268
+ const DEFAULT_RISK_FREE_RATE = 0.02;
9269
+ /**
9270
+ * Cache TTL for the risk-free rate: 24 hours. Treasury yields update daily
9271
+ * (auction + close), so refreshing more aggressively provides no useful signal
9272
+ * and risks rate-limiting the public endpoint.
9273
+ */
9274
+ const RISK_FREE_RATE_TTL_MS = 24 * 60 * 60 * 1000;
9275
+ /**
9276
+ * US Treasury Fiscal Data API — Daily Treasury Bill Rates. Free, no API key,
9277
+ * updated each business day. Returns the most recent 4-, 8-, 13-, 17-, 26-,
9278
+ * and 52-week T-Bill rates. We use the 13-week ("3-month") field for Sharpe /
9279
+ * alpha, which is the industry-standard short risk-free proxy.
9280
+ *
9281
+ * See https://fiscaldata.treasury.gov/datasets/daily-treasury-bill-rates/
9282
+ */
9283
+ const TREASURY_BILL_RATES_URL = "https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/daily_treasury_bill_rates" +
9284
+ "?sort=-record_date&page%5Bsize%5D=1" +
9285
+ "&fields=record_date,security_term_week_num,avg_inv_rate";
9286
+ let cache = null;
9287
+ let inflight = null;
9288
+ /**
9289
+ * Clears the cached risk-free rate. Exported for tests and for callers that
9290
+ * want to force a re-fetch (e.g., at the start of a backtest run with a
9291
+ * different asOf date).
9292
+ */
9293
+ function resetRiskFreeRateCache() {
9294
+ cache = null;
9295
+ inflight = null;
9296
+ }
9297
+ /**
9298
+ * Explicitly sets the cached risk-free rate. Useful for deterministic tests,
9299
+ * backtests (where rf should be pinned to the asOf date), and environments
9300
+ * where an upstream service already provides the rate.
9301
+ *
9302
+ * @param rate - Annualized decimal rate (e.g. 0.0452 for 4.52%).
9303
+ */
9304
+ function setRiskFreeRate(rate) {
9305
+ if (!Number.isFinite(rate) || rate < 0 || rate > 1) {
9306
+ throw new Error(`Invalid risk-free rate: ${rate}. Must be a finite decimal in [0, 1].`);
9307
+ }
9308
+ cache = { rate, fetchedAt: Date.now() };
9309
+ }
9310
+ /**
9311
+ * Returns true iff the cached entry is present and younger than the TTL.
9312
+ */
9313
+ function isFresh(entry) {
9314
+ return entry !== null && Date.now() - entry.fetchedAt < RISK_FREE_RATE_TTL_MS;
9315
+ }
9316
+ /**
9317
+ * Fetches the latest 3-month (13-week) T-Bill annualized rate from the US
9318
+ * Treasury Fiscal Data API. Returns the rate as a decimal (e.g. 0.0452 for
9319
+ * 4.52%). Throws on any failure (network, parse, or missing field) — callers
9320
+ * are expected to handle fallback via {@link getRiskFreeRate}.
9321
+ */
9322
+ async function fetchTreasuryBillRate() {
9323
+ const signal = createTimeoutSignal(DEFAULT_TIMEOUTS.GENERAL);
9324
+ const res = await fetch(TREASURY_BILL_RATES_URL, {
9325
+ headers: { Accept: "application/json" },
9326
+ signal,
9327
+ });
9328
+ if (!res.ok) {
9329
+ throw new Error(`Treasury Fiscal Data API returned HTTP ${res.status} ${res.statusText}`);
9330
+ }
9331
+ const body = (await res.json());
9332
+ const rows = Array.isArray(body.data) ? body.data : [];
9333
+ if (rows.length === 0) {
9334
+ throw new Error("Treasury Fiscal Data API returned no rows");
9335
+ }
9336
+ // Prefer the 13-week (3-month) bill; fall back to the shortest term
9337
+ // available on that record date if 13-week is missing.
9338
+ const preferred = rows.find((row) => row.security_term_week_num === "13") ?? rows[0];
9339
+ const percent = Number.parseFloat(preferred.avg_inv_rate);
9340
+ if (!Number.isFinite(percent)) {
9341
+ throw new Error(`Treasury Fiscal Data API returned non-numeric rate: ${preferred.avg_inv_rate}`);
9342
+ }
9343
+ // avg_inv_rate is quoted as a percentage (e.g. "4.52"); normalize to a
9344
+ // decimal for downstream math.
9345
+ return percent / 100;
9346
+ }
9347
+ /**
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;
9367
+ }
9368
+ if (inflight !== null) {
9369
+ return inflight;
9370
+ }
9371
+ inflight = (async () => {
9372
+ try {
9373
+ const rate = await fetchTreasuryBillRate();
9374
+ cache = { rate, fetchedAt: Date.now() };
9375
+ return rate;
9376
+ }
9377
+ catch (error) {
9378
+ const message = error instanceof Error ? error.message : String(error);
9379
+ 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;
9382
+ }
9383
+ 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;
9385
+ }
9386
+ finally {
9387
+ inflight = null;
9388
+ }
9389
+ })();
9390
+ return inflight;
9391
+ }
9392
+ /**
9393
+ * Synchronous accessor that returns the most recent cached risk-free rate
9394
+ * without performing I/O. If the cache is stale, a background refresh is
9395
+ * kicked off (fire-and-forget) so the next synchronous call sees a fresh
9396
+ * value. Intended for hot paths (e.g., Sharpe/alpha calculation inside tight
9397
+ * loops) where the existing function signature cannot be made async.
9398
+ *
9399
+ * Callers that can tolerate an async boundary should prefer
9400
+ * {@link getRiskFreeRate}.
9401
+ *
9402
+ * @returns The cached annualized risk-free rate as a decimal, or
9403
+ * {@link DEFAULT_RISK_FREE_RATE} if no value has been cached yet.
9404
+ */
9405
+ function getCachedRiskFreeRateSync() {
9406
+ if (cache === null) {
9407
+ // 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.
9411
+ });
9412
+ return DEFAULT_RISK_FREE_RATE;
9413
+ }
9414
+ if (!isFresh(cache)) {
9415
+ // Stale: trigger background refresh but still return the last-known-good
9416
+ // value so the call remains synchronous.
9417
+ void getRiskFreeRate().catch(() => {
9418
+ // Errors are already logged inside getRiskFreeRate.
9419
+ });
9420
+ }
9421
+ return cache.rate;
9422
+ }
9423
+
9258
9424
  // metric-calcs.ts
9259
9425
  /**
9260
9426
  * Calculates daily returns from an array of closing prices
@@ -9416,9 +9582,11 @@ function calculateBetaFromReturns$1(portfolioReturns, benchmarkReturns) {
9416
9582
  covariance += portfolioDiff * benchmarkDiff;
9417
9583
  variance += benchmarkDiff * benchmarkDiff;
9418
9584
  }
9419
- // Finalize calculations
9420
- covariance /= n;
9421
- variance /= n;
9585
+ // Finalize calculations using sample (Bessel-corrected) estimators —
9586
+ // divide by (n - 1), not n. The guard above (validIndices.length < 2)
9587
+ // already ensures n >= 2, so (n - 1) is always safe.
9588
+ covariance /= n - 1;
9589
+ variance /= n - 1;
9422
9590
  // Handle zero variance case
9423
9591
  if (Math.abs(variance) < 1e-10) {
9424
9592
  getLogger().warn("Benchmark variance is effectively zero. Setting beta to 0.");
@@ -9487,8 +9655,9 @@ async function calculateRiskAdjustedReturn$1(tradeBars) {
9487
9655
  getLogger().warn("Standard deviation is zero or non-finite, cannot calculate Sharpe ratio.");
9488
9656
  return "N/A";
9489
9657
  }
9490
- // Assume a risk-free rate, e.g., 2%
9491
- const riskFreeRate = 0.02; // Annual risk-free rate (2%)
9658
+ // Fetch live annualized risk-free rate (3-month T-Bill), cached daily.
9659
+ // See src/risk-free-rate.ts for source + fallback behavior.
9660
+ const riskFreeRate = await getRiskFreeRate();
9492
9661
  // Calculate Sharpe Ratio
9493
9662
  const sharpeRatio = (avgAnnualReturn - riskFreeRate) / stdDevAnnual;
9494
9663
  if (!isFinite(sharpeRatio)) {
@@ -9536,7 +9705,10 @@ async function calculateAlphaAndBeta$1(tradeBars, benchmarkBars, isShort) {
9536
9705
  alignedTradeReturns.length;
9537
9706
  const avgBenchmarkReturn = alignedBenchmarkReturns.reduce((sum, ret) => sum + ret, 0) /
9538
9707
  alignedBenchmarkReturns.length;
9539
- const riskFreeRateDaily = 0.02 / 252; // Assuming 2% annual risk-free rate
9708
+ // Fetch live annualized risk-free rate (3-month T-Bill), cached daily.
9709
+ // See src/risk-free-rate.ts for source + fallback behavior.
9710
+ const riskFreeRateAnnual = await getRiskFreeRate();
9711
+ const riskFreeRateDaily = riskFreeRateAnnual / 252;
9540
9712
  // Alpha calculation adjusts based on position direction
9541
9713
  const alpha = avgTradeReturn -
9542
9714
  (riskFreeRateDaily +
@@ -9840,8 +10012,9 @@ async function calculateRiskAdjustedReturn(portfolioHistory) {
9840
10012
  getLogger().warn("Standard deviation is zero or non-finite, cannot calculate Sharpe ratio.");
9841
10013
  return "N/A";
9842
10014
  }
9843
- // Assume a risk-free rate, e.g., 2%
9844
- const riskFreeRate = 0.02; // Annual risk-free rate (2%)
10015
+ // Fetch live annualized risk-free rate (3-month T-Bill), cached daily.
10016
+ // See src/risk-free-rate.ts for source + fallback behavior.
10017
+ const riskFreeRate = await getRiskFreeRate();
9845
10018
  // Calculate Sharpe Ratio
9846
10019
  const sharpeRatio = (avgAnnualReturn - riskFreeRate) / stdDevAnnual;
9847
10020
  if (!isFinite(sharpeRatio)) {
@@ -10025,7 +10198,9 @@ async function calculateAlphaAndBeta(portfolioHistory, benchmarkBars) {
10025
10198
  };
10026
10199
  }
10027
10200
  // **Calculate alpha**
10028
- const riskFreeRateAnnual = 0.02; // 2%
10201
+ // Fetch live annualized risk-free rate (3-month T-Bill), cached daily.
10202
+ // See src/risk-free-rate.ts for source + fallback behavior.
10203
+ const riskFreeRateAnnual = await getRiskFreeRate();
10029
10204
  const tradingDaysPerYear = 252;
10030
10205
  const riskFreeRateDaily = riskFreeRateAnnual / tradingDaysPerYear;
10031
10206
  const alpha = portfolioAvgReturn -
@@ -10289,8 +10464,12 @@ function calculateBetaFromReturns(portfolioReturns, benchmarkReturns) {
10289
10464
  covariance += portfolioDiff * benchmarkDiff;
10290
10465
  variance += benchmarkDiff ** 2;
10291
10466
  }
10292
- covariance /= n;
10293
- variance /= n;
10467
+ // Use sample (Bessel-corrected) estimators — divide by (n - 1), not n.
10468
+ // For n === 1 there is no degrees-of-freedom left; treat as zero variance
10469
+ // so beta falls through to the zero-variance guard below.
10470
+ const denom = n > 1 ? n - 1 : 1;
10471
+ covariance /= denom;
10472
+ variance /= denom;
10294
10473
  // Handle zero variance
10295
10474
  if (variance === 0) {
10296
10475
  getLogger().warn("Benchmark variance is zero. Setting beta to 0.");
@@ -68463,5 +68642,5 @@ const adaptic = {
68463
68642
  };
68464
68643
  const adptc = adaptic;
68465
68644
 
68466
- 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_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, 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, 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, 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, rollOptionPosition, roundPriceForAlpaca$3 as roundPriceForAlpaca, roundPriceForAlpacaNumber, safeValidateResponse, searchNews, sellAllCrypto, sellCryptoNotional, sellToClose, sellToOpen, setLogger, shortWithStopLoss, sortOrdersByDate, index as tradingPolicy, trailingStops, updateAccountConfiguration, updateTrailingStop, validateAlpacaCredentials, validateAlphaVantageApiKey, validateMassiveApiKey$1 as validateMassiveApiKey, validateMultiLegOrder, validateResponse, verifyFetchKeepAlive, waitForOrderFill, withRetry, withTimeout };
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 };
68467
68646
  //# sourceMappingURL=index.mjs.map