@adaptic/utils 0.0.903 → 0.0.905

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 (30) hide show
  1. package/dist/index.cjs +39 -46
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.mjs +39 -46
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/types/adaptic.d.ts +4 -4
  6. package/dist/types/adaptic.d.ts.map +1 -1
  7. package/dist/types/alpaca/crypto/data.d.ts.map +1 -1
  8. package/dist/types/alpaca/crypto/orders.d.ts.map +1 -1
  9. package/dist/types/alpaca/index.d.ts.map +1 -1
  10. package/dist/types/alpaca/legacy/positions.d.ts.map +1 -1
  11. package/dist/types/alpaca/market-data/bars.d.ts.map +1 -1
  12. package/dist/types/alpaca/market-data/news.d.ts.map +1 -1
  13. package/dist/types/alpaca/market-data/quotes.d.ts.map +1 -1
  14. package/dist/types/alpaca/market-data/trades.d.ts.map +1 -1
  15. package/dist/types/alpaca/streams/crypto-stream.d.ts.map +1 -1
  16. package/dist/types/alpaca/streams/option-stream.d.ts.map +1 -1
  17. package/dist/types/alpaca/streams/stock-stream.d.ts.map +1 -1
  18. package/dist/types/alpaca/trading/account.d.ts.map +1 -1
  19. package/dist/types/alpaca/trading/oco-orders.d.ts.map +1 -1
  20. package/dist/types/alpaca/trading/order-utils.d.ts.map +1 -1
  21. package/dist/types/alpaca/trading/orders.d.ts.map +1 -1
  22. package/dist/types/alpaca/trading/oto-orders.d.ts.map +1 -1
  23. package/dist/types/alpaca/trading/trailing-stops.d.ts.map +1 -1
  24. package/dist/types/index.d.ts +2 -2
  25. package/dist/types/index.d.ts.map +1 -1
  26. package/dist/types/polygon.d.ts.map +1 -1
  27. package/dist/types/schemas/polygon-schemas.d.ts +6 -6
  28. package/dist/types/types/alpaca-types.d.ts +18 -1
  29. package/dist/types/types/alpaca-types.d.ts.map +1 -1
  30. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -214,7 +214,7 @@ const isAuthConfigured = () => {
214
214
  * Returns a shared Apollo client instance with connection pooling.
215
215
  * This should be used for all @adaptic/backend-legacy operations.
216
216
  *
217
- * @returns {Promise<ApolloClientType>} The shared Apollo client instance.
217
+ * @returns {Promise<ApolloClientInstance>} The shared Apollo client instance.
218
218
  */
219
219
  const getSharedApolloClient = async () => {
220
220
  if (!apolloClientInstance) {
@@ -624,7 +624,7 @@ async function createOrder$1(auth, params) {
624
624
  try {
625
625
  const { APIKey, APISecret, type } = await validateAuth(auth);
626
626
  const apiBaseUrl = getTradingApiUrl(type);
627
- const response = await fetch(`${apiBaseUrl}/v2/orders`, {
627
+ const response = await fetch(`${apiBaseUrl}/orders`, {
628
628
  method: "POST",
629
629
  headers: {
630
630
  "APCA-API-KEY-ID": APIKey,
@@ -673,7 +673,7 @@ async function getOrders$1(auth, params = {}) {
673
673
  queryParams.append("symbols", params.symbols.join(","));
674
674
  if (params.side)
675
675
  queryParams.append("side", params.side);
676
- const response = await fetch(`${apiBaseUrl}/v2/orders?${queryParams}`, {
676
+ const response = await fetch(`${apiBaseUrl}/orders?${queryParams}`, {
677
677
  method: "GET",
678
678
  headers: {
679
679
  "APCA-API-KEY-ID": APIKey,
@@ -711,7 +711,7 @@ async function cancelAllOrders$1(auth) {
711
711
  try {
712
712
  const { APIKey, APISecret, type } = await validateAuth(auth);
713
713
  const apiBaseUrl = getTradingApiUrl(type);
714
- const response = await fetch(`${apiBaseUrl}/v2/orders`, {
714
+ const response = await fetch(`${apiBaseUrl}/orders`, {
715
715
  method: "DELETE",
716
716
  headers: {
717
717
  "APCA-API-KEY-ID": APIKey,
@@ -744,7 +744,7 @@ async function getOrder$1(auth, orderId, nested) {
744
744
  const queryParams = new URLSearchParams();
745
745
  if (nested)
746
746
  queryParams.append("nested", "true");
747
- const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}?${queryParams}`, {
747
+ const response = await fetch(`${apiBaseUrl}/orders/${orderId}?${queryParams}`, {
748
748
  method: "GET",
749
749
  headers: {
750
750
  "APCA-API-KEY-ID": APIKey,
@@ -774,7 +774,7 @@ async function replaceOrder$1(auth, orderId, params) {
774
774
  try {
775
775
  const { APIKey, APISecret, type } = await validateAuth(auth);
776
776
  const apiBaseUrl = getTradingApiUrl(type);
777
- const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}`, {
777
+ const response = await fetch(`${apiBaseUrl}/orders/${orderId}`, {
778
778
  method: "PATCH",
779
779
  headers: {
780
780
  "APCA-API-KEY-ID": APIKey,
@@ -806,7 +806,7 @@ async function cancelOrder$1(auth, orderId) {
806
806
  try {
807
807
  const { APIKey, APISecret, type } = await validateAuth(auth);
808
808
  const apiBaseUrl = getTradingApiUrl(type);
809
- const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}`, {
809
+ const response = await fetch(`${apiBaseUrl}/orders/${orderId}`, {
810
810
  method: "DELETE",
811
811
  headers: {
812
812
  "APCA-API-KEY-ID": APIKey,
@@ -865,7 +865,7 @@ async function createLimitOrder(auth, params = {
865
865
  body.client_order_id = client_order_id;
866
866
  }
867
867
  return makeRequest(auth, {
868
- endpoint: "/v2/orders",
868
+ endpoint: "/orders",
869
869
  method: "POST",
870
870
  body,
871
871
  });
@@ -1494,7 +1494,7 @@ async function fetchAllPositions(auth) {
1494
1494
  try {
1495
1495
  const { APIKey, APISecret, type } = await validateAuth(auth);
1496
1496
  const apiBaseUrl = getTradingApiUrl(type);
1497
- const apiUrl = `${apiBaseUrl}/v2/positions`;
1497
+ const apiUrl = `${apiBaseUrl}/positions`;
1498
1498
  const response = await fetch(apiUrl, {
1499
1499
  method: "GET",
1500
1500
  headers: {
@@ -1525,7 +1525,7 @@ async function fetchPosition(auth, symbolOrAssetId) {
1525
1525
  try {
1526
1526
  const { APIKey, APISecret, type } = await validateAuth(auth);
1527
1527
  const apiBaseUrl = getTradingApiUrl(type);
1528
- const response = await fetch(`${apiBaseUrl}/v2/positions/${symbolOrAssetId}`, {
1528
+ const response = await fetch(`${apiBaseUrl}/positions/${symbolOrAssetId}`, {
1529
1529
  method: "GET",
1530
1530
  headers: {
1531
1531
  "APCA-API-KEY-ID": APIKey,
@@ -1642,7 +1642,7 @@ async function closePosition$1(auth, symbolOrAssetId, params) {
1642
1642
  queryParams.append("percentage", params.percentage.toString());
1643
1643
  }
1644
1644
  const queryString = queryParams.toString();
1645
- const url = `${apiBaseUrl}/v2/positions/${encodeURIComponent(symbolOrAssetId)}${queryString ? `?${queryString}` : ""}`;
1645
+ const url = `${apiBaseUrl}/positions/${encodeURIComponent(symbolOrAssetId)}${queryString ? `?${queryString}` : ""}`;
1646
1646
  const response = await fetch(url, {
1647
1647
  method: "DELETE",
1648
1648
  headers: {
@@ -1748,7 +1748,7 @@ async function closeAllPositions$1(auth, params = { cancel_orders: true, useLimi
1748
1748
  }
1749
1749
  else {
1750
1750
  const response = await makeRequest(auth, {
1751
- endpoint: "/v2/positions",
1751
+ endpoint: "/positions",
1752
1752
  method: "DELETE",
1753
1753
  queryString: cancel_orders ? "?cancel_orders=true" : "",
1754
1754
  });
@@ -1914,7 +1914,7 @@ async function fetchPortfolioHistory({ params, accountId, client, alpacaAccount,
1914
1914
  }
1915
1915
  const { APIKey, APISecret, type } = alpacaAccountObj;
1916
1916
  const apiBaseUrl = getTradingApiUrl(type);
1917
- const apiUrl = `${apiBaseUrl}/v2/account/portfolio/history`;
1917
+ const apiUrl = `${apiBaseUrl}/account/portfolio/history`;
1918
1918
  const { start, end, period } = params;
1919
1919
  // Validate date formats
1920
1920
  if (start) {
@@ -2221,7 +2221,7 @@ async function getAsset(auth, symbolOrAssetId) {
2221
2221
  const apiBaseUrl = getTradingApiUrl(type);
2222
2222
  // Use encodeURIComponent to handle special characters in symbols (e.g., BTC/USDT)
2223
2223
  const encodedSymbolOrAssetId = encodeURIComponent(symbolOrAssetId);
2224
- const response = await fetch(`${apiBaseUrl}/v2/assets/${encodedSymbolOrAssetId}`, {
2224
+ const response = await fetch(`${apiBaseUrl}/assets/${encodedSymbolOrAssetId}`, {
2225
2225
  method: "GET",
2226
2226
  headers: {
2227
2227
  "APCA-API-KEY-ID": APIKey,
@@ -5165,6 +5165,11 @@ function validateConcurrency(concurrency) {
5165
5165
  /**********************************************************************************
5166
5166
  * Polygon.io calls
5167
5167
  **********************************************************************************/
5168
+ /**
5169
+ * Set of Polygon API response statuses that indicate valid, usable data.
5170
+ * "OK" = real-time data, "DELAYED" = delayed data (still valid, e.g. free-tier plans).
5171
+ */
5172
+ const POLYGON_VALID_STATUSES = new Set(["OK", "DELAYED"]);
5168
5173
  // Constants from environment variables
5169
5174
  const POLYGON_API_KEY = process.env.POLYGON_API_KEY;
5170
5175
  // Define concurrency limits per API
@@ -5279,7 +5284,7 @@ const fetchLastTrade = async (symbol, options) => {
5279
5284
  try {
5280
5285
  const response = await fetchWithRetry(`${baseUrl}?${params.toString()}`, {}, 3, 1000);
5281
5286
  const data = await response.json();
5282
- if (data.status !== "OK" || !data.results) {
5287
+ if (!POLYGON_VALID_STATUSES.has(data.status) || !data.results) {
5283
5288
  throw new Error(`Polygon.io API error: ${data.status || "No results"} ${data.error || ""}`);
5284
5289
  }
5285
5290
  const { p: price, s: vol, t: timestamp } = data.results;
@@ -5351,9 +5356,12 @@ const fetchPrices = async (params, options) => {
5351
5356
  //getLogger().info(`Debug: Fetching ${nextUrl}`);
5352
5357
  const response = await fetchWithRetry(nextUrl, {}, 3, 1000);
5353
5358
  const data = await response.json();
5354
- if (data.status !== "OK") {
5359
+ if (!POLYGON_VALID_STATUSES.has(data.status)) {
5355
5360
  throw new Error(`Polygon.io API responded with status: ${data.status}`);
5356
5361
  }
5362
+ if (data.status === "DELAYED") {
5363
+ getLogger().warn(`Polygon.io returned DELAYED data for ${params.ticker} — using delayed results`, { ticker: params.ticker, source: "PolygonAPI.fetchPrices" });
5364
+ }
5357
5365
  if (data.results) {
5358
5366
  allResults = [...allResults, ...data.results];
5359
5367
  }
@@ -5465,7 +5473,7 @@ const fetchGroupedDaily = async (date, options) => {
5465
5473
  try {
5466
5474
  const response = await fetchWithRetry(`${baseUrl}?${params.toString()}`, {}, 3, 1000);
5467
5475
  const data = await response.json();
5468
- if (data.status !== "OK") {
5476
+ if (!POLYGON_VALID_STATUSES.has(data.status)) {
5469
5477
  throw new Error(`Polygon.io API responded with status: ${data.status}`);
5470
5478
  }
5471
5479
  return {
@@ -5556,7 +5564,7 @@ symbol, date = new Date(), options) => {
5556
5564
  return polygonLimit(async () => {
5557
5565
  const response = await fetchWithRetry(`${baseUrl}?${params.toString()}`, {}, 3, 1000);
5558
5566
  const data = await response.json();
5559
- if (data.status !== "OK") {
5567
+ if (!POLYGON_VALID_STATUSES.has(data.status)) {
5560
5568
  throw new Error(`Failed to fetch daily open/close data for ${symbol}: ${data.status}`);
5561
5569
  }
5562
5570
  return data;
@@ -53805,7 +53813,6 @@ async function getPortfolioHistory(client, params) {
53805
53813
  log$i(`Fetching portfolio history with period: ${params.period || "default"}, timeframe: ${params.timeframe || "default"}`);
53806
53814
  try {
53807
53815
  const sdk = client.getSDK();
53808
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
53809
53816
  const history = await sdk.getPortfolioHistory(params);
53810
53817
  log$i(`Portfolio history fetched successfully with ${history.equity?.length || 0} data points`);
53811
53818
  return history;
@@ -55545,7 +55552,6 @@ async function getOpenTrailingStops(client, symbol) {
55545
55552
  if (symbol) {
55546
55553
  queryParams.symbols = symbol.toUpperCase();
55547
55554
  }
55548
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
55549
55555
  const orders = (await sdk.getOrders(queryParams));
55550
55556
  // Filter to only trailing stop orders
55551
55557
  const trailingStops = orders.filter((order) => order.type === "trailing_stop");
@@ -55783,12 +55789,11 @@ async function createOCOOrder(client, params) {
55783
55789
  limit_price: roundPriceForAlpaca$2(takeProfit.limitPrice).toString(),
55784
55790
  stop_loss: {
55785
55791
  stop_price: roundPriceForAlpaca$2(stopLoss.stopPrice).toString(),
55792
+ ...(stopLoss.limitPrice !== undefined
55793
+ ? { limit_price: roundPriceForAlpaca$2(stopLoss.limitPrice).toString() }
55794
+ : {}),
55786
55795
  },
55787
55796
  };
55788
- // Add stop-limit price if provided
55789
- if (stopLoss.limitPrice !== undefined) {
55790
- orderRequest.stop_loss.limit_price = roundPriceForAlpaca$2(stopLoss.limitPrice).toString();
55791
- }
55792
55797
  log$f(`Submitting OCO order request: ${JSON.stringify(orderRequest)}`, {
55793
55798
  symbol,
55794
55799
  type: "debug",
@@ -56203,14 +56208,14 @@ async function createOTOOrder(client, params) {
56203
56208
  }
56204
56209
  else if (dependent.type === "trailing_stop") {
56205
56210
  // Trailing stop order
56206
- orderRequest.stop_loss = {};
56211
+ const trailingStop = {};
56207
56212
  if (dependent.trailPercent !== undefined) {
56208
- orderRequest.stop_loss.trail_percent =
56209
- dependent.trailPercent.toString();
56213
+ trailingStop.trail_percent = dependent.trailPercent.toString();
56210
56214
  }
56211
56215
  if (dependent.trailPrice !== undefined) {
56212
- orderRequest.stop_loss.trail_price = roundPriceForAlpaca$1(dependent.trailPrice).toString();
56216
+ trailingStop.trail_price = roundPriceForAlpaca$1(dependent.trailPrice).toString();
56213
56217
  }
56218
+ orderRequest.stop_loss = trailingStop;
56214
56219
  }
56215
56220
  log$e(`Submitting OTO order request: ${JSON.stringify(orderRequest)}`, {
56216
56221
  symbol,
@@ -56631,7 +56636,6 @@ async function getLatestQuote(client, symbol, feed) {
56631
56636
  const config = client.getConfig();
56632
56637
  const dataFeed = feed || config.dataFeed || "iex";
56633
56638
  // Use SDK's getLatestQuote method
56634
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
56635
56639
  const response = await sdk.getLatestQuote(normalizedSymbol, {
56636
56640
  feed: dataFeed,
56637
56641
  });
@@ -56689,7 +56693,6 @@ async function getLatestQuotes(client, symbols, feed) {
56689
56693
  const config = client.getConfig();
56690
56694
  const dataFeed = feed || config.dataFeed || "iex";
56691
56695
  // Use SDK's getLatestQuotes method
56692
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
56693
56696
  const response = await sdk.getLatestQuotes(normalizedSymbols, {
56694
56697
  feed: dataFeed,
56695
56698
  });
@@ -56945,7 +56948,6 @@ async function getLatestBars(client, symbols) {
56945
56948
  const sdk = client.getSDK();
56946
56949
  const config = client.getConfig();
56947
56950
  const dataFeed = config.dataFeed || "iex";
56948
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
56949
56951
  const response = await sdk.getLatestBars(normalizedSymbols, {
56950
56952
  feed: dataFeed,
56951
56953
  });
@@ -57236,7 +57238,6 @@ async function getLatestTrade(client, symbol, feed) {
57236
57238
  const config = client.getConfig();
57237
57239
  const dataFeed = feed || config.dataFeed || "iex";
57238
57240
  // Use SDK's getLatestTrade method
57239
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
57240
57241
  const response = await sdk.getLatestTrade(normalizedSymbol, {
57241
57242
  feed: dataFeed,
57242
57243
  });
@@ -57292,7 +57293,6 @@ async function getLatestTrades(client, symbols, feed) {
57292
57293
  const config = client.getConfig();
57293
57294
  const dataFeed = feed || config.dataFeed || "iex";
57294
57295
  // Use SDK's getLatestTrades method
57295
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
57296
57296
  const response = await sdk.getLatestTrades(normalizedSymbols, {
57297
57297
  feed: dataFeed,
57298
57298
  });
@@ -57407,7 +57407,6 @@ async function getCurrentPrice(client, symbol, feed) {
57407
57407
  const dataFeed = feed || config.dataFeed || "iex";
57408
57408
  // Try to get quote first for mid-point price
57409
57409
  try {
57410
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
57411
57410
  const quote = await sdk.getLatestQuote(normalizedSymbol, {
57412
57411
  feed: dataFeed,
57413
57412
  });
@@ -57842,7 +57841,6 @@ async function getNews(client, params = {}) {
57842
57841
  // The SDK returns a slightly different structure, so we map the fields
57843
57842
  const articles = response.map((article) => {
57844
57843
  // SDK returns properties in different format
57845
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
57846
57844
  const sdkArticle = article;
57847
57845
  // Normalize to our expected format
57848
57846
  const normalizedArticle = {
@@ -61508,7 +61506,6 @@ async function getOpenCryptoOrders(client, symbols) {
61508
61506
  ? symbols.map(normalizeCryptoSymbol$1).join(",")
61509
61507
  : undefined,
61510
61508
  };
61511
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
61512
61509
  const orders = (await sdk.getOrders(queryParams));
61513
61510
  // Filter to only crypto orders (asset_class === 'crypto')
61514
61511
  const cryptoOrders = orders.filter((order) => order.asset_class === "crypto");
@@ -61710,9 +61707,7 @@ async function getCryptoBars(client, params) {
61710
61707
  result.set(symbol, []);
61711
61708
  }
61712
61709
  // Use SDK's getCryptoBars method
61713
- // The SDK may return an async iterator or a Promise depending on the version;
61714
- // cast to any so TypeScript does not constrain the runtime duck-typing below.
61715
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
61710
+ // The SDK may return an async iterator or a Promise depending on the version
61716
61711
  const barsResponse = sdk.getCryptoBars(normalizedSymbols, options);
61717
61712
  // Handle both async iterator and direct response formats
61718
61713
  if (barsResponse &&
@@ -61733,8 +61728,8 @@ async function getCryptoBars(client, params) {
61733
61728
  result.set(symbol, existingBars);
61734
61729
  }
61735
61730
  }
61736
- else if (barsResponse && barsResponse.then) {
61737
- // Handle Promise response
61731
+ else if (barsResponse && "then" in barsResponse) {
61732
+ // Handle Promise response (SDK returns thenable in some versions)
61738
61733
  const response = await barsResponse;
61739
61734
  if (response && response.bars) {
61740
61735
  for (const [symbol, bars] of Object.entries(response.bars)) {
@@ -62048,9 +62043,7 @@ async function getCryptoTrades(client, symbol, start, end, limit) {
62048
62043
  options.limit = limit;
62049
62044
  }
62050
62045
  const trades = [];
62051
- // The SDK may return an async iterator or a Promise depending on the version;
62052
- // cast to any so TypeScript does not constrain the runtime duck-typing below.
62053
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
62046
+ // The SDK may return an async iterator or a Promise depending on the version
62054
62047
  const tradesResponse = sdk.getCryptoTrades(normalizedSymbol, options);
62055
62048
  // Handle both async iterator and direct response formats
62056
62049
  if (tradesResponse &&
@@ -62069,8 +62062,8 @@ async function getCryptoTrades(client, symbol, start, end, limit) {
62069
62062
  }
62070
62063
  }
62071
62064
  }
62072
- else if (tradesResponse && tradesResponse.then) {
62073
- // Handle Promise response
62065
+ else if (tradesResponse && "then" in tradesResponse) {
62066
+ // Handle Promise response (SDK returns thenable in some versions)
62074
62067
  const response = await tradesResponse;
62075
62068
  if (response && response.trades) {
62076
62069
  const tradeArray = response.trades;