@adaptic/utils 0.0.1001 → 0.0.1002

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.cjs CHANGED
@@ -2359,6 +2359,23 @@ class NetworkError extends AdapticUtilsError {
2359
2359
  this.service = service;
2360
2360
  }
2361
2361
  }
2362
+ /**
2363
+ * Unsupported brokerage provider errors
2364
+ * Thrown when a broker operation is requested for a provider that has no
2365
+ * implemented integration (e.g. IBKR or COINBASE before their adapters land,
2366
+ * or an unrecognised provider string from an untyped caller).
2367
+ * Never retryable — the caller must route to a supported provider.
2368
+ */
2369
+ class UnsupportedBrokerError extends AdapticUtilsError {
2370
+ provider;
2371
+ constructor(
2372
+ /** The provider that was requested but is not supported. */
2373
+ provider, cause) {
2374
+ super(`Brokerage provider "${provider}" is not supported. Supported providers: ALPACA`, "UNSUPPORTED_BROKER", "broker", false, // Unsupported providers are never retryable
2375
+ cause);
2376
+ this.provider = provider;
2377
+ }
2378
+ }
2362
2379
  /**
2363
2380
  * Data parsing and format errors
2364
2381
  * Used when API responses cannot be parsed or are in unexpected format
@@ -5773,9 +5790,18 @@ class AlpacaTradingAPI {
5773
5790
  *
5774
5791
  * @param auth - The authentication details for Alpaca
5775
5792
  * @returns Validated authentication credentials
5793
+ * @throws UnsupportedBrokerError if `auth.provider` is set to a non-ALPACA provider
5776
5794
  * @throws Error if authentication details are missing or invalid
5777
5795
  */
5778
5796
  async function validateAuth(auth) {
5797
+ // Multi-broker guard (SP2): this seam only resolves Alpaca credentials.
5798
+ // `auth.provider` is typed as "ALPACA" on AlpacaAuth, but untyped callers
5799
+ // (or future BrokerAuth adapters) may pass other providers at runtime —
5800
+ // fail fast with a typed error instead of silently hitting Alpaca hosts.
5801
+ const requestedProvider = auth.provider;
5802
+ if (requestedProvider !== undefined && requestedProvider !== "ALPACA") {
5803
+ throw new UnsupportedBrokerError(requestedProvider);
5804
+ }
5779
5805
  const inlineKey = auth.alpacaApiKey && auth.alpacaApiKey.trim().length > 0
5780
5806
  ? auth.alpacaApiKey
5781
5807
  : undefined;
@@ -5797,26 +5823,54 @@ async function validateAuth(auth) {
5797
5823
  };
5798
5824
  }
5799
5825
  if (auth.adapticAccountId) {
5800
- const client = await getSharedApolloClient();
5801
- const alpacaAccount = (await adaptic$1.alpacaAccount.get({
5802
- id: auth.adapticAccountId,
5803
- }, client));
5804
- if (!alpacaAccount || !alpacaAccount.APIKey || !alpacaAccount.APISecret) {
5805
- throw new Error("Alpaca account not found or incomplete");
5806
- }
5807
- validateAlpacaCredentials({
5808
- apiKey: alpacaAccount.APIKey,
5809
- apiSecret: alpacaAccount.APISecret,
5810
- isPaper: alpacaAccount.type === "PAPER",
5811
- });
5812
- return {
5813
- APIKey: alpacaAccount.APIKey,
5814
- APISecret: alpacaAccount.APISecret,
5815
- type: alpacaAccount.type,
5816
- };
5826
+ return resolveBrokerCredentials(auth.adapticAccountId);
5817
5827
  }
5818
5828
  throw new Error("Either adapticAccountId or both alpacaApiKey and alpacaApiSecret must be provided");
5819
5829
  }
5830
+ /**
5831
+ * Resolves broker credentials for a backend brokerage-account id.
5832
+ *
5833
+ * This is the SINGLE backend-coupled credential lookup in this package —
5834
+ * every account-id-based credential resolution must flow through here so
5835
+ * that backend model changes touch exactly one function.
5836
+ *
5837
+ * SP2 transition note: today the id is an `AlpacaAccount.id` resolved via
5838
+ * `adaptic.alpacaAccount.get`. When backend-legacy publishes the
5839
+ * `BrokerageAccount` model (backfilled with `id = AlpacaAccount.id`, so the
5840
+ * id space is identical), the switch to `adaptic.brokerageAccount.get`
5841
+ * happens INSIDE this function only, following the sequencing rule in
5842
+ * CLAUDE.md ("Multi-Broker Sequencing Rule"): backend-legacy publishes →
5843
+ * utils bumps the dependency and switches this helper → utils publishes →
5844
+ * engine bumps its pin. Do not reference `brokerageAccount` anywhere in
5845
+ * this package before the pinned backend-legacy version exports it.
5846
+ *
5847
+ * The lookup is a no-cache GraphQL round trip to backend-legacy; callers
5848
+ * holding inline credentials should never reach it (see `validateAuth`
5849
+ * precedence).
5850
+ *
5851
+ * @param brokerageAccountId - Backend brokerage-account id (currently the AlpacaAccount id)
5852
+ * @returns Validated authentication credentials
5853
+ * @throws Error if the account is not found or its credentials are incomplete
5854
+ */
5855
+ async function resolveBrokerCredentials(brokerageAccountId) {
5856
+ const client = await getSharedApolloClient();
5857
+ const alpacaAccount = (await adaptic$1.alpacaAccount.get({
5858
+ id: brokerageAccountId,
5859
+ }, client));
5860
+ if (!alpacaAccount || !alpacaAccount.APIKey || !alpacaAccount.APISecret) {
5861
+ throw new Error("Alpaca account not found or incomplete");
5862
+ }
5863
+ validateAlpacaCredentials({
5864
+ apiKey: alpacaAccount.APIKey,
5865
+ apiSecret: alpacaAccount.APISecret,
5866
+ isPaper: alpacaAccount.type === "PAPER",
5867
+ });
5868
+ return {
5869
+ APIKey: alpacaAccount.APIKey,
5870
+ APISecret: alpacaAccount.APISecret,
5871
+ type: alpacaAccount.type,
5872
+ };
5873
+ }
5820
5874
 
5821
5875
  /**
5822
5876
  * Legacy Alpaca Utility Functions
@@ -7946,6 +8000,7 @@ var index$1 = /*#__PURE__*/Object.freeze({
7946
8000
  getOrders: getOrders$1,
7947
8001
  makeRequest: makeRequest,
7948
8002
  replaceOrder: replaceOrder$1,
8003
+ resolveBrokerCredentials: resolveBrokerCredentials,
7949
8004
  roundPriceForAlpaca: roundPriceForAlpaca$5,
7950
8005
  updateConfiguration: updateConfiguration,
7951
8006
  validateAuth: validateAuth
@@ -11168,9 +11223,16 @@ function calculateBetaFromReturns(portfolioReturns, benchmarkReturns) {
11168
11223
  const denom = n > 1 ? n - 1 : 1;
11169
11224
  covariance /= denom;
11170
11225
  variance /= denom;
11171
- // Handle zero variance
11172
- if (variance === 0) {
11173
- getLogger().warn("Benchmark variance is zero. Setting beta to 0.");
11226
+ // Handle zero (or numerically-degenerate) variance. A constant benchmark
11227
+ // series can still produce a tiny nonzero variance because the computed
11228
+ // mean differs from the constant by an ulp; dividing covariance by that
11229
+ // rounding noise yields a meaningless beta. Treat any variance at or
11230
+ // below the summation noise floor — (n * eps * |mean|)^2, the square of
11231
+ // the worst-case naive-summation error — as zero. When the mean is
11232
+ // exactly 0 this reduces to the exact zero check.
11233
+ const varianceNoiseFloor = (n * Number.EPSILON * Math.abs(averageBenchmarkReturn)) ** 2;
11234
+ if (variance <= varianceNoiseFloor) {
11235
+ getLogger().warn("Benchmark variance is zero or below the floating-point noise floor. Setting beta to 0.");
11174
11236
  return {
11175
11237
  beta: 0,
11176
11238
  covariance,
@@ -12349,8 +12411,33 @@ const timeDiffString = (milliseconds) => {
12349
12411
  return parts.join(", ");
12350
12412
  };
12351
12413
 
12414
+ /**
12415
+ * Multi-broker foundation types
12416
+ *
12417
+ * Provider-agnostic brokerage types for the org → fund → brokerageAccount →
12418
+ * broker alignment (SP2). These are strictly ADDITIVE: the existing
12419
+ * Alpaca-specific types (`AlpacaAuth`, `AlpacaCredentials`,
12420
+ * `AlpacaClientConfig`) remain the canonical shapes consumed by the engine
12421
+ * and are unchanged. New provider-aware call sites should prefer these
12422
+ * types; only ALPACA is implemented today — IBKR and COINBASE arms are
12423
+ * typed placeholders that resolve to `UnsupportedBrokerError` at runtime.
12424
+ *
12425
+ * @module @adaptic/utils/types/broker-types
12426
+ */
12427
+ /**
12428
+ * Type guard narrowing {@link BrokerCredentials} to the implemented
12429
+ * ALPACA arm.
12430
+ *
12431
+ * @param credentials - Any broker credentials union member
12432
+ * @returns True when the credentials belong to the ALPACA provider
12433
+ */
12434
+ function isAlpacaBrokerCredentials(credentials) {
12435
+ return credentials.provider === "ALPACA";
12436
+ }
12437
+
12352
12438
  var Types = /*#__PURE__*/Object.freeze({
12353
- __proto__: null
12439
+ __proto__: null,
12440
+ isAlpacaBrokerCredentials: isAlpacaBrokerCredentials
12354
12441
  });
12355
12442
 
12356
12443
  /**
@@ -50663,12 +50750,16 @@ class AlpacaClient {
50663
50750
  }
50664
50751
  // Client cache for connection pooling
50665
50752
  const clientCache = new Map();
50753
+ // Provider discriminant for cache-key scoping (multi-broker SP2 seam):
50754
+ // keeps Alpaca pool entries disjoint from future providers that might
50755
+ // reuse an identical apiKey string.
50756
+ const ALPACA_PROVIDER = "ALPACA";
50666
50757
  /**
50667
50758
  * Create or get a cached Alpaca client
50668
- * Uses apiKey as cache key for connection pooling
50759
+ * Uses provider + apiKey + accountType as cache key for connection pooling
50669
50760
  */
50670
50761
  function createAlpacaClient(config) {
50671
- const cacheKey = `${config.apiKey}-${config.accountType}`;
50762
+ const cacheKey = `${ALPACA_PROVIDER}-${config.apiKey}-${config.accountType}`;
50672
50763
  if (clientCache.has(cacheKey)) {
50673
50764
  log$k(`Returning cached client for ${config.accountType}`, { type: "debug" });
50674
50765
  return clientCache.get(cacheKey);
@@ -68788,6 +68879,49 @@ function verifyFetchKeepAlive() {
68788
68879
  };
68789
68880
  }
68790
68881
 
68882
+ /**
68883
+ * Broker Client Factory
68884
+ *
68885
+ * Provider-agnostic entry point for broker trading clients (SP2 multi-broker
68886
+ * seam). Strictly ADDITIVE: `createAlpacaClient`, `createAlpacaTradingAPI`,
68887
+ * and `createAlpacaMarketDataAPI` remain the canonical Alpaca factories and
68888
+ * are unchanged. Only ALPACA is implemented — all other providers throw a
68889
+ * typed {@link UnsupportedBrokerError}.
68890
+ *
68891
+ * @module @adaptic/utils/broker
68892
+ */
68893
+ /**
68894
+ * Create (or reuse from cache) a broker trading client for the given
68895
+ * credentials.
68896
+ *
68897
+ * ALPACA delegates to `createAlpacaClient`, whose connection-pool cache key
68898
+ * is provider-scoped (`ALPACA-<apiKey>-<accountType>`), so a future
68899
+ * provider reusing an identical apiKey string can never collide with an
68900
+ * Alpaca client. All other providers — including unknown provider strings
68901
+ * from untyped callers — throw {@link UnsupportedBrokerError}.
68902
+ *
68903
+ * @param credentials - Discriminated broker credentials union
68904
+ * @returns A provider-appropriate {@link BrokerTradingClient}
68905
+ * @throws UnsupportedBrokerError for any provider other than ALPACA
68906
+ */
68907
+ function createBrokerClient(credentials) {
68908
+ switch (credentials.provider) {
68909
+ case "ALPACA":
68910
+ return createAlpacaClient({
68911
+ apiKey: credentials.apiKey,
68912
+ apiSecret: credentials.apiSecret,
68913
+ accountType: credentials.type,
68914
+ });
68915
+ case "IBKR":
68916
+ case "COINBASE":
68917
+ throw new UnsupportedBrokerError(credentials.provider);
68918
+ }
68919
+ // Unreachable for typed callers (the switch above is exhaustive), but
68920
+ // untyped runtime callers may pass an unrecognised provider string —
68921
+ // fail fast with the same typed error rather than undefined behaviour.
68922
+ throw new UnsupportedBrokerError(String(credentials.provider));
68923
+ }
68924
+
68791
68925
  /**
68792
68926
  * Mirror enums for the trading policy preference system.
68793
68927
  * These enums are used by both the trading engine and the frontend app
@@ -69937,6 +70071,7 @@ exports.TrailingStopValidationError = TrailingStopValidationError;
69937
70071
  exports.USDC_PAIRS = USDC_PAIRS;
69938
70072
  exports.USDT_PAIRS = USDT_PAIRS;
69939
70073
  exports.USD_PAIRS = USD_PAIRS;
70074
+ exports.UnsupportedBrokerError = UnsupportedBrokerError;
69940
70075
  exports.ValidationError = ValidationError;
69941
70076
  exports.ValidationResponseError = ValidationResponseError;
69942
70077
  exports.WEBSOCKET_STREAMS = WEBSOCKET_STREAMS;
@@ -69975,6 +70110,7 @@ exports.createAlpacaClient = createAlpacaClient;
69975
70110
  exports.createAlpacaMarketDataAPI = createAlpacaMarketDataAPI;
69976
70111
  exports.createAlpacaTradingAPI = createAlpacaTradingAPI;
69977
70112
  exports.createBracketOrder = createBracketOrder;
70113
+ exports.createBrokerClient = createBrokerClient;
69978
70114
  exports.createButterflySpread = createButterflySpread;
69979
70115
  exports.createClientFromEnv = createClientFromEnv;
69980
70116
  exports.createCoveredCall = createCoveredCall;
@@ -70105,6 +70241,7 @@ exports.hasStockLiquidity = hasGoodLiquidity$1;
70105
70241
  exports.hasSufficientVolume = hasSufficientVolume;
70106
70242
  exports.httpAgent = httpAgent;
70107
70243
  exports.httpsAgent = httpsAgent;
70244
+ exports.isAlpacaBrokerCredentials = isAlpacaBrokerCredentials;
70108
70245
  exports.isContractTradable = isContractTradable;
70109
70246
  exports.isCryptoPair = isCryptoPair;
70110
70247
  exports.isExpiringWithin = isExpiringWithin;