@adaptic/utils 0.1.49 → 0.1.50

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.
Files changed (137) hide show
  1. package/dist/index.cjs +58226 -229
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.mjs +58193 -229
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/types/alpaca/client.d.ts +105 -0
  6. package/dist/types/alpaca/client.d.ts.map +1 -0
  7. package/dist/types/alpaca/crypto/data.d.ts +281 -0
  8. package/dist/types/alpaca/crypto/data.d.ts.map +1 -0
  9. package/dist/types/alpaca/crypto/index.d.ts +75 -0
  10. package/dist/types/alpaca/crypto/index.d.ts.map +1 -0
  11. package/dist/types/alpaca/crypto/orders.d.ts +221 -0
  12. package/dist/types/alpaca/crypto/orders.d.ts.map +1 -0
  13. package/dist/types/alpaca/index.d.ts +204 -0
  14. package/dist/types/alpaca/index.d.ts.map +1 -0
  15. package/dist/types/alpaca/market-data/bars.d.ts +142 -0
  16. package/dist/types/alpaca/market-data/bars.d.ts.map +1 -0
  17. package/dist/types/alpaca/market-data/index.d.ts +13 -0
  18. package/dist/types/alpaca/market-data/index.d.ts.map +1 -0
  19. package/dist/types/alpaca/market-data/news.d.ts +87 -0
  20. package/dist/types/alpaca/market-data/news.d.ts.map +1 -0
  21. package/dist/types/alpaca/market-data/quotes.d.ts +85 -0
  22. package/dist/types/alpaca/market-data/quotes.d.ts.map +1 -0
  23. package/dist/types/alpaca/market-data/trades.d.ts +98 -0
  24. package/dist/types/alpaca/market-data/trades.d.ts.map +1 -0
  25. package/dist/types/alpaca/options/contracts.d.ts +279 -0
  26. package/dist/types/alpaca/options/contracts.d.ts.map +1 -0
  27. package/dist/types/alpaca/options/data.d.ts +126 -0
  28. package/dist/types/alpaca/options/data.d.ts.map +1 -0
  29. package/dist/types/alpaca/options/index.d.ts +17 -0
  30. package/dist/types/alpaca/options/index.d.ts.map +1 -0
  31. package/dist/types/alpaca/options/orders.d.ts +366 -0
  32. package/dist/types/alpaca/options/orders.d.ts.map +1 -0
  33. package/dist/types/alpaca/options/strategies.d.ts +224 -0
  34. package/dist/types/alpaca/options/strategies.d.ts.map +1 -0
  35. package/dist/types/alpaca/streams/base-stream.d.ts +143 -0
  36. package/dist/types/alpaca/streams/base-stream.d.ts.map +1 -0
  37. package/dist/types/alpaca/streams/crypto-stream.d.ts +173 -0
  38. package/dist/types/alpaca/streams/crypto-stream.d.ts.map +1 -0
  39. package/dist/types/alpaca/streams/index.d.ts +54 -0
  40. package/dist/types/alpaca/streams/index.d.ts.map +1 -0
  41. package/dist/types/alpaca/streams/option-stream.d.ts +167 -0
  42. package/dist/types/alpaca/streams/option-stream.d.ts.map +1 -0
  43. package/dist/types/alpaca/streams/stock-stream.d.ts +176 -0
  44. package/dist/types/alpaca/streams/stock-stream.d.ts.map +1 -0
  45. package/dist/types/alpaca/streams/stream-manager.d.ts +277 -0
  46. package/dist/types/alpaca/streams/stream-manager.d.ts.map +1 -0
  47. package/dist/types/alpaca/streams/trading-stream.d.ts +186 -0
  48. package/dist/types/alpaca/streams/trading-stream.d.ts.map +1 -0
  49. package/dist/types/alpaca/trading/account.d.ts +198 -0
  50. package/dist/types/alpaca/trading/account.d.ts.map +1 -0
  51. package/dist/types/alpaca/trading/bracket-orders.d.ts +162 -0
  52. package/dist/types/alpaca/trading/bracket-orders.d.ts.map +1 -0
  53. package/dist/types/alpaca/trading/clock.d.ts +99 -0
  54. package/dist/types/alpaca/trading/clock.d.ts.map +1 -0
  55. package/dist/types/alpaca/trading/index.d.ts +15 -0
  56. package/dist/types/alpaca/trading/index.d.ts.map +1 -0
  57. package/dist/types/alpaca/trading/oco-orders.d.ts +203 -0
  58. package/dist/types/alpaca/trading/oco-orders.d.ts.map +1 -0
  59. package/dist/types/alpaca/trading/order-utils.d.ts +404 -0
  60. package/dist/types/alpaca/trading/order-utils.d.ts.map +1 -0
  61. package/dist/types/alpaca/trading/orders.d.ts +199 -0
  62. package/dist/types/alpaca/trading/orders.d.ts.map +1 -0
  63. package/dist/types/alpaca/trading/oto-orders.d.ts +282 -0
  64. package/dist/types/alpaca/trading/oto-orders.d.ts.map +1 -0
  65. package/dist/types/alpaca/trading/positions.d.ts +389 -0
  66. package/dist/types/alpaca/trading/positions.d.ts.map +1 -0
  67. package/dist/types/alpaca/trading/smart-orders.d.ts +301 -0
  68. package/dist/types/alpaca/trading/smart-orders.d.ts.map +1 -0
  69. package/dist/types/alpaca/trading/trailing-stops.d.ts +247 -0
  70. package/dist/types/alpaca/trading/trailing-stops.d.ts.map +1 -0
  71. package/dist/types/config/api-endpoints.d.ts +94 -0
  72. package/dist/types/config/api-endpoints.d.ts.map +1 -0
  73. package/dist/types/errors/index.d.ts +130 -0
  74. package/dist/types/errors/index.d.ts.map +1 -0
  75. package/dist/types/examples/rate-limiter-example.d.ts +7 -0
  76. package/dist/types/examples/rate-limiter-example.d.ts.map +1 -0
  77. package/dist/types/http-timeout.d.ts +37 -0
  78. package/dist/types/http-timeout.d.ts.map +1 -0
  79. package/dist/types/index.d.ts +9 -0
  80. package/dist/types/index.d.ts.map +1 -1
  81. package/dist/types/logger.d.ts +68 -0
  82. package/dist/types/logger.d.ts.map +1 -0
  83. package/dist/types/massive.d.ts +167 -0
  84. package/dist/types/massive.d.ts.map +1 -0
  85. package/dist/types/rate-limiter.d.ts +173 -0
  86. package/dist/types/rate-limiter.d.ts.map +1 -0
  87. package/dist/types/risk-free-rate.d.ts +153 -0
  88. package/dist/types/risk-free-rate.d.ts.map +1 -0
  89. package/dist/types/schemas/alpaca-schemas.d.ts +779 -0
  90. package/dist/types/schemas/alpaca-schemas.d.ts.map +1 -0
  91. package/dist/types/schemas/alphavantage-schemas.d.ts +255 -0
  92. package/dist/types/schemas/alphavantage-schemas.d.ts.map +1 -0
  93. package/dist/types/schemas/index.d.ts +21 -0
  94. package/dist/types/schemas/index.d.ts.map +1 -0
  95. package/dist/types/schemas/massive-schemas.d.ts +561 -0
  96. package/dist/types/schemas/massive-schemas.d.ts.map +1 -0
  97. package/dist/types/schemas/validate-response.d.ts +88 -0
  98. package/dist/types/schemas/validate-response.d.ts.map +1 -0
  99. package/dist/types/trading-policy/defaults/default-trading-policy.d.ts +29 -0
  100. package/dist/types/trading-policy/defaults/default-trading-policy.d.ts.map +1 -0
  101. package/dist/types/trading-policy/enums.d.ts +85 -0
  102. package/dist/types/trading-policy/enums.d.ts.map +1 -0
  103. package/dist/types/trading-policy/index.d.ts +13 -2
  104. package/dist/types/trading-policy/index.d.ts.map +1 -1
  105. package/dist/types/trading-policy/schemas/asset-universe-prefs.schema.d.ts +182 -0
  106. package/dist/types/trading-policy/schemas/asset-universe-prefs.schema.d.ts.map +1 -0
  107. package/dist/types/trading-policy/schemas/audit-notification-prefs.schema.d.ts +112 -0
  108. package/dist/types/trading-policy/schemas/audit-notification-prefs.schema.d.ts.map +1 -0
  109. package/dist/types/trading-policy/schemas/autonomy-prefs.schema.d.ts +369 -0
  110. package/dist/types/trading-policy/schemas/autonomy-prefs.schema.d.ts.map +1 -0
  111. package/dist/types/trading-policy/schemas/effective-policy.schema.d.ts +1703 -0
  112. package/dist/types/trading-policy/schemas/effective-policy.schema.d.ts.map +1 -0
  113. package/dist/types/trading-policy/schemas/execution-prefs.schema.d.ts +122 -0
  114. package/dist/types/trading-policy/schemas/execution-prefs.schema.d.ts.map +1 -0
  115. package/dist/types/trading-policy/schemas/index.d.ts +13 -0
  116. package/dist/types/trading-policy/schemas/index.d.ts.map +1 -0
  117. package/dist/types/trading-policy/schemas/model-prefs.schema.d.ts +249 -0
  118. package/dist/types/trading-policy/schemas/model-prefs.schema.d.ts.map +1 -0
  119. package/dist/types/trading-policy/schemas/overlay-response-prefs.schema.d.ts +217 -0
  120. package/dist/types/trading-policy/schemas/overlay-response-prefs.schema.d.ts.map +1 -0
  121. package/dist/types/trading-policy/schemas/policy-mutation.schema.d.ts +3031 -0
  122. package/dist/types/trading-policy/schemas/policy-mutation.schema.d.ts.map +1 -0
  123. package/dist/types/trading-policy/schemas/portfolio-construction-prefs.schema.d.ts +258 -0
  124. package/dist/types/trading-policy/schemas/portfolio-construction-prefs.schema.d.ts.map +1 -0
  125. package/dist/types/trading-policy/schemas/position-management-prefs.schema.d.ts +218 -0
  126. package/dist/types/trading-policy/schemas/position-management-prefs.schema.d.ts.map +1 -0
  127. package/dist/types/trading-policy/schemas/risk-budget-prefs.schema.d.ts +188 -0
  128. package/dist/types/trading-policy/schemas/risk-budget-prefs.schema.d.ts.map +1 -0
  129. package/dist/types/trading-policy/schemas/signal-consumption-prefs.schema.d.ts +274 -0
  130. package/dist/types/trading-policy/schemas/signal-consumption-prefs.schema.d.ts.map +1 -0
  131. package/dist/types/types/alpaca-types.d.ts +108 -17
  132. package/dist/types/types/alpaca-types.d.ts.map +1 -1
  133. package/dist/types/utils/paginator.d.ts +154 -0
  134. package/dist/types/utils/paginator.d.ts.map +1 -0
  135. package/dist/types/utils/retry.d.ts +83 -0
  136. package/dist/types/utils/retry.d.ts.map +1 -0
  137. package/package.json +5 -1
@@ -0,0 +1,167 @@
1
+ /**********************************************************************************
2
+ * Massive.com calls
3
+ **********************************************************************************/
4
+ import { MassiveDailyOpenClose, MassiveGroupedDailyResponse, MassivePriceData, MassiveQuote, MassiveResult, MassiveSpreadInfo, MassiveTickerInfo, MassiveTradesResponse } from "./types";
5
+ /**
6
+ * Fetches general information about a stock ticker.
7
+ * @param {string} symbol - The stock ticker symbol to fetch information for.
8
+ * @param {Object} [options] - Optional parameters.
9
+ * @param {string} [options.apiKey] - The API key to use for the request.
10
+ * @returns {Promise<MassiveTickerInfo | null>} The ticker information or null if not found.
11
+ */
12
+ export declare const fetchTickerInfo: (symbol: string, options?: {
13
+ apiKey?: string;
14
+ }) => Promise<MassiveTickerInfo | null>;
15
+ /**
16
+ * Fetches the last trade for a given stock ticker.
17
+ * @param {string} symbol - The stock ticker symbol to fetch the last trade for.
18
+ * @param {Object} [options] - Optional parameters.
19
+ * @param {string} [options.apiKey] - The API key to use for the request.
20
+ * @returns {Promise<MassiveQuote>} The last trade information.
21
+ */
22
+ export declare const fetchLastTrade: (symbol: string, options?: {
23
+ apiKey?: string;
24
+ }) => Promise<MassiveQuote>;
25
+ /**
26
+ * Fetches the latest NBBO quote for a given stock ticker using the Massive v3 API.
27
+ * Returns processed spread information including bid, ask, spread, and mid price.
28
+ *
29
+ * @param symbol - The stock ticker symbol.
30
+ * @param options - Optional parameters including API key override.
31
+ * @returns Processed quote data with spread metrics.
32
+ */
33
+ export declare const fetchLastQuote: (symbol: string, options?: {
34
+ apiKey?: string;
35
+ }) => Promise<MassiveSpreadInfo>;
36
+ /**
37
+ * Fetches price data for a given stock ticker.
38
+ * @param {Object} params - The parameters for fetching price data.
39
+ * @param {string} params.ticker - The stock ticker symbol.
40
+ * @param {number} params.start - The start timestamp for fetching price data.
41
+ * @param {number} [params.end] - The end timestamp for fetching price data.
42
+ * @param {number} params.multiplier - The multiplier for the price data.
43
+ * @param {string} params.timespan - The timespan for the price data.
44
+ * @param {number} [params.limit] - The maximum number of price data points to fetch.
45
+ * @param {Object} [options] - Optional parameters.
46
+ * @param {string} [options.apiKey] - The API key to use for the request.
47
+ * @returns {Promise<MassivePriceData[]>} The fetched price data.
48
+ */
49
+ export declare const fetchPrices: (params: {
50
+ ticker: string;
51
+ start: number;
52
+ end?: number;
53
+ multiplier: number;
54
+ timespan: string;
55
+ limit?: number;
56
+ adjusted?: boolean;
57
+ }, options?: {
58
+ apiKey?: string;
59
+ }) => Promise<MassivePriceData[]>;
60
+ /**
61
+ * Variant of {@link fetchPrices} that returns a discriminated
62
+ * {@link MassiveResult} wrapper, surfacing the upstream feed status (`OK` vs
63
+ * `DELAYED`) at the result level. This is the preferred entry point for new
64
+ * code that needs to gate latency-sensitive decisions on freshness.
65
+ *
66
+ * The underlying bars are still stamped with `_freshness` so consumers that
67
+ * already destructure the array can branch per-bar; the wrapper simply
68
+ * promotes that information to the top of the result for clarity.
69
+ *
70
+ * DE-006: closes the loop for callers that need to know when the Massive feed
71
+ * is on a delayed plan (e.g. free tier, market-data outage downgrade).
72
+ *
73
+ * @param params - Same parameters accepted by {@link fetchPrices}.
74
+ * @param options - Same options accepted by {@link fetchPrices}.
75
+ * @returns A {@link MassiveResult} carrying the bar array plus freshness
76
+ * metadata.
77
+ */
78
+ export declare const fetchPricesWithFreshness: (params: {
79
+ ticker: string;
80
+ start: number;
81
+ end?: number;
82
+ multiplier: number;
83
+ timespan: string;
84
+ limit?: number;
85
+ adjusted?: boolean;
86
+ }, options?: {
87
+ apiKey?: string;
88
+ }) => Promise<MassiveResult<MassivePriceData[]>>;
89
+ /**
90
+ * Analyzes the price data for a given stock.
91
+ * @param {MassivePriceData[]} priceData - The price data to analyze.
92
+ * @returns {string} The analysis report.
93
+ */
94
+ export declare function analyseMassivePriceData(priceData: MassivePriceData[]): string;
95
+ /**
96
+ * Fetches grouped daily price data for a specific date.
97
+ * @param {string} date - The date to fetch grouped daily data for.
98
+ * @param {Object} [options] - Optional parameters.
99
+ * @param {string} [options.apiKey] - The API key to use for the request.
100
+ * @param {boolean} [options.adjusted] - Whether to adjust the data.
101
+ * @param {boolean} [options.includeOTC] - Whether to include OTC data.
102
+ * @returns {Promise<MassiveGroupedDailyResponse>} The grouped daily response.
103
+ */
104
+ export declare const fetchGroupedDaily: (date: string, options?: {
105
+ apiKey?: string;
106
+ adjusted?: boolean;
107
+ includeOTC?: boolean;
108
+ }) => Promise<MassiveGroupedDailyResponse>;
109
+ /**
110
+ * Formats the price data into a readable string.
111
+ * @param {MassivePriceData[]} priceData - The price data to format.
112
+ * @returns {string} The formatted price data.
113
+ */
114
+ export declare function formatPriceData(priceData: MassivePriceData[]): string;
115
+ export declare const fetchDailyOpenClose: (
116
+ /**
117
+ * Fetches the daily open and close data for a given stock ticker.
118
+ * @param {string} symbol - The stock ticker symbol to fetch data for.
119
+ * @param {Date} [date=new Date()] - The date to fetch data for.
120
+ * @param {Object} [options] - Optional parameters.
121
+ * @param {string} [options.apiKey] - The API key to use for the request.
122
+ * @param {boolean} [options.adjusted] - Whether to adjust the data.
123
+ * @returns {Promise<MassiveDailyOpenClose>} The daily open and close data.
124
+ */
125
+ symbol: string, date?: Date, options?: {
126
+ apiKey?: string;
127
+ adjusted?: boolean;
128
+ }) => Promise<MassiveDailyOpenClose>;
129
+ /**
130
+ * Gets the previous close price for a given stock ticker.
131
+ * @param {string} symbol - The stock ticker symbol to fetch the previous close for.
132
+ * @param {Date} [referenceDate] - The reference date to use for fetching the previous close.
133
+ * @returns {Promise<{ close: number; date: Date }>} The previous close price and date.
134
+ */
135
+ export declare function getPreviousClose(symbol: string, referenceDate?: Date, options?: {
136
+ apiKey?: string;
137
+ }): Promise<{
138
+ close: number;
139
+ date: Date;
140
+ }>;
141
+ /**
142
+ * Fetches trade data for a given stock ticker.
143
+ * @param {string} symbol - The stock ticker symbol to fetch trades for.
144
+ * @param {Object} [options] - Optional parameters.
145
+ * @param {string} [options.apiKey] - The API key to use for the request.
146
+ * @param {string | number} [options.timestamp] - The timestamp for fetching trades.
147
+ * @param {string | number} [options.timestampgt] - Greater than timestamp for fetching trades.
148
+ * @param {string | number} [options.timestampgte] - Greater than or equal to timestamp for fetching trades.
149
+ * @param {string | number} [options.timestamplt] - Less than timestamp for fetching trades.
150
+ * @param {string | number} [options.timestamplte] - Less than or equal to timestamp for fetching trades.
151
+ * @param {'asc' | 'desc'} [options.order] - The order of the trades.
152
+ * @param {number} [options.limit] - The maximum number of trades to fetch.
153
+ * @param {string} [options.sort] - The sort order for the trades.
154
+ * @returns {Promise<MassiveTradesResponse>} The fetched trades response.
155
+ */
156
+ export declare const fetchTrades: (symbol: string, options?: {
157
+ apiKey?: string;
158
+ timestamp?: string | number;
159
+ timestampgt?: string | number;
160
+ timestampgte?: string | number;
161
+ timestamplt?: string | number;
162
+ timestamplte?: string | number;
163
+ order?: "asc" | "desc";
164
+ limit?: number;
165
+ sort?: string;
166
+ }) => Promise<MassiveTradesResponse>;
167
+ //# sourceMappingURL=massive.d.ts.map
@@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eAAO,MAAM,WAAW,GACtB,QAAQ,MAAM,EACd,UAAU;IACR,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC9B,YAAY,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC/B,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC9B,YAAY,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC/B,KAAK,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,KACA,OAAO,CAAC,qBAAqB,CAsE/B,CAAC"}
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Token bucket rate limiter for external API integrations
3
+ *
4
+ * Implements client-side rate limiting to prevent exceeding API quotas
5
+ * and ensure fair usage of external services like Alpaca, Massive, and AlphaVantage.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { rateLimiters } from '@adaptic/utils';
10
+ *
11
+ * // Before making an API call
12
+ * await rateLimiters.alpaca.acquire();
13
+ * const result = await makeAlpacaApiCall();
14
+ * ```
15
+ */
16
+ import { RateLimitError } from "./errors";
17
+ export { RateLimitError };
18
+ /**
19
+ * Configuration for a rate limiter instance
20
+ */
21
+ export interface RateLimiterConfig {
22
+ /** Maximum number of tokens (requests) that can be accumulated */
23
+ maxTokens: number;
24
+ /** Rate at which tokens are refilled (tokens per second) */
25
+ refillRate: number;
26
+ /** Human-readable label for logging and error messages */
27
+ label: string;
28
+ /** Maximum time to wait for a token before timing out (milliseconds) */
29
+ timeoutMs?: number;
30
+ }
31
+ /**
32
+ * Token bucket rate limiter implementation
33
+ *
34
+ * Uses the token bucket algorithm to control the rate of API requests.
35
+ * Tokens are consumed on each request and refilled at a constant rate.
36
+ * Requests that exceed the available tokens are queued and processed
37
+ * when tokens become available.
38
+ */
39
+ export declare class TokenBucketRateLimiter {
40
+ private readonly config;
41
+ private tokens;
42
+ private lastRefill;
43
+ private queue;
44
+ private readonly timeoutMs;
45
+ private processingQueue;
46
+ /**
47
+ * Creates a new rate limiter instance
48
+ *
49
+ * @param config - Rate limiter configuration
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * // Alpaca: 200 requests per minute
54
+ * const alpacaLimiter = new TokenBucketRateLimiter({
55
+ * maxTokens: 200,
56
+ * refillRate: 200 / 60, // ~3.33 per second
57
+ * label: 'alpaca',
58
+ * timeoutMs: 60000
59
+ * });
60
+ * ```
61
+ */
62
+ constructor(config: RateLimiterConfig);
63
+ /**
64
+ * Acquires a token for making an API request
65
+ *
66
+ * If a token is available, it is consumed immediately.
67
+ * If no tokens are available, the request is queued and will resolve
68
+ * when a token becomes available or reject if it times out.
69
+ *
70
+ * @throws {RateLimitError} If the request times out waiting for a token
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * try {
75
+ * await limiter.acquire();
76
+ * // Make API call
77
+ * } catch (error) {
78
+ * if (error instanceof RateLimitError) {
79
+ * // Handle rate limit timeout
80
+ * }
81
+ * }
82
+ * ```
83
+ */
84
+ acquire(): Promise<void>;
85
+ /**
86
+ * Refills tokens based on elapsed time and processes queued requests
87
+ *
88
+ * Tokens are refilled at the configured rate up to the maximum capacity.
89
+ * If tokens are available after refilling, queued requests are processed.
90
+ */
91
+ private refill;
92
+ /**
93
+ * Processes queued requests when tokens are available
94
+ *
95
+ * Prevents concurrent queue processing to ensure FIFO order.
96
+ */
97
+ private processQueue;
98
+ /**
99
+ * Gets the current number of available tokens
100
+ *
101
+ * @returns Number of tokens currently available
102
+ */
103
+ getAvailableTokens(): number;
104
+ /**
105
+ * Gets the current queue length
106
+ *
107
+ * @returns Number of requests waiting for tokens
108
+ */
109
+ getQueueLength(): number;
110
+ /**
111
+ * Clears all queued requests and resets the token bucket
112
+ *
113
+ * All queued requests will be rejected with a RateLimitError.
114
+ * Useful for cleanup or when changing rate limit configurations.
115
+ */
116
+ reset(): void;
117
+ }
118
+ /**
119
+ * Pre-configured rate limiters for common external APIs
120
+ *
121
+ * These limiters are configured based on the documented rate limits
122
+ * for each service. Adjust the configurations if you have different
123
+ * tier access or if limits change.
124
+ *
125
+ * @example
126
+ * ```typescript
127
+ * import { rateLimiters } from '@adaptic/utils';
128
+ *
129
+ * // Use before making API calls
130
+ * await rateLimiters.alpaca.acquire();
131
+ * await rateLimiters.massive.acquire();
132
+ * await rateLimiters.alphaVantage.acquire();
133
+ * ```
134
+ */
135
+ export declare const rateLimiters: {
136
+ /**
137
+ * Alpaca API rate limiter
138
+ *
139
+ * Configured for 1000 requests per minute (paid tier).
140
+ * The token bucket allows burst up to maxTokens, then refills at the steady rate.
141
+ * See: https://alpaca.markets/docs/api-references/trading-api/#rate-limit
142
+ */
143
+ alpaca: TokenBucketRateLimiter;
144
+ /**
145
+ * Massive.com API rate limiter
146
+ *
147
+ * Configured generously for paid unlimited tier. The bucket exists only as a
148
+ * safety net against runaway loops — the 1000 token burst and 500/sec refill
149
+ * should never be hit under normal operation. If the paid plan truly has no
150
+ * hard limit, this just prevents accidental self-DDoS.
151
+ */
152
+ massive: TokenBucketRateLimiter;
153
+ /**
154
+ * AlphaVantage API rate limiter
155
+ *
156
+ * Configured for 5 requests per minute (free tier).
157
+ * For premium tier (75/min), create a custom limiter:
158
+ *
159
+ * @example
160
+ * ```typescript
161
+ * const premiumAV = new TokenBucketRateLimiter({
162
+ * maxTokens: 75,
163
+ * refillRate: 75 / 60,
164
+ * label: 'alphaVantage-premium',
165
+ * timeoutMs: 60000,
166
+ * });
167
+ * ```
168
+ *
169
+ * See: https://www.alphavantage.co/premium/
170
+ */
171
+ alphaVantage: TokenBucketRateLimiter;
172
+ };
173
+ //# sourceMappingURL=rate-limiter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limiter.d.ts","sourceRoot":"","sources":["../../src/rate-limiter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE1C,OAAO,EAAE,cAAc,EAAE,CAAC;AAE1B;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,kEAAkE;IAClE,SAAS,EAAE,MAAM,CAAC;IAClB,4DAA4D;IAC5D,UAAU,EAAE,MAAM,CAAC;IACnB,0DAA0D;IAC1D,KAAK,EAAE,MAAM,CAAC;IACd,wEAAwE;IACxE,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAcD;;;;;;;GAOG;AACH,qBAAa,sBAAsB;IAuBrB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAtBnC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,eAAe,CAAkB;IAEzC;;;;;;;;;;;;;;;OAeG;gBAC0B,MAAM,EAAE,iBAAiB;IAMtD;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAkD9B;;;;;OAKG;IACH,OAAO,CAAC,MAAM;IAYd;;;;OAIG;IACH,OAAO,CAAC,YAAY;IA6BpB;;;;OAIG;IACH,kBAAkB,IAAI,MAAM;IAK5B;;;;OAIG;IACH,cAAc,IAAI,MAAM;IAIxB;;;;;OAKG;IACH,KAAK,IAAI,IAAI;CAwBd;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,YAAY;IACvB;;;;;;OAMG;;IAQH;;;;;;;OAOG;;IAQH;;;;;;;;;;;;;;;;;OAiBG;;CAOJ,CAAC"}
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Conservative fallback annual risk-free rate used when no live rate has been
3
+ * fetched yet AND the remote source is unreachable. Chosen to roughly match the
4
+ * longer-run (post-2000) average of the 3-month US Treasury bill yield.
5
+ *
6
+ * This is the rate of LAST resort. Callers that need a live number should
7
+ * prefer {@link getRiskFreeRate} (async) and only rely on
8
+ * {@link getCachedRiskFreeRateSync} for hot paths that cannot be made async.
9
+ */
10
+ export declare const DEFAULT_RISK_FREE_RATE = 0.02;
11
+ /**
12
+ * Provenance describing where a risk-free rate value came from.
13
+ *
14
+ * - `"live"`: Just fetched successfully from the Treasury Fiscal Data API.
15
+ * - `"cached"`: Returned from the in-process cache. May be from an earlier
16
+ * successful fetch (the common case) OR from a stale cache that
17
+ * survived a failed refresh attempt — callers that want to
18
+ * distinguish these cases should compare `fetchedAt` against
19
+ * {@link RISK_FREE_RATE_TTL_MS}.
20
+ * - `"default"`: The Treasury fetch failed AND no usable cached value was
21
+ * available, so {@link DEFAULT_RISK_FREE_RATE} was returned.
22
+ * Performance metrics computed against a `"default"` rate are
23
+ * using a fictional 2% baseline and should be flagged in
24
+ * downstream reporting.
25
+ *
26
+ * DE-029: previously the function returned only the numeric rate, so a fall
27
+ * back to the 2% default propagated through Sharpe/alpha/Sortino computations
28
+ * indistinguishable from a live observation. The provenance field closes that
29
+ * loop.
30
+ */
31
+ export type RiskFreeRateSource = "live" | "cached" | "default";
32
+ /**
33
+ * Result shape returned by the provenance-aware accessors.
34
+ *
35
+ * @see RiskFreeRateSource
36
+ */
37
+ export interface RiskFreeRateResult {
38
+ /** Annualized decimal rate (e.g. 0.0452 for 4.52%). */
39
+ rate: number;
40
+ /** Where the rate value came from. See {@link RiskFreeRateSource}. */
41
+ source: RiskFreeRateSource;
42
+ /**
43
+ * Wall-clock time the rate was last sourced. For `"live"` this is the
44
+ * moment the fetch resolved. For `"cached"` this is the original fetch
45
+ * time. For `"default"` this is the time the fallback was selected.
46
+ */
47
+ fetchedAt: Date;
48
+ }
49
+ /**
50
+ * Cache TTL for the risk-free rate: 24 hours. Treasury yields update daily
51
+ * (auction + close), so refreshing more aggressively provides no useful signal
52
+ * and risks rate-limiting the public endpoint.
53
+ */
54
+ export declare const RISK_FREE_RATE_TTL_MS: number;
55
+ /**
56
+ * Clears the cached risk-free rate. Exported for tests and for callers that
57
+ * want to force a re-fetch (e.g., at the start of a backtest run with a
58
+ * different asOf date).
59
+ */
60
+ export declare function resetRiskFreeRateCache(): void;
61
+ /**
62
+ * Explicitly sets the cached risk-free rate. Useful for deterministic tests,
63
+ * backtests (where rf should be pinned to the asOf date), and environments
64
+ * where an upstream service already provides the rate.
65
+ *
66
+ * @param rate - Annualized decimal rate (e.g. 0.0452 for 4.52%).
67
+ */
68
+ export declare function setRiskFreeRate(rate: number): void;
69
+ /**
70
+ * Provenance-aware variant of {@link getRiskFreeRate} that returns the rate
71
+ * AND tells the caller where it came from. Use this in any code path that
72
+ * publishes performance metrics (Sharpe, alpha, Sortino) so downstream
73
+ * reports can flag computations made against a fictional fallback rate.
74
+ *
75
+ * Behavior is identical to {@link getRiskFreeRate} for the cache and
76
+ * deduplication semantics; only the return shape differs:
77
+ *
78
+ * - Fresh cache hit: `{ source: "cached", fetchedAt: <original fetch time> }`
79
+ * - Cold or stale cache + successful fetch: `{ source: "live", fetchedAt: <now> }`
80
+ * - Cold or stale cache + failed fetch but cached value present:
81
+ * `{ source: "cached", fetchedAt: <original fetch time> }` — the stale
82
+ * value is reused so existing alpha calculations keep working through a
83
+ * transient outage. The provenance still says `cached`, not `live`.
84
+ * - Cold cache + failed fetch + no cached value:
85
+ * `{ source: "default", fetchedAt: <now> }` — the 2% fallback is used. This
86
+ * is the case downstream reports MUST flag, because Sharpe / alpha computed
87
+ * against a 2% floor that was never observed in market data is a fiction.
88
+ *
89
+ * DE-029: closes the silent-failure loop where a first-fetch network failure
90
+ * propagated `DEFAULT_RISK_FREE_RATE` indistinguishable from a live
91
+ * observation.
92
+ *
93
+ * @returns The annualized risk-free rate plus its provenance.
94
+ */
95
+ export declare function getRiskFreeRateWithProvenance(): Promise<RiskFreeRateResult>;
96
+ /**
97
+ * Returns the current annualized risk-free rate (decimal, e.g. 0.0452 for
98
+ * 4.52%), fetching from the US Treasury Fiscal Data API and caching for 24h.
99
+ *
100
+ * Behavior:
101
+ * - If a fresh cached value exists (<24h old), returns it without a network
102
+ * round-trip.
103
+ * - If the cache is stale or empty, fetches the latest 13-week T-Bill rate,
104
+ * updates the cache, and returns it.
105
+ * - If the fetch fails, returns the last-known-good cached value (even if
106
+ * expired) or {@link DEFAULT_RISK_FREE_RATE} as a last resort, logging a
107
+ * warning in both cases.
108
+ * - Concurrent calls during a cold cache are deduplicated so only one network
109
+ * request is in flight at a time.
110
+ *
111
+ * For provenance-aware callers (performance reports, audit logging) prefer
112
+ * {@link getRiskFreeRateWithProvenance}, which returns both the rate AND
113
+ * whether it came from a live fetch, the cache, or the fallback default.
114
+ *
115
+ * @returns Annualized risk-free rate as a decimal.
116
+ */
117
+ export declare function getRiskFreeRate(): Promise<number>;
118
+ /**
119
+ * Synchronous accessor that returns the most recent cached risk-free rate
120
+ * without performing I/O. If the cache is stale, a background refresh is
121
+ * kicked off (fire-and-forget) so the next synchronous call sees a fresh
122
+ * value. Intended for hot paths (e.g., Sharpe/alpha calculation inside tight
123
+ * loops) where the existing function signature cannot be made async.
124
+ *
125
+ * Callers that can tolerate an async boundary should prefer
126
+ * {@link getRiskFreeRate}.
127
+ *
128
+ * @returns The cached annualized risk-free rate as a decimal, or
129
+ * {@link DEFAULT_RISK_FREE_RATE} if no value has been cached yet.
130
+ */
131
+ export declare function getCachedRiskFreeRateSync(): number;
132
+ /**
133
+ * Provenance-aware sibling of {@link getCachedRiskFreeRateSync}. Returns the
134
+ * cached rate plus a flag indicating whether a real value has been cached
135
+ * (`"cached"`) or whether the caller is being given the {@link DEFAULT_RISK_FREE_RATE}
136
+ * fallback (`"default"`).
137
+ *
138
+ * Use this in synchronous hot paths that nonetheless need to flag computations
139
+ * made against the fallback (e.g., real-time alpha streaming where async
140
+ * round-trips are not viable but downstream reports must still distinguish
141
+ * live from fictional rates).
142
+ *
143
+ * As with the original sync accessor, a stale cache triggers a fire-and-forget
144
+ * background refresh so the next synchronous call sees fresh data; the call
145
+ * itself remains synchronous and returns the last-known-good value.
146
+ *
147
+ * DE-029: closes the silent-failure loop where the synchronous fallback was
148
+ * indistinguishable from a real cache hit.
149
+ *
150
+ * @returns A {@link RiskFreeRateResult} carrying the rate and its provenance.
151
+ */
152
+ export declare function getCachedRiskFreeRateSyncWithProvenance(): RiskFreeRateResult;
153
+ //# sourceMappingURL=risk-free-rate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"risk-free-rate.d.ts","sourceRoot":"","sources":["../../src/risk-free-rate.ts"],"names":[],"mappings":"AAIA;;;;;;;;GAQG;AACH,eAAO,MAAM,sBAAsB,OAAO,CAAC;AAE3C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC;AAE/D;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC;IACb,sEAAsE;IACtE,MAAM,EAAE,kBAAkB,CAAC;IAC3B;;;;OAIG;IACH,SAAS,EAAE,IAAI,CAAC;CACjB;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,QAAsB,CAAC;AA6CzD;;;;GAIG;AACH,wBAAgB,sBAAsB,IAAI,IAAI,CAG7C;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAOlD;AA8CD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,6BAA6B,IAAI,OAAO,CAAC,kBAAkB,CAAC,CA2DjF;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,eAAe,IAAI,OAAO,CAAC,MAAM,CAAC,CAGvD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,yBAAyB,IAAI,MAAM,CAElD;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,uCAAuC,IAAI,kBAAkB,CAyB5E"}