@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.mjs CHANGED
@@ -212,7 +212,7 @@ const isAuthConfigured = () => {
212
212
  * Returns a shared Apollo client instance with connection pooling.
213
213
  * This should be used for all @adaptic/backend-legacy operations.
214
214
  *
215
- * @returns {Promise<ApolloClientType>} The shared Apollo client instance.
215
+ * @returns {Promise<ApolloClientInstance>} The shared Apollo client instance.
216
216
  */
217
217
  const getSharedApolloClient = async () => {
218
218
  if (!apolloClientInstance) {
@@ -622,7 +622,7 @@ async function createOrder$1(auth, params) {
622
622
  try {
623
623
  const { APIKey, APISecret, type } = await validateAuth(auth);
624
624
  const apiBaseUrl = getTradingApiUrl(type);
625
- const response = await fetch(`${apiBaseUrl}/v2/orders`, {
625
+ const response = await fetch(`${apiBaseUrl}/orders`, {
626
626
  method: "POST",
627
627
  headers: {
628
628
  "APCA-API-KEY-ID": APIKey,
@@ -671,7 +671,7 @@ async function getOrders$1(auth, params = {}) {
671
671
  queryParams.append("symbols", params.symbols.join(","));
672
672
  if (params.side)
673
673
  queryParams.append("side", params.side);
674
- const response = await fetch(`${apiBaseUrl}/v2/orders?${queryParams}`, {
674
+ const response = await fetch(`${apiBaseUrl}/orders?${queryParams}`, {
675
675
  method: "GET",
676
676
  headers: {
677
677
  "APCA-API-KEY-ID": APIKey,
@@ -709,7 +709,7 @@ async function cancelAllOrders$1(auth) {
709
709
  try {
710
710
  const { APIKey, APISecret, type } = await validateAuth(auth);
711
711
  const apiBaseUrl = getTradingApiUrl(type);
712
- const response = await fetch(`${apiBaseUrl}/v2/orders`, {
712
+ const response = await fetch(`${apiBaseUrl}/orders`, {
713
713
  method: "DELETE",
714
714
  headers: {
715
715
  "APCA-API-KEY-ID": APIKey,
@@ -742,7 +742,7 @@ async function getOrder$1(auth, orderId, nested) {
742
742
  const queryParams = new URLSearchParams();
743
743
  if (nested)
744
744
  queryParams.append("nested", "true");
745
- const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}?${queryParams}`, {
745
+ const response = await fetch(`${apiBaseUrl}/orders/${orderId}?${queryParams}`, {
746
746
  method: "GET",
747
747
  headers: {
748
748
  "APCA-API-KEY-ID": APIKey,
@@ -772,7 +772,7 @@ async function replaceOrder$1(auth, orderId, params) {
772
772
  try {
773
773
  const { APIKey, APISecret, type } = await validateAuth(auth);
774
774
  const apiBaseUrl = getTradingApiUrl(type);
775
- const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}`, {
775
+ const response = await fetch(`${apiBaseUrl}/orders/${orderId}`, {
776
776
  method: "PATCH",
777
777
  headers: {
778
778
  "APCA-API-KEY-ID": APIKey,
@@ -804,7 +804,7 @@ async function cancelOrder$1(auth, orderId) {
804
804
  try {
805
805
  const { APIKey, APISecret, type } = await validateAuth(auth);
806
806
  const apiBaseUrl = getTradingApiUrl(type);
807
- const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}`, {
807
+ const response = await fetch(`${apiBaseUrl}/orders/${orderId}`, {
808
808
  method: "DELETE",
809
809
  headers: {
810
810
  "APCA-API-KEY-ID": APIKey,
@@ -863,7 +863,7 @@ async function createLimitOrder(auth, params = {
863
863
  body.client_order_id = client_order_id;
864
864
  }
865
865
  return makeRequest(auth, {
866
- endpoint: "/v2/orders",
866
+ endpoint: "/orders",
867
867
  method: "POST",
868
868
  body,
869
869
  });
@@ -1492,7 +1492,7 @@ async function fetchAllPositions(auth) {
1492
1492
  try {
1493
1493
  const { APIKey, APISecret, type } = await validateAuth(auth);
1494
1494
  const apiBaseUrl = getTradingApiUrl(type);
1495
- const apiUrl = `${apiBaseUrl}/v2/positions`;
1495
+ const apiUrl = `${apiBaseUrl}/positions`;
1496
1496
  const response = await fetch(apiUrl, {
1497
1497
  method: "GET",
1498
1498
  headers: {
@@ -1523,7 +1523,7 @@ async function fetchPosition(auth, symbolOrAssetId) {
1523
1523
  try {
1524
1524
  const { APIKey, APISecret, type } = await validateAuth(auth);
1525
1525
  const apiBaseUrl = getTradingApiUrl(type);
1526
- const response = await fetch(`${apiBaseUrl}/v2/positions/${symbolOrAssetId}`, {
1526
+ const response = await fetch(`${apiBaseUrl}/positions/${symbolOrAssetId}`, {
1527
1527
  method: "GET",
1528
1528
  headers: {
1529
1529
  "APCA-API-KEY-ID": APIKey,
@@ -1640,7 +1640,7 @@ async function closePosition$1(auth, symbolOrAssetId, params) {
1640
1640
  queryParams.append("percentage", params.percentage.toString());
1641
1641
  }
1642
1642
  const queryString = queryParams.toString();
1643
- const url = `${apiBaseUrl}/v2/positions/${encodeURIComponent(symbolOrAssetId)}${queryString ? `?${queryString}` : ""}`;
1643
+ const url = `${apiBaseUrl}/positions/${encodeURIComponent(symbolOrAssetId)}${queryString ? `?${queryString}` : ""}`;
1644
1644
  const response = await fetch(url, {
1645
1645
  method: "DELETE",
1646
1646
  headers: {
@@ -1746,7 +1746,7 @@ async function closeAllPositions$1(auth, params = { cancel_orders: true, useLimi
1746
1746
  }
1747
1747
  else {
1748
1748
  const response = await makeRequest(auth, {
1749
- endpoint: "/v2/positions",
1749
+ endpoint: "/positions",
1750
1750
  method: "DELETE",
1751
1751
  queryString: cancel_orders ? "?cancel_orders=true" : "",
1752
1752
  });
@@ -1912,7 +1912,7 @@ async function fetchPortfolioHistory({ params, accountId, client, alpacaAccount,
1912
1912
  }
1913
1913
  const { APIKey, APISecret, type } = alpacaAccountObj;
1914
1914
  const apiBaseUrl = getTradingApiUrl(type);
1915
- const apiUrl = `${apiBaseUrl}/v2/account/portfolio/history`;
1915
+ const apiUrl = `${apiBaseUrl}/account/portfolio/history`;
1916
1916
  const { start, end, period } = params;
1917
1917
  // Validate date formats
1918
1918
  if (start) {
@@ -2219,7 +2219,7 @@ async function getAsset(auth, symbolOrAssetId) {
2219
2219
  const apiBaseUrl = getTradingApiUrl(type);
2220
2220
  // Use encodeURIComponent to handle special characters in symbols (e.g., BTC/USDT)
2221
2221
  const encodedSymbolOrAssetId = encodeURIComponent(symbolOrAssetId);
2222
- const response = await fetch(`${apiBaseUrl}/v2/assets/${encodedSymbolOrAssetId}`, {
2222
+ const response = await fetch(`${apiBaseUrl}/assets/${encodedSymbolOrAssetId}`, {
2223
2223
  method: "GET",
2224
2224
  headers: {
2225
2225
  "APCA-API-KEY-ID": APIKey,
@@ -5163,6 +5163,11 @@ function validateConcurrency(concurrency) {
5163
5163
  /**********************************************************************************
5164
5164
  * Polygon.io calls
5165
5165
  **********************************************************************************/
5166
+ /**
5167
+ * Set of Polygon API response statuses that indicate valid, usable data.
5168
+ * "OK" = real-time data, "DELAYED" = delayed data (still valid, e.g. free-tier plans).
5169
+ */
5170
+ const POLYGON_VALID_STATUSES = new Set(["OK", "DELAYED"]);
5166
5171
  // Constants from environment variables
5167
5172
  const POLYGON_API_KEY = process.env.POLYGON_API_KEY;
5168
5173
  // Define concurrency limits per API
@@ -5277,7 +5282,7 @@ const fetchLastTrade = async (symbol, options) => {
5277
5282
  try {
5278
5283
  const response = await fetchWithRetry(`${baseUrl}?${params.toString()}`, {}, 3, 1000);
5279
5284
  const data = await response.json();
5280
- if (data.status !== "OK" || !data.results) {
5285
+ if (!POLYGON_VALID_STATUSES.has(data.status) || !data.results) {
5281
5286
  throw new Error(`Polygon.io API error: ${data.status || "No results"} ${data.error || ""}`);
5282
5287
  }
5283
5288
  const { p: price, s: vol, t: timestamp } = data.results;
@@ -5349,9 +5354,12 @@ const fetchPrices = async (params, options) => {
5349
5354
  //getLogger().info(`Debug: Fetching ${nextUrl}`);
5350
5355
  const response = await fetchWithRetry(nextUrl, {}, 3, 1000);
5351
5356
  const data = await response.json();
5352
- if (data.status !== "OK") {
5357
+ if (!POLYGON_VALID_STATUSES.has(data.status)) {
5353
5358
  throw new Error(`Polygon.io API responded with status: ${data.status}`);
5354
5359
  }
5360
+ if (data.status === "DELAYED") {
5361
+ getLogger().warn(`Polygon.io returned DELAYED data for ${params.ticker} — using delayed results`, { ticker: params.ticker, source: "PolygonAPI.fetchPrices" });
5362
+ }
5355
5363
  if (data.results) {
5356
5364
  allResults = [...allResults, ...data.results];
5357
5365
  }
@@ -5463,7 +5471,7 @@ const fetchGroupedDaily = async (date, options) => {
5463
5471
  try {
5464
5472
  const response = await fetchWithRetry(`${baseUrl}?${params.toString()}`, {}, 3, 1000);
5465
5473
  const data = await response.json();
5466
- if (data.status !== "OK") {
5474
+ if (!POLYGON_VALID_STATUSES.has(data.status)) {
5467
5475
  throw new Error(`Polygon.io API responded with status: ${data.status}`);
5468
5476
  }
5469
5477
  return {
@@ -5554,7 +5562,7 @@ symbol, date = new Date(), options) => {
5554
5562
  return polygonLimit(async () => {
5555
5563
  const response = await fetchWithRetry(`${baseUrl}?${params.toString()}`, {}, 3, 1000);
5556
5564
  const data = await response.json();
5557
- if (data.status !== "OK") {
5565
+ if (!POLYGON_VALID_STATUSES.has(data.status)) {
5558
5566
  throw new Error(`Failed to fetch daily open/close data for ${symbol}: ${data.status}`);
5559
5567
  }
5560
5568
  return data;
@@ -53803,7 +53811,6 @@ async function getPortfolioHistory(client, params) {
53803
53811
  log$i(`Fetching portfolio history with period: ${params.period || "default"}, timeframe: ${params.timeframe || "default"}`);
53804
53812
  try {
53805
53813
  const sdk = client.getSDK();
53806
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
53807
53814
  const history = await sdk.getPortfolioHistory(params);
53808
53815
  log$i(`Portfolio history fetched successfully with ${history.equity?.length || 0} data points`);
53809
53816
  return history;
@@ -55543,7 +55550,6 @@ async function getOpenTrailingStops(client, symbol) {
55543
55550
  if (symbol) {
55544
55551
  queryParams.symbols = symbol.toUpperCase();
55545
55552
  }
55546
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
55547
55553
  const orders = (await sdk.getOrders(queryParams));
55548
55554
  // Filter to only trailing stop orders
55549
55555
  const trailingStops = orders.filter((order) => order.type === "trailing_stop");
@@ -55781,12 +55787,11 @@ async function createOCOOrder(client, params) {
55781
55787
  limit_price: roundPriceForAlpaca$2(takeProfit.limitPrice).toString(),
55782
55788
  stop_loss: {
55783
55789
  stop_price: roundPriceForAlpaca$2(stopLoss.stopPrice).toString(),
55790
+ ...(stopLoss.limitPrice !== undefined
55791
+ ? { limit_price: roundPriceForAlpaca$2(stopLoss.limitPrice).toString() }
55792
+ : {}),
55784
55793
  },
55785
55794
  };
55786
- // Add stop-limit price if provided
55787
- if (stopLoss.limitPrice !== undefined) {
55788
- orderRequest.stop_loss.limit_price = roundPriceForAlpaca$2(stopLoss.limitPrice).toString();
55789
- }
55790
55795
  log$f(`Submitting OCO order request: ${JSON.stringify(orderRequest)}`, {
55791
55796
  symbol,
55792
55797
  type: "debug",
@@ -56201,14 +56206,14 @@ async function createOTOOrder(client, params) {
56201
56206
  }
56202
56207
  else if (dependent.type === "trailing_stop") {
56203
56208
  // Trailing stop order
56204
- orderRequest.stop_loss = {};
56209
+ const trailingStop = {};
56205
56210
  if (dependent.trailPercent !== undefined) {
56206
- orderRequest.stop_loss.trail_percent =
56207
- dependent.trailPercent.toString();
56211
+ trailingStop.trail_percent = dependent.trailPercent.toString();
56208
56212
  }
56209
56213
  if (dependent.trailPrice !== undefined) {
56210
- orderRequest.stop_loss.trail_price = roundPriceForAlpaca$1(dependent.trailPrice).toString();
56214
+ trailingStop.trail_price = roundPriceForAlpaca$1(dependent.trailPrice).toString();
56211
56215
  }
56216
+ orderRequest.stop_loss = trailingStop;
56212
56217
  }
56213
56218
  log$e(`Submitting OTO order request: ${JSON.stringify(orderRequest)}`, {
56214
56219
  symbol,
@@ -56629,7 +56634,6 @@ async function getLatestQuote(client, symbol, feed) {
56629
56634
  const config = client.getConfig();
56630
56635
  const dataFeed = feed || config.dataFeed || "iex";
56631
56636
  // Use SDK's getLatestQuote method
56632
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
56633
56637
  const response = await sdk.getLatestQuote(normalizedSymbol, {
56634
56638
  feed: dataFeed,
56635
56639
  });
@@ -56687,7 +56691,6 @@ async function getLatestQuotes(client, symbols, feed) {
56687
56691
  const config = client.getConfig();
56688
56692
  const dataFeed = feed || config.dataFeed || "iex";
56689
56693
  // Use SDK's getLatestQuotes method
56690
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
56691
56694
  const response = await sdk.getLatestQuotes(normalizedSymbols, {
56692
56695
  feed: dataFeed,
56693
56696
  });
@@ -56943,7 +56946,6 @@ async function getLatestBars(client, symbols) {
56943
56946
  const sdk = client.getSDK();
56944
56947
  const config = client.getConfig();
56945
56948
  const dataFeed = config.dataFeed || "iex";
56946
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
56947
56949
  const response = await sdk.getLatestBars(normalizedSymbols, {
56948
56950
  feed: dataFeed,
56949
56951
  });
@@ -57234,7 +57236,6 @@ async function getLatestTrade(client, symbol, feed) {
57234
57236
  const config = client.getConfig();
57235
57237
  const dataFeed = feed || config.dataFeed || "iex";
57236
57238
  // Use SDK's getLatestTrade method
57237
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
57238
57239
  const response = await sdk.getLatestTrade(normalizedSymbol, {
57239
57240
  feed: dataFeed,
57240
57241
  });
@@ -57290,7 +57291,6 @@ async function getLatestTrades(client, symbols, feed) {
57290
57291
  const config = client.getConfig();
57291
57292
  const dataFeed = feed || config.dataFeed || "iex";
57292
57293
  // Use SDK's getLatestTrades method
57293
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
57294
57294
  const response = await sdk.getLatestTrades(normalizedSymbols, {
57295
57295
  feed: dataFeed,
57296
57296
  });
@@ -57405,7 +57405,6 @@ async function getCurrentPrice(client, symbol, feed) {
57405
57405
  const dataFeed = feed || config.dataFeed || "iex";
57406
57406
  // Try to get quote first for mid-point price
57407
57407
  try {
57408
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
57409
57408
  const quote = await sdk.getLatestQuote(normalizedSymbol, {
57410
57409
  feed: dataFeed,
57411
57410
  });
@@ -57840,7 +57839,6 @@ async function getNews(client, params = {}) {
57840
57839
  // The SDK returns a slightly different structure, so we map the fields
57841
57840
  const articles = response.map((article) => {
57842
57841
  // SDK returns properties in different format
57843
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
57844
57842
  const sdkArticle = article;
57845
57843
  // Normalize to our expected format
57846
57844
  const normalizedArticle = {
@@ -61506,7 +61504,6 @@ async function getOpenCryptoOrders(client, symbols) {
61506
61504
  ? symbols.map(normalizeCryptoSymbol$1).join(",")
61507
61505
  : undefined,
61508
61506
  };
61509
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
61510
61507
  const orders = (await sdk.getOrders(queryParams));
61511
61508
  // Filter to only crypto orders (asset_class === 'crypto')
61512
61509
  const cryptoOrders = orders.filter((order) => order.asset_class === "crypto");
@@ -61708,9 +61705,7 @@ async function getCryptoBars(client, params) {
61708
61705
  result.set(symbol, []);
61709
61706
  }
61710
61707
  // Use SDK's getCryptoBars method
61711
- // The SDK may return an async iterator or a Promise depending on the version;
61712
- // cast to any so TypeScript does not constrain the runtime duck-typing below.
61713
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
61708
+ // The SDK may return an async iterator or a Promise depending on the version
61714
61709
  const barsResponse = sdk.getCryptoBars(normalizedSymbols, options);
61715
61710
  // Handle both async iterator and direct response formats
61716
61711
  if (barsResponse &&
@@ -61731,8 +61726,8 @@ async function getCryptoBars(client, params) {
61731
61726
  result.set(symbol, existingBars);
61732
61727
  }
61733
61728
  }
61734
- else if (barsResponse && barsResponse.then) {
61735
- // Handle Promise response
61729
+ else if (barsResponse && "then" in barsResponse) {
61730
+ // Handle Promise response (SDK returns thenable in some versions)
61736
61731
  const response = await barsResponse;
61737
61732
  if (response && response.bars) {
61738
61733
  for (const [symbol, bars] of Object.entries(response.bars)) {
@@ -62046,9 +62041,7 @@ async function getCryptoTrades(client, symbol, start, end, limit) {
62046
62041
  options.limit = limit;
62047
62042
  }
62048
62043
  const trades = [];
62049
- // The SDK may return an async iterator or a Promise depending on the version;
62050
- // cast to any so TypeScript does not constrain the runtime duck-typing below.
62051
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
62044
+ // The SDK may return an async iterator or a Promise depending on the version
62052
62045
  const tradesResponse = sdk.getCryptoTrades(normalizedSymbol, options);
62053
62046
  // Handle both async iterator and direct response formats
62054
62047
  if (tradesResponse &&
@@ -62067,8 +62060,8 @@ async function getCryptoTrades(client, symbol, start, end, limit) {
62067
62060
  }
62068
62061
  }
62069
62062
  }
62070
- else if (tradesResponse && tradesResponse.then) {
62071
- // Handle Promise response
62063
+ else if (tradesResponse && "then" in tradesResponse) {
62064
+ // Handle Promise response (SDK returns thenable in some versions)
62072
62065
  const response = await tradesResponse;
62073
62066
  if (response && response.trades) {
62074
62067
  const tradeArray = response.trades;