@adaptic/utils 0.1.3 → 0.1.41

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
@@ -368,21 +368,21 @@ function validateAlphaVantageApiKey(apiKey) {
368
368
  async function validateAuth(auth) {
369
369
  if (auth.adapticAccountId) {
370
370
  const client = await getSharedApolloClient();
371
- const alpacaAccount = (await adaptic$1.alpacaAccount.get({
371
+ const brokerageAccount = (await adaptic$1.brokerageAccount.get({
372
372
  id: auth.adapticAccountId,
373
373
  }, client));
374
- if (!alpacaAccount || !alpacaAccount.APIKey || !alpacaAccount.APISecret) {
374
+ if (!brokerageAccount || !brokerageAccount.apiKey || !brokerageAccount.apiSecret) {
375
375
  throw new Error("Alpaca account not found or incomplete");
376
376
  }
377
377
  validateAlpacaCredentials({
378
- apiKey: alpacaAccount.APIKey,
379
- apiSecret: alpacaAccount.APISecret,
380
- isPaper: alpacaAccount.type === "PAPER",
378
+ apiKey: brokerageAccount.apiKey,
379
+ apiSecret: brokerageAccount.apiSecret,
380
+ isPaper: brokerageAccount.type === "PAPER",
381
381
  });
382
382
  return {
383
- APIKey: alpacaAccount.APIKey,
384
- APISecret: alpacaAccount.APISecret,
385
- type: alpacaAccount.type,
383
+ apiKey: brokerageAccount.apiKey,
384
+ apiSecret: brokerageAccount.apiSecret,
385
+ type: brokerageAccount.type,
386
386
  };
387
387
  }
388
388
  else if (auth.alpacaApiKey && auth.alpacaApiSecret) {
@@ -391,8 +391,8 @@ async function validateAuth(auth) {
391
391
  apiKey: auth.alpacaApiKey,
392
392
  apiSecret: auth.alpacaApiSecret});
393
393
  return {
394
- APIKey: auth.alpacaApiKey,
395
- APISecret: auth.alpacaApiSecret,
394
+ apiKey: auth.alpacaApiKey,
395
+ apiSecret: auth.alpacaApiSecret,
396
396
  type: accountType,
397
397
  };
398
398
  }
@@ -563,11 +563,11 @@ const ORDER_CHUNK_SIZE = 500;
563
563
  async function makeRequest(auth, params) {
564
564
  const { endpoint, method, body, queryString, apiBaseUrl } = params;
565
565
  try {
566
- const { APIKey, APISecret, type } = await validateAuth(auth);
566
+ const { apiKey, apiSecret, type } = await validateAuth(auth);
567
567
  const apiBaseUrlInner = apiBaseUrl
568
568
  ? apiBaseUrl
569
569
  : getTradingApiUrl(type);
570
- if (!APIKey || !APISecret) {
570
+ if (!apiKey || !apiSecret) {
571
571
  throw new Error("No valid Alpaca authentication found. Please provide either auth object or set ALPACA_API_KEY and ALPACA_API_SECRET environment variables.");
572
572
  }
573
573
  const url = `${apiBaseUrlInner}${endpoint}${queryString || ""}`;
@@ -578,8 +578,8 @@ async function makeRequest(auth, params) {
578
578
  const fetchOptions = {
579
579
  method,
580
580
  headers: {
581
- "APCA-API-KEY-ID": APIKey,
582
- "APCA-API-SECRET-KEY": APISecret,
581
+ "APCA-API-KEY-ID": apiKey,
582
+ "APCA-API-SECRET-KEY": apiSecret,
583
583
  },
584
584
  };
585
585
  // Only add Content-Type and body for non-GET/HEAD requests that have a body
@@ -623,13 +623,13 @@ async function makeRequest(auth, params) {
623
623
  */
624
624
  async function createOrder$1(auth, params) {
625
625
  try {
626
- const { APIKey, APISecret, type } = await validateAuth(auth);
626
+ const { apiKey, apiSecret, type } = await validateAuth(auth);
627
627
  const apiBaseUrl = getTradingApiUrl(type);
628
628
  const response = await fetch(`${apiBaseUrl}/v2/orders`, {
629
629
  method: "POST",
630
630
  headers: {
631
- "APCA-API-KEY-ID": APIKey,
632
- "APCA-API-SECRET-KEY": APISecret,
631
+ "APCA-API-KEY-ID": apiKey,
632
+ "APCA-API-SECRET-KEY": apiSecret,
633
633
  "Content-Type": "application/json",
634
634
  },
635
635
  body: JSON.stringify(params),
@@ -654,7 +654,7 @@ async function createOrder$1(auth, params) {
654
654
  */
655
655
  async function getOrders$1(auth, params = {}) {
656
656
  try {
657
- const { APIKey, APISecret, type } = await validateAuth(auth);
657
+ const { apiKey, apiSecret, type } = await validateAuth(auth);
658
658
  const apiBaseUrl = getTradingApiUrl(type);
659
659
  const allOrders = [];
660
660
  let currentUntil = params.until ? params.until : new Date().toISOString();
@@ -677,8 +677,8 @@ async function getOrders$1(auth, params = {}) {
677
677
  const response = await fetch(`${apiBaseUrl}/v2/orders?${queryParams}`, {
678
678
  method: "GET",
679
679
  headers: {
680
- "APCA-API-KEY-ID": APIKey,
681
- "APCA-API-SECRET-KEY": APISecret,
680
+ "APCA-API-KEY-ID": apiKey,
681
+ "APCA-API-SECRET-KEY": apiSecret,
682
682
  },
683
683
  signal: createTimeoutSignal(DEFAULT_TIMEOUTS.ALPACA_API),
684
684
  });
@@ -710,13 +710,13 @@ async function getOrders$1(auth, params = {}) {
710
710
  */
711
711
  async function cancelAllOrders$1(auth) {
712
712
  try {
713
- const { APIKey, APISecret, type } = await validateAuth(auth);
713
+ const { apiKey, apiSecret, type } = await validateAuth(auth);
714
714
  const apiBaseUrl = getTradingApiUrl(type);
715
715
  const response = await fetch(`${apiBaseUrl}/v2/orders`, {
716
716
  method: "DELETE",
717
717
  headers: {
718
- "APCA-API-KEY-ID": APIKey,
719
- "APCA-API-SECRET-KEY": APISecret,
718
+ "APCA-API-KEY-ID": apiKey,
719
+ "APCA-API-SECRET-KEY": apiSecret,
720
720
  },
721
721
  signal: createTimeoutSignal(DEFAULT_TIMEOUTS.ALPACA_API),
722
722
  });
@@ -740,7 +740,7 @@ async function cancelAllOrders$1(auth) {
740
740
  */
741
741
  async function getOrder$1(auth, orderId, nested) {
742
742
  try {
743
- const { APIKey, APISecret, type } = await validateAuth(auth);
743
+ const { apiKey, apiSecret, type } = await validateAuth(auth);
744
744
  const apiBaseUrl = getTradingApiUrl(type);
745
745
  const queryParams = new URLSearchParams();
746
746
  if (nested)
@@ -748,8 +748,8 @@ async function getOrder$1(auth, orderId, nested) {
748
748
  const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}?${queryParams}`, {
749
749
  method: "GET",
750
750
  headers: {
751
- "APCA-API-KEY-ID": APIKey,
752
- "APCA-API-SECRET-KEY": APISecret,
751
+ "APCA-API-KEY-ID": apiKey,
752
+ "APCA-API-SECRET-KEY": apiSecret,
753
753
  },
754
754
  signal: createTimeoutSignal(DEFAULT_TIMEOUTS.ALPACA_API),
755
755
  });
@@ -773,13 +773,13 @@ async function getOrder$1(auth, orderId, nested) {
773
773
  */
774
774
  async function replaceOrder$1(auth, orderId, params) {
775
775
  try {
776
- const { APIKey, APISecret, type } = await validateAuth(auth);
776
+ const { apiKey, apiSecret, type } = await validateAuth(auth);
777
777
  const apiBaseUrl = getTradingApiUrl(type);
778
778
  const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}`, {
779
779
  method: "PATCH",
780
780
  headers: {
781
- "APCA-API-KEY-ID": APIKey,
782
- "APCA-API-SECRET-KEY": APISecret,
781
+ "APCA-API-KEY-ID": apiKey,
782
+ "APCA-API-SECRET-KEY": apiSecret,
783
783
  "Content-Type": "application/json",
784
784
  accept: "application/json",
785
785
  },
@@ -805,13 +805,13 @@ async function replaceOrder$1(auth, orderId, params) {
805
805
  */
806
806
  async function cancelOrder$1(auth, orderId) {
807
807
  try {
808
- const { APIKey, APISecret, type } = await validateAuth(auth);
808
+ const { apiKey, apiSecret, type } = await validateAuth(auth);
809
809
  const apiBaseUrl = getTradingApiUrl(type);
810
810
  const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}`, {
811
811
  method: "DELETE",
812
812
  headers: {
813
- "APCA-API-KEY-ID": APIKey,
814
- "APCA-API-SECRET-KEY": APISecret,
813
+ "APCA-API-KEY-ID": apiKey,
814
+ "APCA-API-SECRET-KEY": apiSecret,
815
815
  },
816
816
  signal: createTimeoutSignal(DEFAULT_TIMEOUTS.ALPACA_API),
817
817
  });
@@ -1393,14 +1393,14 @@ async function fetchNews$1(symbols, params) {
1393
1393
  }
1394
1394
  else if (mergedParams.auth.adapticAccountId) {
1395
1395
  const client = await getSharedApolloClient();
1396
- const alpacaAccount = (await adaptic$1.alpacaAccount.get({
1396
+ const brokerageAccount = (await adaptic$1.brokerageAccount.get({
1397
1397
  id: mergedParams.auth.adapticAccountId,
1398
1398
  }, client));
1399
- if (!alpacaAccount || !alpacaAccount.APIKey || !alpacaAccount.APISecret) {
1399
+ if (!brokerageAccount || !brokerageAccount.apiKey || !brokerageAccount.apiSecret) {
1400
1400
  throw new Error("Alpaca account not found or incomplete");
1401
1401
  }
1402
- APIKey = alpacaAccount.APIKey;
1403
- APISecret = alpacaAccount.APISecret;
1402
+ APIKey = brokerageAccount.apiKey;
1403
+ APISecret = brokerageAccount.apiSecret;
1404
1404
  }
1405
1405
  }
1406
1406
  else {
@@ -1493,14 +1493,14 @@ async function fetchNews$1(symbols, params) {
1493
1493
  */
1494
1494
  async function fetchAllPositions(auth) {
1495
1495
  try {
1496
- const { APIKey, APISecret, type } = await validateAuth(auth);
1496
+ const { apiKey, apiSecret, type } = await validateAuth(auth);
1497
1497
  const apiBaseUrl = getTradingApiUrl(type);
1498
1498
  const apiUrl = `${apiBaseUrl}/v2/positions`;
1499
1499
  const response = await fetch(apiUrl, {
1500
1500
  method: "GET",
1501
1501
  headers: {
1502
- "APCA-API-KEY-ID": APIKey,
1503
- "APCA-API-SECRET-KEY": APISecret,
1502
+ "APCA-API-KEY-ID": apiKey,
1503
+ "APCA-API-SECRET-KEY": apiSecret,
1504
1504
  "Content-Type": "application/json",
1505
1505
  },
1506
1506
  signal: createTimeoutSignal(DEFAULT_TIMEOUTS.ALPACA_API),
@@ -1524,13 +1524,13 @@ async function fetchAllPositions(auth) {
1524
1524
  */
1525
1525
  async function fetchPosition(auth, symbolOrAssetId) {
1526
1526
  try {
1527
- const { APIKey, APISecret, type } = await validateAuth(auth);
1527
+ const { apiKey, apiSecret, type } = await validateAuth(auth);
1528
1528
  const apiBaseUrl = getTradingApiUrl(type);
1529
1529
  const response = await fetch(`${apiBaseUrl}/v2/positions/${symbolOrAssetId}`, {
1530
1530
  method: "GET",
1531
1531
  headers: {
1532
- "APCA-API-KEY-ID": APIKey,
1533
- "APCA-API-SECRET-KEY": APISecret,
1532
+ "APCA-API-KEY-ID": apiKey,
1533
+ "APCA-API-SECRET-KEY": apiSecret,
1534
1534
  "Content-Type": "application/json",
1535
1535
  },
1536
1536
  signal: createTimeoutSignal(DEFAULT_TIMEOUTS.ALPACA_API),
@@ -1564,7 +1564,7 @@ async function fetchPosition(auth, symbolOrAssetId) {
1564
1564
  */
1565
1565
  async function closePosition$1(auth, symbolOrAssetId, params) {
1566
1566
  try {
1567
- const { APIKey, APISecret, type } = await validateAuth(auth);
1567
+ const { apiKey, apiSecret, type } = await validateAuth(auth);
1568
1568
  const apiBaseUrl = getTradingApiUrl(type);
1569
1569
  const useLimitOrder = params?.useLimitOrder ?? false;
1570
1570
  const cancelOrdersFlag = params?.cancelOrders ?? true;
@@ -1647,8 +1647,8 @@ async function closePosition$1(auth, symbolOrAssetId, params) {
1647
1647
  const response = await fetch(url, {
1648
1648
  method: "DELETE",
1649
1649
  headers: {
1650
- "APCA-API-KEY-ID": APIKey,
1651
- "APCA-API-SECRET-KEY": APISecret,
1650
+ "APCA-API-KEY-ID": apiKey,
1651
+ "APCA-API-SECRET-KEY": apiSecret,
1652
1652
  },
1653
1653
  });
1654
1654
  if (!response.ok) {
@@ -1839,20 +1839,20 @@ async function closeAllPositionsAfterHours$1(auth, params = { cancel_orders: tru
1839
1839
  * @param props - The properties for fetching account details
1840
1840
  * @returns The account details
1841
1841
  */
1842
- async function fetchAccountDetails({ accountId, client, alpacaAccount, auth, }) {
1843
- let alpacaAccountObj = alpacaAccount ? alpacaAccount : null;
1844
- if (!alpacaAccountObj && auth) {
1842
+ async function fetchAccountDetails({ accountId, client, brokerageAccount, auth, }) {
1843
+ let brokerageAccountObj = brokerageAccount ? brokerageAccount : null;
1844
+ if (!brokerageAccountObj && auth) {
1845
1845
  const validatedAuth = await validateAuth(auth);
1846
- alpacaAccountObj = {
1847
- APIKey: validatedAuth.APIKey,
1848
- APISecret: validatedAuth.APISecret,
1846
+ brokerageAccountObj = {
1847
+ apiKey: validatedAuth.apiKey,
1848
+ apiSecret: validatedAuth.apiSecret,
1849
1849
  type: validatedAuth.type,
1850
1850
  };
1851
1851
  }
1852
- if (!alpacaAccountObj) {
1852
+ if (!brokerageAccountObj) {
1853
1853
  try {
1854
1854
  const apolloClient = client || (await getSharedApolloClient());
1855
- alpacaAccountObj = (await adaptic$1.alpacaAccount.get({
1855
+ brokerageAccountObj = (await adaptic$1.brokerageAccount.get({
1856
1856
  id: accountId,
1857
1857
  }, apolloClient));
1858
1858
  }
@@ -1861,19 +1861,19 @@ async function fetchAccountDetails({ accountId, client, alpacaAccount, auth, })
1861
1861
  throw error;
1862
1862
  }
1863
1863
  }
1864
- if (!alpacaAccountObj ||
1865
- !alpacaAccountObj.APIKey ||
1866
- !alpacaAccountObj.APISecret) {
1864
+ if (!brokerageAccountObj ||
1865
+ !brokerageAccountObj.apiKey ||
1866
+ !brokerageAccountObj.apiSecret) {
1867
1867
  throw new Error("[fetchAccountDetails] Alpaca account not found or incomplete");
1868
1868
  }
1869
- const { APIKey, APISecret, type } = alpacaAccountObj;
1869
+ const { apiKey, apiSecret, type } = brokerageAccountObj;
1870
1870
  const apiUrl = `${getTradingApiUrl(type)}/account`;
1871
1871
  try {
1872
1872
  const response = await fetch(apiUrl, {
1873
1873
  method: "GET",
1874
1874
  headers: {
1875
- "APCA-API-KEY-ID": APIKey,
1876
- "APCA-API-SECRET-KEY": APISecret,
1875
+ "APCA-API-KEY-ID": apiKey,
1876
+ "APCA-API-SECRET-KEY": apiSecret,
1877
1877
  "Content-Type": "application/json",
1878
1878
  },
1879
1879
  signal: createTimeoutSignal(DEFAULT_TIMEOUTS.ALPACA_API),
@@ -1894,12 +1894,12 @@ async function fetchAccountDetails({ accountId, client, alpacaAccount, auth, })
1894
1894
  * @param props - The properties for fetching portfolio history
1895
1895
  * @returns The portfolio history
1896
1896
  */
1897
- async function fetchPortfolioHistory({ params, accountId, client, alpacaAccount, }) {
1898
- let alpacaAccountObj = alpacaAccount ? alpacaAccount : null;
1899
- if (!alpacaAccountObj) {
1897
+ async function fetchPortfolioHistory({ params, accountId, client, brokerageAccount, }) {
1898
+ let brokerageAccountObj = brokerageAccount ? brokerageAccount : null;
1899
+ if (!brokerageAccountObj) {
1900
1900
  try {
1901
1901
  const apolloClient = client || (await getSharedApolloClient());
1902
- alpacaAccountObj = (await adaptic$1.alpacaAccount.get({
1902
+ brokerageAccountObj = (await adaptic$1.brokerageAccount.get({
1903
1903
  id: accountId,
1904
1904
  }, apolloClient));
1905
1905
  }
@@ -1908,12 +1908,12 @@ async function fetchPortfolioHistory({ params, accountId, client, alpacaAccount,
1908
1908
  throw error;
1909
1909
  }
1910
1910
  }
1911
- if (!alpacaAccountObj ||
1912
- !alpacaAccountObj.APIKey ||
1913
- !alpacaAccountObj.APISecret) {
1911
+ if (!brokerageAccountObj ||
1912
+ !brokerageAccountObj.apiKey ||
1913
+ !brokerageAccountObj.apiSecret) {
1914
1914
  throw new Error("[fetchPortfolioHistory] Alpaca account not found or incomplete");
1915
1915
  }
1916
- const { APIKey, APISecret, type } = alpacaAccountObj;
1916
+ const { apiKey, apiSecret, type } = brokerageAccountObj;
1917
1917
  const apiBaseUrl = getTradingApiUrl(type);
1918
1918
  const apiUrl = `${apiBaseUrl}/v2/account/portfolio/history`;
1919
1919
  const { start, end, period } = params;
@@ -1939,8 +1939,8 @@ async function fetchPortfolioHistory({ params, accountId, client, alpacaAccount,
1939
1939
  const response = await fetch(fullUrl, {
1940
1940
  method: "GET",
1941
1941
  headers: {
1942
- "APCA-API-KEY-ID": APIKey,
1943
- "APCA-API-SECRET-KEY": APISecret,
1942
+ "APCA-API-KEY-ID": apiKey,
1943
+ "APCA-API-SECRET-KEY": apiSecret,
1944
1944
  "Content-Type": "application/json",
1945
1945
  },
1946
1946
  signal: createTimeoutSignal(DEFAULT_TIMEOUTS.ALPACA_API),
@@ -1967,31 +1967,31 @@ async function getConfiguration(account) {
1967
1967
  if (!account) {
1968
1968
  throw new Error(`Account is missing.`);
1969
1969
  }
1970
- const { APIKey, APISecret } = account;
1971
- if (!APIKey || !APISecret) {
1972
- throw new Error("User APIKey or APISecret is missing.");
1970
+ const { apiKey, apiSecret } = account;
1971
+ if (!apiKey || !apiSecret) {
1972
+ throw new Error("Account apiKey or apiSecret is missing.");
1973
1973
  }
1974
1974
  const apiUrl = getTradingApiUrl(account.type);
1975
1975
  const client = await getSharedApolloClient();
1976
- const [alpacaResponse, freshAlpacaAccount] = await Promise.all([
1976
+ const [alpacaResponse, freshBrokerageAccount] = await Promise.all([
1977
1977
  fetch(`${apiUrl}/account/configurations`, {
1978
1978
  method: "GET",
1979
1979
  headers: {
1980
- "APCA-API-KEY-ID": APIKey,
1981
- "APCA-API-SECRET-KEY": APISecret,
1980
+ "APCA-API-KEY-ID": apiKey,
1981
+ "APCA-API-SECRET-KEY": apiSecret,
1982
1982
  accept: "application/json",
1983
1983
  },
1984
1984
  }),
1985
- adaptic$1.alpacaAccount.get({ id: account.id }, client),
1985
+ adaptic$1.brokerageAccount.get({ id: account.id }, client),
1986
1986
  ]);
1987
1987
  if (!alpacaResponse.ok) {
1988
1988
  throw new Error(`Failed to fetch account configuration: ${alpacaResponse.statusText}`);
1989
1989
  }
1990
- if (!freshAlpacaAccount) {
1990
+ if (!freshBrokerageAccount) {
1991
1991
  throw new Error("Failed to get Alpaca Account from @adaptic/backend-legacy.");
1992
1992
  }
1993
1993
  const dataFromAlpaca = (await alpacaResponse.json());
1994
- const accountWithAllocation = freshAlpacaAccount;
1994
+ const accountWithAllocation = freshBrokerageAccount;
1995
1995
  const allocationData = accountWithAllocation.allocation || {
1996
1996
  stocks: 70,
1997
1997
  options: 0,
@@ -2002,26 +2002,26 @@ async function getConfiguration(account) {
2002
2002
  };
2003
2003
  const combinedConfig = {
2004
2004
  ...dataFromAlpaca,
2005
- marketOpen: freshAlpacaAccount.marketOpen,
2006
- realTime: freshAlpacaAccount.realTime,
2007
- tradeAllocationPct: freshAlpacaAccount.tradeAllocationPct,
2008
- minPercentageChange: freshAlpacaAccount.minPercentageChange,
2009
- volumeThreshold: freshAlpacaAccount.volumeThreshold,
2010
- cryptoTradingEnabled: freshAlpacaAccount.cryptoTradingEnabled ?? false,
2011
- cryptoTradingPairs: freshAlpacaAccount.cryptoTradingPairs ?? [],
2012
- cryptoTradeAllocationPct: freshAlpacaAccount.cryptoTradeAllocationPct ?? 5.0,
2005
+ marketOpen: freshBrokerageAccount.marketOpen,
2006
+ realTime: freshBrokerageAccount.realTime,
2007
+ tradeAllocationPct: freshBrokerageAccount.tradeAllocationPct,
2008
+ minPercentageChange: freshBrokerageAccount.minPercentageChange,
2009
+ volumeThreshold: freshBrokerageAccount.volumeThreshold,
2010
+ cryptoTradingEnabled: freshBrokerageAccount.cryptoTradingEnabled ?? false,
2011
+ cryptoTradingPairs: freshBrokerageAccount.cryptoTradingPairs ?? [],
2012
+ cryptoTradeAllocationPct: freshBrokerageAccount.cryptoTradeAllocationPct ?? 5.0,
2013
2013
  autoAllocation: accountWithAllocation.autoAllocation ?? false,
2014
2014
  allocation: allocationData,
2015
- enablePortfolioTrailingStop: freshAlpacaAccount.enablePortfolioTrailingStop,
2016
- portfolioTrailPercent: freshAlpacaAccount.portfolioTrailPercent,
2017
- portfolioProfitThresholdPercent: freshAlpacaAccount.portfolioProfitThresholdPercent,
2018
- reducedPortfolioTrailPercent: freshAlpacaAccount.reducedPortfolioTrailPercent,
2019
- defaultTrailingStopPercentage100: freshAlpacaAccount.defaultTrailingStopPercentage100 ?? 4.0,
2020
- firstTrailReductionThreshold100: freshAlpacaAccount.firstTrailReductionThreshold100 ?? 2.0,
2021
- secondTrailReductionThreshold100: freshAlpacaAccount.secondTrailReductionThreshold100 ?? 5.0,
2022
- firstReducedTrailPercentage100: freshAlpacaAccount.firstReducedTrailPercentage100 ?? 1.0,
2023
- secondReducedTrailPercentage100: freshAlpacaAccount.secondReducedTrailPercentage100 ?? 0.5,
2024
- minimumPriceChangePercent100: freshAlpacaAccount.minimumPriceChangePercent100 ?? 0.5,
2015
+ enablePortfolioTrailingStop: freshBrokerageAccount.enablePortfolioTrailingStop,
2016
+ portfolioTrailPercent: freshBrokerageAccount.portfolioTrailPercent,
2017
+ portfolioProfitThresholdPercent: freshBrokerageAccount.portfolioProfitThresholdPercent,
2018
+ reducedPortfolioTrailPercent: freshBrokerageAccount.reducedPortfolioTrailPercent,
2019
+ defaultTrailingStopPercentage100: freshBrokerageAccount.defaultTrailingStopPercentage100 ?? 4.0,
2020
+ firstTrailReductionThreshold100: freshBrokerageAccount.firstTrailReductionThreshold100 ?? 2.0,
2021
+ secondTrailReductionThreshold100: freshBrokerageAccount.secondTrailReductionThreshold100 ?? 5.0,
2022
+ firstReducedTrailPercentage100: freshBrokerageAccount.firstReducedTrailPercentage100 ?? 1.0,
2023
+ secondReducedTrailPercentage100: freshBrokerageAccount.secondReducedTrailPercentage100 ?? 0.5,
2024
+ minimumPriceChangePercent100: freshBrokerageAccount.minimumPriceChangePercent100 ?? 0.5,
2025
2025
  };
2026
2026
  return combinedConfig;
2027
2027
  }
@@ -2042,9 +2042,9 @@ async function updateConfiguration(user, account, updatedConfig) {
2042
2042
  if (!account) {
2043
2043
  throw new Error(`Account is missing.`);
2044
2044
  }
2045
- const { APIKey, APISecret } = account;
2046
- if (!APIKey || !APISecret) {
2047
- throw new Error("User APIKey or APISecret is missing.");
2045
+ const { apiKey, apiSecret } = account;
2046
+ if (!apiKey || !apiSecret) {
2047
+ throw new Error("Account apiKey or apiSecret is missing.");
2048
2048
  }
2049
2049
  const apiUrl = getTradingApiUrl(account.type);
2050
2050
  // Prepare the config object for Alpaca by removing DB-only fields
@@ -2072,8 +2072,8 @@ async function updateConfiguration(user, account, updatedConfig) {
2072
2072
  const alpacaUpdatePromise = fetch(`${apiUrl}/account/configurations`, {
2073
2073
  method: "PATCH",
2074
2074
  headers: {
2075
- "APCA-API-KEY-ID": APIKey,
2076
- "APCA-API-SECRET-KEY": APISecret,
2075
+ "APCA-API-KEY-ID": apiKey,
2076
+ "APCA-API-SECRET-KEY": apiSecret,
2077
2077
  "Content-Type": "application/json",
2078
2078
  accept: "application/json",
2079
2079
  },
@@ -2094,10 +2094,10 @@ async function updateConfiguration(user, account, updatedConfig) {
2094
2094
  if (account.allocation) {
2095
2095
  allocUpdatePromise = adaptic$1.allocation.update({
2096
2096
  id: account.allocation.id,
2097
- alpacaAccount: {
2097
+ brokerageAccount: {
2098
2098
  id: account.id,
2099
2099
  },
2100
- alpacaAccountId: account.id,
2100
+ brokerageAccountId: account.id,
2101
2101
  stocks: updatedConfig.allocation.stocks ?? 0,
2102
2102
  options: updatedConfig.allocation.options ?? 0,
2103
2103
  futures: updatedConfig.allocation.futures ?? 0,
@@ -2114,14 +2114,14 @@ async function updateConfiguration(user, account, updatedConfig) {
2114
2114
  etfs: updatedConfig.allocation.etfs ?? 0,
2115
2115
  forex: updatedConfig.allocation.forex ?? 0,
2116
2116
  crypto: updatedConfig.allocation.crypto ?? 0,
2117
- alpacaAccount: {
2117
+ brokerageAccount: {
2118
2118
  id: account.id,
2119
2119
  },
2120
- alpacaAccountId: account.id,
2120
+ brokerageAccountId: account.id,
2121
2121
  }, client);
2122
2122
  }
2123
2123
  }
2124
- const adapticUpdatePromise = adaptic$1.alpacaAccount.update({
2124
+ const adapticUpdatePromise = adaptic$1.brokerageAccount.update({
2125
2125
  id: account.id,
2126
2126
  user: {
2127
2127
  id: user.id,
@@ -2148,7 +2148,7 @@ async function updateConfiguration(user, account, updatedConfig) {
2148
2148
  secondReducedTrailPercentage100: updatedConfig.secondReducedTrailPercentage100 ?? 0,
2149
2149
  minimumPriceChangePercent100: updatedConfig.minimumPriceChangePercent100 ?? 0,
2150
2150
  }, client);
2151
- const [alpacaResponse, updatedAlpacaAccount, updatedAllocation] = await Promise.all([
2151
+ const [alpacaResponse, updatedBrokerageAccount, updatedAllocation] = await Promise.all([
2152
2152
  alpacaUpdatePromise,
2153
2153
  adapticUpdatePromise,
2154
2154
  allocUpdatePromise,
@@ -2168,10 +2168,10 @@ async function updateConfiguration(user, account, updatedConfig) {
2168
2168
  throw new Error(`Failed to update account config at Alpaca: ${alpacaResponse.statusText}`);
2169
2169
  }
2170
2170
  const alpacaData = (await alpacaResponse.json());
2171
- if (!updatedAlpacaAccount) {
2171
+ if (!updatedBrokerageAccount) {
2172
2172
  throw new Error("Failed to update Alpaca Account in @adaptic/backend-legacy.");
2173
2173
  }
2174
- const updatedAccountWithAllocation = updatedAlpacaAccount;
2174
+ const updatedAccountWithAllocation = updatedBrokerageAccount;
2175
2175
  const selectedAllocation = (updatedConfig.allocation ||
2176
2176
  updatedAllocation ||
2177
2177
  updatedAccountWithAllocation.allocation);
@@ -2181,26 +2181,26 @@ async function updateConfiguration(user, account, updatedConfig) {
2181
2181
  getLogger().info("Final allocation:", selectedAllocation);
2182
2182
  const finalConfig = {
2183
2183
  ...alpacaData,
2184
- marketOpen: updatedAlpacaAccount.marketOpen,
2185
- realTime: updatedAlpacaAccount.realTime,
2186
- tradeAllocationPct: updatedAlpacaAccount.tradeAllocationPct,
2187
- minPercentageChange: updatedAlpacaAccount.minPercentageChange,
2188
- volumeThreshold: updatedAlpacaAccount.volumeThreshold,
2189
- cryptoTradingEnabled: updatedAlpacaAccount.cryptoTradingEnabled,
2190
- cryptoTradingPairs: updatedAlpacaAccount.cryptoTradingPairs,
2191
- cryptoTradeAllocationPct: updatedAlpacaAccount.cryptoTradeAllocationPct,
2184
+ marketOpen: updatedBrokerageAccount.marketOpen,
2185
+ realTime: updatedBrokerageAccount.realTime,
2186
+ tradeAllocationPct: updatedBrokerageAccount.tradeAllocationPct,
2187
+ minPercentageChange: updatedBrokerageAccount.minPercentageChange,
2188
+ volumeThreshold: updatedBrokerageAccount.volumeThreshold,
2189
+ cryptoTradingEnabled: updatedBrokerageAccount.cryptoTradingEnabled,
2190
+ cryptoTradingPairs: updatedBrokerageAccount.cryptoTradingPairs,
2191
+ cryptoTradeAllocationPct: updatedBrokerageAccount.cryptoTradeAllocationPct,
2192
2192
  autoAllocation: updatedAccountWithAllocation.autoAllocation,
2193
2193
  allocation: selectedAllocation,
2194
- enablePortfolioTrailingStop: updatedAlpacaAccount.enablePortfolioTrailingStop,
2195
- portfolioTrailPercent: updatedAlpacaAccount.portfolioTrailPercent,
2196
- portfolioProfitThresholdPercent: updatedAlpacaAccount.portfolioProfitThresholdPercent,
2197
- reducedPortfolioTrailPercent: updatedAlpacaAccount.reducedPortfolioTrailPercent,
2198
- defaultTrailingStopPercentage100: updatedAlpacaAccount.defaultTrailingStopPercentage100,
2199
- firstTrailReductionThreshold100: updatedAlpacaAccount.firstTrailReductionThreshold100,
2200
- secondTrailReductionThreshold100: updatedAlpacaAccount.secondTrailReductionThreshold100,
2201
- firstReducedTrailPercentage100: updatedAlpacaAccount.firstReducedTrailPercentage100,
2202
- secondReducedTrailPercentage100: updatedAlpacaAccount.secondReducedTrailPercentage100,
2203
- minimumPriceChangePercent100: updatedAlpacaAccount.minimumPriceChangePercent100,
2194
+ enablePortfolioTrailingStop: updatedBrokerageAccount.enablePortfolioTrailingStop,
2195
+ portfolioTrailPercent: updatedBrokerageAccount.portfolioTrailPercent,
2196
+ portfolioProfitThresholdPercent: updatedBrokerageAccount.portfolioProfitThresholdPercent,
2197
+ reducedPortfolioTrailPercent: updatedBrokerageAccount.reducedPortfolioTrailPercent,
2198
+ defaultTrailingStopPercentage100: updatedBrokerageAccount.defaultTrailingStopPercentage100,
2199
+ firstTrailReductionThreshold100: updatedBrokerageAccount.firstTrailReductionThreshold100,
2200
+ secondTrailReductionThreshold100: updatedBrokerageAccount.secondTrailReductionThreshold100,
2201
+ firstReducedTrailPercentage100: updatedBrokerageAccount.firstReducedTrailPercentage100,
2202
+ secondReducedTrailPercentage100: updatedBrokerageAccount.secondReducedTrailPercentage100,
2203
+ minimumPriceChangePercent100: updatedBrokerageAccount.minimumPriceChangePercent100,
2204
2204
  };
2205
2205
  return finalConfig;
2206
2206
  }
@@ -2218,15 +2218,15 @@ async function updateConfiguration(user, account, updatedConfig) {
2218
2218
  */
2219
2219
  async function getAsset(auth, symbolOrAssetId) {
2220
2220
  try {
2221
- const { APIKey, APISecret, type } = await validateAuth(auth);
2221
+ const { apiKey, apiSecret, type } = await validateAuth(auth);
2222
2222
  const apiBaseUrl = getTradingApiUrl(type);
2223
2223
  // Use encodeURIComponent to handle special characters in symbols (e.g., BTC/USDT)
2224
2224
  const encodedSymbolOrAssetId = encodeURIComponent(symbolOrAssetId);
2225
2225
  const response = await fetch(`${apiBaseUrl}/v2/assets/${encodedSymbolOrAssetId}`, {
2226
2226
  method: "GET",
2227
2227
  headers: {
2228
- "APCA-API-KEY-ID": APIKey,
2229
- "APCA-API-SECRET-KEY": APISecret,
2228
+ "APCA-API-KEY-ID": apiKey,
2229
+ "APCA-API-SECRET-KEY": apiSecret,
2230
2230
  "Content-Type": "application/json",
2231
2231
  },
2232
2232
  signal: createTimeoutSignal(DEFAULT_TIMEOUTS.ALPACA_API),
@@ -3283,24 +3283,24 @@ async function calculateTotalReturnYTD(portfolioHistory) {
3283
3283
  * Calculates the expense ratio for a given Alpaca account.
3284
3284
  * @param accountId - The ID of the Alpaca account.
3285
3285
  * @param client - The Apollo client instance.
3286
- * @param alpacaAccount - The Alpaca account object.
3286
+ * @param brokerageAccount - The Alpaca account object.
3287
3287
  * @returns A promise that resolves to a string representing the expense ratio in percentage format.
3288
3288
  */
3289
- async function calculateExpenseRatio$1({ accountId, client, alpacaAccount, }) {
3290
- if (!accountId && !alpacaAccount && !client) {
3289
+ async function calculateExpenseRatio$1({ accountId, client, brokerageAccount, }) {
3290
+ if (!accountId && !brokerageAccount && !client) {
3291
3291
  getLogger().warn("Missing account ID or client to calculate expense ratio.");
3292
3292
  return "N/A";
3293
3293
  }
3294
- let alpacaAccountId = accountId || (alpacaAccount && alpacaAccount.id) || "";
3294
+ let brokerageAccountId = accountId || (brokerageAccount && brokerageAccount.id) || "";
3295
3295
  let accountDetails;
3296
- if (!alpacaAccountId) {
3296
+ if (!brokerageAccountId) {
3297
3297
  getLogger().warn("Invalid account ID.");
3298
3298
  return "N/A";
3299
3299
  }
3300
- if (alpacaAccount) {
3300
+ if (brokerageAccount) {
3301
3301
  // Use Alpaca account object to get accountDetails
3302
3302
  accountDetails = (await fetchAccountDetails({
3303
- alpacaAccount: alpacaAccount,
3303
+ brokerageAccount: brokerageAccount,
3304
3304
  }));
3305
3305
  if (!accountDetails) {
3306
3306
  getLogger().warn("Failed to fetch account details inside calculateExpenseRatio.");
@@ -3339,24 +3339,24 @@ async function getPortfolioExpensesFromYourSystem(accountId) {
3339
3339
  * Calculates the liquidity ratio for a given Alpaca account.
3340
3340
  * @param accountId - The ID of the Alpaca account.
3341
3341
  * @param client - The Apollo client instance.
3342
- * @param alpacaAccount - The Alpaca account object.
3342
+ * @param brokerageAccount - The Alpaca account object.
3343
3343
  * @returns A promise that resolves to a string representing the liquidity ratio in the format "1:ratio".
3344
3344
  */
3345
- async function calculateLiquidityRatio({ accountId, client, alpacaAccount, }) {
3346
- if (!accountId && !alpacaAccount && !client) {
3345
+ async function calculateLiquidityRatio({ accountId, client, brokerageAccount, }) {
3346
+ if (!accountId && !brokerageAccount && !client) {
3347
3347
  getLogger().warn("Missing account ID or client to calculateLiquidityRatio.");
3348
3348
  return "N/A";
3349
3349
  }
3350
- let alpacaAccountId = accountId || (alpacaAccount && alpacaAccount.id) || "";
3350
+ let brokerageAccountId = accountId || (brokerageAccount && brokerageAccount.id) || "";
3351
3351
  let accountDetails;
3352
- if (!alpacaAccountId) {
3352
+ if (!brokerageAccountId) {
3353
3353
  getLogger().warn("Invalid account ID.");
3354
3354
  return "N/A";
3355
3355
  }
3356
- if (alpacaAccount) {
3356
+ if (brokerageAccount) {
3357
3357
  // Use Alpaca account object to get accountDetails
3358
3358
  accountDetails = (await fetchAccountDetails({
3359
- alpacaAccount: alpacaAccount,
3359
+ brokerageAccount: brokerageAccount,
3360
3360
  }));
3361
3361
  if (!accountDetails) {
3362
3362
  getLogger().warn("Failed to fetch account details inside calculateLiquidityRatio.");
@@ -3984,11 +3984,11 @@ async function calculateInformationRatio$1(portfolioHistory, benchmarkBars) {
3984
3984
  * @param params - The parameters for fetching performance metrics.
3985
3985
  * @param client - The Apollo client instance.
3986
3986
  * @param accountId - The ID of the Alpaca account.
3987
- * @param alpacaAccount - The Alpaca account object.
3987
+ * @param brokerageAccount - The Alpaca account object.
3988
3988
  * @returns A promise that resolves to an object containing various performance metrics.
3989
3989
  * @throws Will throw an error if required parameters are missing or if fetching fails.
3990
3990
  */
3991
- async function fetchPerformanceMetrics({ params, client, accountId, alpacaAccount, }) {
3991
+ async function fetchPerformanceMetrics({ params, client, accountId, brokerageAccount, }) {
3992
3992
  // Default response for error cases
3993
3993
  const defaultMetrics = {
3994
3994
  totalReturnYTD: "N/A",
@@ -4011,12 +4011,12 @@ async function fetchPerformanceMetrics({ params, client, accountId, alpacaAccoun
4011
4011
  throw new Error("Missing required timeframe or period parameters");
4012
4012
  }
4013
4013
  // Obtain Alpaca account
4014
- let alpacaAccountObj = alpacaAccount ? alpacaAccount : null;
4015
- if (!alpacaAccountObj && accountId) {
4014
+ let brokerageAccountObj = brokerageAccount ? brokerageAccount : null;
4015
+ if (!brokerageAccountObj && accountId) {
4016
4016
  try {
4017
4017
  // Use provided client or get the shared client
4018
4018
  const apolloClient = client || (await getSharedApolloClient());
4019
- alpacaAccountObj = (await adaptic$1.alpacaAccount.get({
4019
+ brokerageAccountObj = (await adaptic$1.brokerageAccount.get({
4020
4020
  id: accountId,
4021
4021
  }, apolloClient));
4022
4022
  }
@@ -4026,9 +4026,9 @@ async function fetchPerformanceMetrics({ params, client, accountId, alpacaAccoun
4026
4026
  }
4027
4027
  }
4028
4028
  // Validate Alpaca account
4029
- if (!alpacaAccountObj ||
4030
- !alpacaAccountObj.APIKey ||
4031
- !alpacaAccountObj.APISecret) {
4029
+ if (!brokerageAccountObj ||
4030
+ !brokerageAccountObj.apiKey ||
4031
+ !brokerageAccountObj.apiSecret) {
4032
4032
  throw new Error("Alpaca account not found or credentials missing");
4033
4033
  }
4034
4034
  // Fetch portfolio history with structured error handling
@@ -4036,7 +4036,7 @@ async function fetchPerformanceMetrics({ params, client, accountId, alpacaAccoun
4036
4036
  try {
4037
4037
  portfolioHistory = await fetchPortfolioHistory({
4038
4038
  params: params,
4039
- alpacaAccount: alpacaAccountObj,
4039
+ brokerageAccount: brokerageAccountObj,
4040
4040
  });
4041
4041
  }
4042
4042
  catch (error) {
@@ -4086,10 +4086,10 @@ async function fetchPerformanceMetrics({ params, client, accountId, alpacaAccoun
4086
4086
  calculateInformationRatio$1(portfolioHistory, benchmarkBars),
4087
4087
  calculateRiskAdjustedReturn$1(portfolioHistory),
4088
4088
  calculateLiquidityRatio({
4089
- alpacaAccount: alpacaAccountObj,
4089
+ brokerageAccount: brokerageAccountObj,
4090
4090
  }),
4091
4091
  calculateExpenseRatio$1({
4092
- alpacaAccount: alpacaAccountObj,
4092
+ brokerageAccount: brokerageAccountObj,
4093
4093
  }),
4094
4094
  getDividendYield(),
4095
4095
  calculateMaxDrawdown$1(portfolioHistory.equity),
@@ -4309,15 +4309,15 @@ const timeDiffString = (milliseconds) => {
4309
4309
  };
4310
4310
 
4311
4311
  // price-utils.ts
4312
- const calculateFees = async (action, trade, alpacaAccount) => {
4312
+ const calculateFees = async (action, trade, brokerageAccount) => {
4313
4313
  let fee = 0;
4314
4314
  const alpacaOrderId = action.alpacaOrderId;
4315
4315
  if (!alpacaOrderId)
4316
4316
  return fee;
4317
4317
  const order = await getOrder$1({
4318
- adapticAccountId: trade.alpacaAccountId,
4319
- alpacaApiKey: alpacaAccount.APIKey,
4320
- alpacaApiSecret: alpacaAccount.APISecret,
4318
+ adapticAccountId: trade.brokerageAccountId,
4319
+ alpacaApiKey: brokerageAccount.apiKey,
4320
+ alpacaApiSecret: brokerageAccount.apiSecret,
4321
4321
  }, alpacaOrderId);
4322
4322
  if (!order)
4323
4323
  return fee;
@@ -4355,13 +4355,13 @@ const calculateFees = async (action, trade, alpacaAccount) => {
4355
4355
  };
4356
4356
  const computeTotalFees = async (trade) => {
4357
4357
  let totalFees = 0;
4358
- // fetch alpaca account details using adaptic.alpacaAccount.get({id: trade.alpacaAccountId})
4359
- const alpacaAccount = (await adaptic$1.alpacaAccount.get({
4360
- id: trade.alpacaAccountId,
4358
+ // fetch alpaca account details using adaptic.brokerageAccount.get({id: trade.brokerageAccountId})
4359
+ const brokerageAccount = (await adaptic$1.brokerageAccount.get({
4360
+ id: trade.brokerageAccountId,
4361
4361
  }));
4362
- if (!alpacaAccount)
4362
+ if (!brokerageAccount)
4363
4363
  return totalFees;
4364
- const feePromises = trade?.actions?.map((action) => calculateFees(action, trade, alpacaAccount));
4364
+ const feePromises = trade?.actions?.map((action) => calculateFees(action, trade, brokerageAccount));
4365
4365
  const fees = await Promise.all(feePromises || []);
4366
4366
  totalFees = fees.reduce((acc, fee) => acc + fee, 0);
4367
4367
  return totalFees;
@@ -6108,7 +6108,7 @@ async function fetchBars(params) {
6108
6108
  */
6109
6109
  async function fetchNews(params, auth) {
6110
6110
  const { symbol, start = new Date(Date.now() - 24 * 60 * 60 * 1000), sort = "desc", includeContent = false, limit = 1000, } = params;
6111
- if (!auth.APIKey || !auth.APISecret) {
6111
+ if (!auth.alpacaApiKey || !auth.alpacaApiSecret) {
6112
6112
  throw new Error("Alpaca API key and secret are required");
6113
6113
  }
6114
6114
  if (!symbol) {
@@ -6176,7 +6176,7 @@ async function fetchNews(params, auth) {
6176
6176
  */
6177
6177
  async function fetchLatestTrades(params, auth) {
6178
6178
  const { symbols, loc = "us" } = params;
6179
- if (!auth.APIKey || !auth.APISecret) {
6179
+ if (!auth.alpacaApiKey || !auth.alpacaApiSecret) {
6180
6180
  throw new Error("Alpaca API key and secret are required");
6181
6181
  }
6182
6182
  if (!symbols || symbols.length === 0) {
@@ -6192,8 +6192,8 @@ async function fetchLatestTrades(params, auth) {
6192
6192
  return withRetry(async () => {
6193
6193
  const response = await fetch(url, {
6194
6194
  headers: {
6195
- "APCA-API-KEY-ID": auth.APIKey,
6196
- "APCA-API-SECRET-KEY": auth.APISecret,
6195
+ "APCA-API-KEY-ID": auth.alpacaApiKey,
6196
+ "APCA-API-SECRET-KEY": auth.alpacaApiSecret,
6197
6197
  },
6198
6198
  signal: createTimeoutSignal(DEFAULT_TIMEOUTS.ALPACA_API),
6199
6199
  });
@@ -6219,7 +6219,7 @@ async function fetchLatestTrades(params, auth) {
6219
6219
  */
6220
6220
  async function fetchLatestQuotes(params, auth) {
6221
6221
  const { symbols, loc = "us" } = params;
6222
- if (!auth.APIKey || !auth.APISecret) {
6222
+ if (!auth.alpacaApiKey || !auth.alpacaApiSecret) {
6223
6223
  throw new Error("Alpaca API key and secret are required");
6224
6224
  }
6225
6225
  if (!symbols || symbols.length === 0) {
@@ -6235,8 +6235,8 @@ async function fetchLatestQuotes(params, auth) {
6235
6235
  return withRetry(async () => {
6236
6236
  const response = await fetch(url, {
6237
6237
  headers: {
6238
- "APCA-API-KEY-ID": auth.APIKey,
6239
- "APCA-API-SECRET-KEY": auth.APISecret,
6238
+ "APCA-API-KEY-ID": auth.alpacaApiKey,
6239
+ "APCA-API-SECRET-KEY": auth.alpacaApiSecret,
6240
6240
  },
6241
6241
  signal: createTimeoutSignal(DEFAULT_TIMEOUTS.ALPACA_API),
6242
6242
  });