@adaptic/utils 0.0.1013 → 0.0.1015
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 +488 -77
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +485 -78
- package/dist/index.mjs.map +1 -1
- package/dist/test.js.map +1 -1
- package/dist/types/__tests__/alpaca-broker-error-preservation.test.d.ts +2 -0
- package/dist/types/__tests__/alpaca-broker-error-preservation.test.d.ts.map +1 -0
- package/dist/types/__tests__/technical-analysis-totality.test.d.ts +2 -0
- package/dist/types/__tests__/technical-analysis-totality.test.d.ts.map +1 -0
- package/dist/types/alpaca/index.d.ts.map +1 -1
- package/dist/types/alpaca/legacy/orders.d.ts.map +1 -1
- package/dist/types/alpaca/trading/orders.d.ts.map +1 -1
- package/dist/types/alpaca/trading/trailing-stops.d.ts.map +1 -1
- package/dist/types/alpaca-trading-api.d.ts.map +1 -1
- package/dist/types/errors/index.d.ts +149 -1
- package/dist/types/errors/index.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/schemas/massive-schemas.d.ts +6 -6
- package/dist/types/technical-analysis.d.ts +25 -0
- package/dist/types/technical-analysis.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -2212,11 +2212,20 @@ class AdapticUtilsError extends Error {
|
|
|
2212
2212
|
*/
|
|
2213
2213
|
class AlpacaApiError extends AdapticUtilsError {
|
|
2214
2214
|
statusCode;
|
|
2215
|
-
|
|
2215
|
+
brokerError;
|
|
2216
|
+
constructor(message, code, statusCode, cause,
|
|
2217
|
+
/**
|
|
2218
|
+
* Normalized Alpaca broker-rejection detail (numeric code + message + raw
|
|
2219
|
+
* body), when the underlying rejection carried one. Additive and optional:
|
|
2220
|
+
* synthetic errors and non-broker failures omit it, and every existing
|
|
2221
|
+
* consumer of `message`/`code`/`statusCode`/`cause` is unaffected.
|
|
2222
|
+
*/
|
|
2223
|
+
brokerError) {
|
|
2216
2224
|
// Rate limit (429) and server errors (5xx) are retryable
|
|
2217
2225
|
const isRetryable = statusCode === 429 || (statusCode !== undefined && statusCode >= 500);
|
|
2218
2226
|
super(message, code, "alpaca", isRetryable, cause);
|
|
2219
2227
|
this.statusCode = statusCode;
|
|
2228
|
+
this.brokerError = brokerError;
|
|
2220
2229
|
}
|
|
2221
2230
|
}
|
|
2222
2231
|
/**
|
|
@@ -2412,11 +2421,261 @@ class DuplicateClientOrderIdError extends AlpacaApiError {
|
|
|
2412
2421
|
clientOrderId,
|
|
2413
2422
|
/** Whether the colliding id was derived by the wrapper (vs caller-supplied). */
|
|
2414
2423
|
wasDerived, cause) {
|
|
2415
|
-
|
|
2424
|
+
// Carry the normalized broker payload forward from the original rejection
|
|
2425
|
+
// (the `cause`) so a consumer can read the numeric code without re-parsing.
|
|
2426
|
+
super(message, "DUPLICATE_CLIENT_ORDER_ID", 422, cause, extractAlpacaBrokerError(cause));
|
|
2416
2427
|
this.clientOrderId = clientOrderId;
|
|
2417
2428
|
this.wasDerived = wasDerived;
|
|
2418
2429
|
}
|
|
2419
2430
|
}
|
|
2431
|
+
/** Max depth walked along the `error.cause` chain when locating a broker payload. */
|
|
2432
|
+
const MAX_BROKER_ERROR_CAUSE_DEPTH = 6;
|
|
2433
|
+
/**
|
|
2434
|
+
* Narrows an unknown value to an index-signature record so nested properties
|
|
2435
|
+
* can be probed without an unsafe cast.
|
|
2436
|
+
* @param value - The value to test.
|
|
2437
|
+
* @returns true when the value is a non-null object.
|
|
2438
|
+
*/
|
|
2439
|
+
function isBrokerErrorRecord(value) {
|
|
2440
|
+
return typeof value === "object" && value !== null;
|
|
2441
|
+
}
|
|
2442
|
+
/**
|
|
2443
|
+
* Reads a finite number from an unknown value, accepting Alpaca's numeric
|
|
2444
|
+
* `code` whether it arrives as a JSON number or a numeric string.
|
|
2445
|
+
* @param value - The candidate value.
|
|
2446
|
+
* @returns The number when finite, otherwise null.
|
|
2447
|
+
*/
|
|
2448
|
+
function asBrokerCode(value) {
|
|
2449
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
2450
|
+
return value;
|
|
2451
|
+
}
|
|
2452
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
2453
|
+
const parsed = Number(value);
|
|
2454
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
2455
|
+
}
|
|
2456
|
+
return null;
|
|
2457
|
+
}
|
|
2458
|
+
/**
|
|
2459
|
+
* Reads the axios/SDK-shaped broker payload from a SINGLE node's `response`
|
|
2460
|
+
* field: an object `response.data` (`{ code, message }`) or a `response.data`
|
|
2461
|
+
* left as an unparsed JSON string (the raw-`fetch` seams attach the body as a
|
|
2462
|
+
* string). A known HTTP `response.status` is itself a broker-boundary signal —
|
|
2463
|
+
* a `422` whose body carries no numeric code is still a `422` — so a
|
|
2464
|
+
* status-only detail (`brokerCode: null`) is surfaced rather than discarded.
|
|
2465
|
+
* Returns `undefined` only when the node carries no `response` and no status.
|
|
2466
|
+
*
|
|
2467
|
+
* @param node - The candidate error-like record.
|
|
2468
|
+
* @returns The normalized detail, or undefined when the node has no response.
|
|
2469
|
+
*/
|
|
2470
|
+
function readResponseBrokerDetail(node) {
|
|
2471
|
+
const response = node.response;
|
|
2472
|
+
if (!isBrokerErrorRecord(response)) {
|
|
2473
|
+
return undefined;
|
|
2474
|
+
}
|
|
2475
|
+
const statusCode = asBrokerCode(response.status);
|
|
2476
|
+
// A known status with no structured code/message: preserve the status rather
|
|
2477
|
+
// than discarding it (a code null is never fabricated into a value).
|
|
2478
|
+
const statusOnly = statusCode === null
|
|
2479
|
+
? undefined
|
|
2480
|
+
: { brokerCode: null, brokerMessage: null, statusCode, raw: response.data };
|
|
2481
|
+
// Keep the raw body in its own const so the string narrowing survives the
|
|
2482
|
+
// JSON.parse (a reassigned `let` would widen back to `unknown` in the catch).
|
|
2483
|
+
const rawData = response.data;
|
|
2484
|
+
let parsed = rawData;
|
|
2485
|
+
if (typeof rawData === "string") {
|
|
2486
|
+
try {
|
|
2487
|
+
parsed = JSON.parse(rawData);
|
|
2488
|
+
}
|
|
2489
|
+
catch {
|
|
2490
|
+
// A non-JSON string body carries a human reason but no structured code.
|
|
2491
|
+
return { brokerCode: null, brokerMessage: rawData, statusCode, raw: rawData };
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
if (!isBrokerErrorRecord(parsed)) {
|
|
2495
|
+
return statusOnly;
|
|
2496
|
+
}
|
|
2497
|
+
const brokerCode = asBrokerCode(parsed.code);
|
|
2498
|
+
const brokerMessage = typeof parsed.message === "string" ? parsed.message : null;
|
|
2499
|
+
if (brokerCode === null && brokerMessage === null) {
|
|
2500
|
+
return statusOnly;
|
|
2501
|
+
}
|
|
2502
|
+
return { brokerCode, brokerMessage, statusCode, raw: rawData };
|
|
2503
|
+
}
|
|
2504
|
+
/**
|
|
2505
|
+
* Reads the normalized broker detail from a SINGLE error-like node, without
|
|
2506
|
+
* walking its `cause` chain. Recognizes two carriers on the node: an
|
|
2507
|
+
* {@link AlpacaBrokerErrorDetail} already attached as `brokerError`, and an
|
|
2508
|
+
* axios/SDK-shaped `response` body (object or unparsed JSON string). A carrier
|
|
2509
|
+
* bearing a numeric code wins over a code-less one, so an enrichment that
|
|
2510
|
+
* resolved no code never shadows a numeric code sitting in the same node's raw
|
|
2511
|
+
* response body. Returns `undefined` when the node carries no broker payload,
|
|
2512
|
+
* so absence is never converted into a fabricated code.
|
|
2513
|
+
*
|
|
2514
|
+
* @param node - The candidate error-like value.
|
|
2515
|
+
* @returns The normalized detail, or undefined.
|
|
2516
|
+
*/
|
|
2517
|
+
function readBrokerDetailFromNode(node) {
|
|
2518
|
+
if (!isBrokerErrorRecord(node)) {
|
|
2519
|
+
return undefined;
|
|
2520
|
+
}
|
|
2521
|
+
// Carrier 1: a detail already normalized and attached by this module
|
|
2522
|
+
// (e.g. AlpacaApiError.brokerError or a value enriched via enrichAlpacaError).
|
|
2523
|
+
let attachedDetail;
|
|
2524
|
+
const attached = node.brokerError;
|
|
2525
|
+
if (isBrokerErrorRecord(attached) && "brokerCode" in attached) {
|
|
2526
|
+
attachedDetail = {
|
|
2527
|
+
brokerCode: asBrokerCode(attached.brokerCode),
|
|
2528
|
+
brokerMessage: typeof attached.brokerMessage === "string"
|
|
2529
|
+
? attached.brokerMessage
|
|
2530
|
+
: null,
|
|
2531
|
+
statusCode: asBrokerCode(attached.statusCode),
|
|
2532
|
+
raw: attached.raw,
|
|
2533
|
+
};
|
|
2534
|
+
// A numeric code on the attached detail is authoritative for this node.
|
|
2535
|
+
if (attachedDetail.brokerCode !== null) {
|
|
2536
|
+
return attachedDetail;
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
// Carrier 2: an axios/SDK-shaped `response` body on the same node. Prefer a
|
|
2540
|
+
// numeric code found here over a code-less attached detail.
|
|
2541
|
+
const responseDetail = readResponseBrokerDetail(node);
|
|
2542
|
+
if (responseDetail?.brokerCode != null) {
|
|
2543
|
+
return responseDetail;
|
|
2544
|
+
}
|
|
2545
|
+
return attachedDetail ?? responseDetail;
|
|
2546
|
+
}
|
|
2547
|
+
/**
|
|
2548
|
+
* Extracts the normalized {@link AlpacaBrokerErrorDetail} from a thrown Alpaca
|
|
2549
|
+
* SDK/axios error, reading the vendor payload at `error.response.data` and,
|
|
2550
|
+
* failing that, walking the `error.cause` chain (the raw SDK error is preserved
|
|
2551
|
+
* there once a wrapper has re-thrown). Returns `undefined` when no broker
|
|
2552
|
+
* payload is present anywhere on the chain.
|
|
2553
|
+
*
|
|
2554
|
+
* Pure and outcome-independent: derived solely from Alpaca's documented error
|
|
2555
|
+
* contract, with zero reference to realized P&L, fills, or account state.
|
|
2556
|
+
*
|
|
2557
|
+
* A node bearing a numeric broker code wins immediately; a code-less detail
|
|
2558
|
+
* (status-only or message-only) found higher on the chain is held as a fallback
|
|
2559
|
+
* while the walk continues, so a numeric code sitting deeper in the `cause`
|
|
2560
|
+
* chain is never shadowed by a shallower code-less node — and when no code
|
|
2561
|
+
* exists anywhere, the code-less detail is still returned rather than discarded.
|
|
2562
|
+
*
|
|
2563
|
+
* @param error - The thrown value.
|
|
2564
|
+
* @returns The normalized broker detail, or undefined when none is present.
|
|
2565
|
+
*/
|
|
2566
|
+
function extractAlpacaBrokerError(error) {
|
|
2567
|
+
let current = error;
|
|
2568
|
+
let fallback;
|
|
2569
|
+
for (let depth = 0; depth < MAX_BROKER_ERROR_CAUSE_DEPTH && current != null; depth++) {
|
|
2570
|
+
const detail = readBrokerDetailFromNode(current);
|
|
2571
|
+
if (detail !== undefined) {
|
|
2572
|
+
if (detail.brokerCode !== null) {
|
|
2573
|
+
return detail;
|
|
2574
|
+
}
|
|
2575
|
+
if (fallback === undefined) {
|
|
2576
|
+
fallback = detail;
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
if (!isBrokerErrorRecord(current)) {
|
|
2580
|
+
break;
|
|
2581
|
+
}
|
|
2582
|
+
current = current.cause;
|
|
2583
|
+
}
|
|
2584
|
+
return fallback;
|
|
2585
|
+
}
|
|
2586
|
+
/**
|
|
2587
|
+
* Returns the normalized {@link AlpacaBrokerErrorDetail} for a thrown error, or
|
|
2588
|
+
* `null` when the error carries no Alpaca broker payload. The typed
|
|
2589
|
+
* vendor-boundary replacement for reaching into `err.response.data` downstream.
|
|
2590
|
+
*
|
|
2591
|
+
* @param error - The thrown value.
|
|
2592
|
+
* @returns The normalized detail, or null.
|
|
2593
|
+
*/
|
|
2594
|
+
function getAlpacaBrokerErrorDetail(error) {
|
|
2595
|
+
return extractAlpacaBrokerError(error) ?? null;
|
|
2596
|
+
}
|
|
2597
|
+
/**
|
|
2598
|
+
* Returns Alpaca's machine-readable numeric broker error code from a thrown
|
|
2599
|
+
* error (walking the `cause` chain), or `null` when absent. The typed
|
|
2600
|
+
* replacement for `err.message.includes("42210000")`:
|
|
2601
|
+
*
|
|
2602
|
+
* ```typescript
|
|
2603
|
+
* if (getAlpacaBrokerErrorCode(err) === 42210000) { ... } // stale-order reject
|
|
2604
|
+
* ```
|
|
2605
|
+
*
|
|
2606
|
+
* The code resolves uniformly across every vendor seam: the SDK/axios path
|
|
2607
|
+
* (where `response.data` rides along for free) and the raw-`fetch` paths — the
|
|
2608
|
+
* `AlpacaTradingAPI` class `makeRequest` and the legacy order helpers, which
|
|
2609
|
+
* throw via {@link alpacaHttpError} so the verbatim status + body are carried as
|
|
2610
|
+
* a typed `.response`. A consumer branching on the stale-order `42210000` gets
|
|
2611
|
+
* the same answer regardless of which seam produced the reject, including the
|
|
2612
|
+
* dominant percent-trailing-stop tighten path where a plain `Error` previously
|
|
2613
|
+
* dropped the broker payload.
|
|
2614
|
+
*
|
|
2615
|
+
* @param error - The thrown value.
|
|
2616
|
+
* @returns The numeric broker code, or null.
|
|
2617
|
+
*/
|
|
2618
|
+
function getAlpacaBrokerErrorCode(error) {
|
|
2619
|
+
return extractAlpacaBrokerError(error)?.brokerCode ?? null;
|
|
2620
|
+
}
|
|
2621
|
+
/**
|
|
2622
|
+
* Additively enriches a thrown error with the normalized Alpaca broker detail
|
|
2623
|
+
* extracted from `source` (the original SDK/axios rejection), WITHOUT changing
|
|
2624
|
+
* the target's `message`, `name`, or prototype. It:
|
|
2625
|
+
*
|
|
2626
|
+
* - sets `target.cause = source` when the target has no cause yet, so the raw
|
|
2627
|
+
* rejection (and its `response.data`) is never lost down the wrapper chain;
|
|
2628
|
+
* - attaches the normalized {@link AlpacaBrokerErrorDetail} as
|
|
2629
|
+
* `target.brokerError` when `source` carried a broker payload.
|
|
2630
|
+
*
|
|
2631
|
+
* Purely additive by construction: a caller writes
|
|
2632
|
+
* `throw enrichAlpacaError(new Error(msg), error)` and every consumer that read
|
|
2633
|
+
* `error.message` or `error instanceof Error` before reads the identical value
|
|
2634
|
+
* after, while new consumers can call {@link getAlpacaBrokerErrorCode}. This is
|
|
2635
|
+
* the restoration for the dropped-`response.data` defect (Alpaca `42210000` /
|
|
2636
|
+
* `40310000` reaching consumers only as a lossy "status code NNN" string).
|
|
2637
|
+
*
|
|
2638
|
+
* @param target - The wrapper error about to be thrown.
|
|
2639
|
+
* @param source - The original rejection to normalize and preserve.
|
|
2640
|
+
* @returns The same `target`, typed to expose the optional `brokerError`.
|
|
2641
|
+
*/
|
|
2642
|
+
function enrichAlpacaError(target, source) {
|
|
2643
|
+
const enriched = target;
|
|
2644
|
+
if (enriched.cause === undefined && source !== undefined) {
|
|
2645
|
+
enriched.cause = source;
|
|
2646
|
+
}
|
|
2647
|
+
const detail = extractAlpacaBrokerError(source);
|
|
2648
|
+
if (detail !== undefined) {
|
|
2649
|
+
enriched.brokerError = detail;
|
|
2650
|
+
}
|
|
2651
|
+
return enriched;
|
|
2652
|
+
}
|
|
2653
|
+
/**
|
|
2654
|
+
* Builds a thrown-ready `Error` for a raw-`fetch` Alpaca rejection, carrying the
|
|
2655
|
+
* verbatim HTTP status + body as a typed `.response` so that
|
|
2656
|
+
* {@link getAlpacaBrokerErrorCode} / {@link extractAlpacaBrokerError} resolve
|
|
2657
|
+
* the numeric broker code on the `fetch` seams (the `AlpacaTradingAPI` class
|
|
2658
|
+
* `makeRequest` and the legacy functional order helpers) exactly as they
|
|
2659
|
+
* already do on the SDK seam — where the SDK/axios error carries `response.data`
|
|
2660
|
+
* for free but a hand-thrown `new Error(...)` does not.
|
|
2661
|
+
*
|
|
2662
|
+
* Purely additive by construction: the `.message` is caller-supplied and
|
|
2663
|
+
* returned byte-identical (so message string-matching consumers are
|
|
2664
|
+
* unaffected), the returned value `instanceof Error` still holds, and only the
|
|
2665
|
+
* `.response` surface is added. The `data` is the raw string body exactly as
|
|
2666
|
+
* `response.text()` returned it — {@link extractAlpacaBrokerError} parses a
|
|
2667
|
+
* JSON-string body itself, so no vendor payload is lost or reshaped here.
|
|
2668
|
+
*
|
|
2669
|
+
* @param message - The error message, thrown verbatim (never rewritten).
|
|
2670
|
+
* @param status - The HTTP status the rejection arrived on.
|
|
2671
|
+
* @param body - The raw response body (`response.text()`), preserved verbatim.
|
|
2672
|
+
* @returns An `Error` whose `.response` exposes `{ status, data: body }`.
|
|
2673
|
+
*/
|
|
2674
|
+
function alpacaHttpError(message, status, body) {
|
|
2675
|
+
return Object.assign(new Error(message), {
|
|
2676
|
+
response: { status, data: body },
|
|
2677
|
+
});
|
|
2678
|
+
}
|
|
2420
2679
|
|
|
2421
2680
|
const DEFAULT_RETRY_CONFIG = {
|
|
2422
2681
|
maxRetries: 3,
|
|
@@ -5296,7 +5555,13 @@ class AlpacaTradingAPI {
|
|
|
5296
5555
|
this.log(`Alpaca API error (${response.status}): ${errorText}`, {
|
|
5297
5556
|
type: "error",
|
|
5298
5557
|
});
|
|
5299
|
-
|
|
5558
|
+
// Additive broker-error preservation: the message is byte-identical
|
|
5559
|
+
// (existing "422"/"42210000" string-matching consumers are unaffected),
|
|
5560
|
+
// and the verbatim status + body ride along as a typed `.response` so
|
|
5561
|
+
// getAlpacaBrokerErrorCode resolves the numeric code on this fetch seam —
|
|
5562
|
+
// the dominant percent-trailing-stop tighten path and the 08-20 defect
|
|
5563
|
+
// site, where a plain Error dropped the broker's response.data.
|
|
5564
|
+
throw alpacaHttpError(`Alpaca API error (${response.status}): ${errorText}`, response.status, errorText);
|
|
5300
5565
|
}
|
|
5301
5566
|
// Handle responses with no content (e.g., 204 No Content)
|
|
5302
5567
|
if (response.status === 204 ||
|
|
@@ -5681,7 +5946,10 @@ class AlpacaTradingAPI {
|
|
|
5681
5946
|
this.log(`Order ${orderId} is not cancelable`, {
|
|
5682
5947
|
type: "error",
|
|
5683
5948
|
});
|
|
5684
|
-
|
|
5949
|
+
// Re-message stays byte-identical; the broker payload from makeRequest's
|
|
5950
|
+
// `.response` is carried onto the new error so the numeric code survives
|
|
5951
|
+
// this wrapper instead of being dropped at the re-throw.
|
|
5952
|
+
throw enrichAlpacaError(new Error(`Order ${orderId} is not cancelable`), error);
|
|
5685
5953
|
}
|
|
5686
5954
|
// Re-throw other errors
|
|
5687
5955
|
throw error;
|
|
@@ -6731,7 +6999,7 @@ async function makeRequest(auth, params) {
|
|
|
6731
6999
|
source: "AlpacaAPI",
|
|
6732
7000
|
type: "error",
|
|
6733
7001
|
});
|
|
6734
|
-
throw
|
|
7002
|
+
throw alpacaHttpError(`Alpaca API error (${response.status}): ${errorText}`, response.status, errorText);
|
|
6735
7003
|
}
|
|
6736
7004
|
catch (err) {
|
|
6737
7005
|
const error = err;
|
|
@@ -6764,7 +7032,7 @@ async function createOrder$1(auth, params) {
|
|
|
6764
7032
|
});
|
|
6765
7033
|
if (!response.ok) {
|
|
6766
7034
|
const errorText = await response.text();
|
|
6767
|
-
throw
|
|
7035
|
+
throw alpacaHttpError(`Failed to create order: ${response.status} ${response.statusText} ${errorText}`, response.status, errorText);
|
|
6768
7036
|
}
|
|
6769
7037
|
return (await response.json());
|
|
6770
7038
|
}
|
|
@@ -6811,7 +7079,7 @@ async function getOrders$1(auth, params = {}) {
|
|
|
6811
7079
|
});
|
|
6812
7080
|
if (!response.ok) {
|
|
6813
7081
|
const errorText = await response.text();
|
|
6814
|
-
throw
|
|
7082
|
+
throw alpacaHttpError(`Failed to get orders: ${response.status} ${response.statusText} ${errorText}`, response.status, errorText);
|
|
6815
7083
|
}
|
|
6816
7084
|
const orders = (await response.json());
|
|
6817
7085
|
allOrders.push(...orders);
|
|
@@ -6872,7 +7140,7 @@ async function cancelAllOrders$1(auth) {
|
|
|
6872
7140
|
});
|
|
6873
7141
|
if (!response.ok) {
|
|
6874
7142
|
const errorText = await response.text();
|
|
6875
|
-
throw
|
|
7143
|
+
throw alpacaHttpError(`Failed to cancel orders: ${response.status} ${response.statusText} ${errorText}`, response.status, errorText);
|
|
6876
7144
|
}
|
|
6877
7145
|
return (await response.json());
|
|
6878
7146
|
}
|
|
@@ -6905,7 +7173,7 @@ async function getOrder$1(auth, orderId, nested) {
|
|
|
6905
7173
|
});
|
|
6906
7174
|
if (!response.ok) {
|
|
6907
7175
|
const errorText = await response.text();
|
|
6908
|
-
throw
|
|
7176
|
+
throw alpacaHttpError(`Failed to get order: ${response.status} ${response.statusText} ${errorText}`, response.status, errorText);
|
|
6909
7177
|
}
|
|
6910
7178
|
return (await response.json());
|
|
6911
7179
|
}
|
|
@@ -6938,7 +7206,7 @@ async function replaceOrder$1(auth, orderId, params) {
|
|
|
6938
7206
|
});
|
|
6939
7207
|
if (!response.ok) {
|
|
6940
7208
|
const errorText = await response.text();
|
|
6941
|
-
throw
|
|
7209
|
+
throw alpacaHttpError(`Failed to replace order: ${response.status} ${response.statusText} ${errorText}`, response.status, errorText);
|
|
6942
7210
|
}
|
|
6943
7211
|
return (await response.json());
|
|
6944
7212
|
}
|
|
@@ -6971,7 +7239,7 @@ async function cancelOrder$1(auth, orderId) {
|
|
|
6971
7239
|
return { success: false, message: `Order not found: ${orderId}` };
|
|
6972
7240
|
}
|
|
6973
7241
|
else {
|
|
6974
|
-
throw
|
|
7242
|
+
throw alpacaHttpError(`Failed to cancel order: ${response.status} ${response.statusText} ${errorText}`, response.status, errorText);
|
|
6975
7243
|
}
|
|
6976
7244
|
}
|
|
6977
7245
|
return { success: true };
|
|
@@ -12862,6 +13130,66 @@ var strategyNs = /*#__PURE__*/Object.freeze({
|
|
|
12862
13130
|
calculateRollingSortino: calculateRollingSortino
|
|
12863
13131
|
});
|
|
12864
13132
|
|
|
13133
|
+
/**
|
|
13134
|
+
* Round a PRICE-scale indicator output to a precision derived from its own
|
|
13135
|
+
* magnitude, rather than a hardcoded 2 decimal places.
|
|
13136
|
+
*
|
|
13137
|
+
* A flat `toFixed(2)` silently destroys every sub-penny price — a $0.0003
|
|
13138
|
+
* microcap's bands collapse to `0.00`, and a MACD histogram of a low-priced
|
|
13139
|
+
* name rounds to nothing (F7.2). Precision must scale with the price: values at
|
|
13140
|
+
* or above $1 keep the conventional 2dp, while sub-dollar values keep ~4
|
|
13141
|
+
* significant figures so the number survives its own scale. Non-finite inputs
|
|
13142
|
+
* pass through untouched — totality of the underlying value is the caller's
|
|
13143
|
+
* responsibility, this helper only quantises.
|
|
13144
|
+
*
|
|
13145
|
+
* The `>= $1` branch delegates to `toFixed(2)` rather than re-deriving it as
|
|
13146
|
+
* `Math.round(value * 100) / 100`. The two disagree wherever the intermediate
|
|
13147
|
+
* `value * 100` rounds onto an exact `.5` that the decimal value sits just
|
|
13148
|
+
* below (`1.045` → `1.05` vs `1.04`), which would make this helper shift
|
|
13149
|
+
* ordinary dollar prices by a cent — a behaviour change well outside repairing
|
|
13150
|
+
* sub-penny collapse. Delegating keeps the common case byte-identical to the
|
|
13151
|
+
* historical output by construction, which matters because the same function
|
|
13152
|
+
* computes indicators for unit tests, backtests, paper and live.
|
|
13153
|
+
*
|
|
13154
|
+
* @param value - A price-scale indicator output (band, EMA, MACD component).
|
|
13155
|
+
* @returns The value rounded to a scale-appropriate precision.
|
|
13156
|
+
*/
|
|
13157
|
+
function roundToPriceScale(value) {
|
|
13158
|
+
if (!Number.isFinite(value))
|
|
13159
|
+
return value;
|
|
13160
|
+
const abs = Math.abs(value);
|
|
13161
|
+
if (abs === 0)
|
|
13162
|
+
return 0;
|
|
13163
|
+
if (abs >= 1)
|
|
13164
|
+
return parseFloat(value.toFixed(2));
|
|
13165
|
+
// Sub-dollar: decimals = leading zeros after the point + 4 significant figures,
|
|
13166
|
+
// capped so the factor stays within safe-integer range.
|
|
13167
|
+
const decimals = Math.min(12, Math.ceil(-Math.log10(abs)) + 4);
|
|
13168
|
+
const factor = 10 ** decimals;
|
|
13169
|
+
return Math.round(value * factor) / factor;
|
|
13170
|
+
}
|
|
13171
|
+
/**
|
|
13172
|
+
* Relative Strength Index from average gain / average loss, total on the
|
|
13173
|
+
* degenerate flat window.
|
|
13174
|
+
*
|
|
13175
|
+
* When a window has no losses the Wilder ratio `avgGain / avgLoss` is
|
|
13176
|
+
* `+Infinity` (→ RSI 100); on a perfectly flat window it is `0 / 0 = NaN`,
|
|
13177
|
+
* which the naive formula propagates straight into the output. A flat window
|
|
13178
|
+
* carries no momentum, so its RSI is the neutral 50 — never NaN. This mirrors
|
|
13179
|
+
* the engine's live RSI guards (a constant series scores neutral, an all-gains
|
|
13180
|
+
* series scores 100).
|
|
13181
|
+
*
|
|
13182
|
+
* @param avgGain - Average gain over the period (>= 0).
|
|
13183
|
+
* @param avgLoss - Average loss over the period (>= 0).
|
|
13184
|
+
* @returns RSI in [0, 100]; 50 for a flat window, 100 for an all-gains window.
|
|
13185
|
+
*/
|
|
13186
|
+
function rsiFromAverages(avgGain, avgLoss) {
|
|
13187
|
+
if (avgLoss === 0)
|
|
13188
|
+
return avgGain === 0 ? 50 : 100;
|
|
13189
|
+
const rs = avgGain / avgLoss;
|
|
13190
|
+
const rsi = 100 - 100 / (1 + rs);
|
|
13191
|
+
return Number.isFinite(rsi) ? rsi : 50;
|
|
13192
|
+
}
|
|
12865
13193
|
/**
|
|
12866
13194
|
* Calculates Bollinger Bands for a given set of price data.
|
|
12867
13195
|
* Bollinger Bands consist of a middle band (SMA) and two outer bands
|
|
@@ -12894,9 +13222,9 @@ function calculateBollingerBands(priceData, { period = 20, standardDeviations =
|
|
|
12894
13222
|
const lowerBand = sma - standardDeviation * standardDeviations;
|
|
12895
13223
|
result.push({
|
|
12896
13224
|
date: priceData[i].date,
|
|
12897
|
-
middle:
|
|
12898
|
-
upper:
|
|
12899
|
-
lower:
|
|
13225
|
+
middle: roundToPriceScale(sma),
|
|
13226
|
+
upper: roundToPriceScale(upperBand),
|
|
13227
|
+
lower: roundToPriceScale(lowerBand),
|
|
12900
13228
|
close: priceData[i].close,
|
|
12901
13229
|
});
|
|
12902
13230
|
}
|
|
@@ -12938,11 +13266,11 @@ function calculateEMA(priceData, { period = 20, period2 = 9 } = {}) {
|
|
|
12938
13266
|
// Add first EMA(s)
|
|
12939
13267
|
const firstEntry = {
|
|
12940
13268
|
date: priceData[Math.max(period, period2 || 0) - 1].date,
|
|
12941
|
-
ema:
|
|
13269
|
+
ema: roundToPriceScale(prevEMA),
|
|
12942
13270
|
close: priceData[Math.max(period, period2 || 0) - 1].close,
|
|
12943
13271
|
};
|
|
12944
13272
|
if (period2) {
|
|
12945
|
-
firstEntry.ema2 =
|
|
13273
|
+
firstEntry.ema2 = roundToPriceScale(prevEMA2);
|
|
12946
13274
|
}
|
|
12947
13275
|
result.push(firstEntry);
|
|
12948
13276
|
// Calculate EMA for remaining periods
|
|
@@ -12952,13 +13280,13 @@ function calculateEMA(priceData, { period = 20, period2 = 9 } = {}) {
|
|
|
12952
13280
|
prevEMA = currentEMA;
|
|
12953
13281
|
const entry = {
|
|
12954
13282
|
date: priceData[i].date,
|
|
12955
|
-
ema:
|
|
13283
|
+
ema: roundToPriceScale(currentEMA),
|
|
12956
13284
|
close: currentClose,
|
|
12957
13285
|
};
|
|
12958
13286
|
if (period2) {
|
|
12959
13287
|
const currentEMA2 = (currentClose - prevEMA2) * multiplier2 + prevEMA2;
|
|
12960
13288
|
prevEMA2 = currentEMA2;
|
|
12961
|
-
entry.ema2 =
|
|
13289
|
+
entry.ema2 = roundToPriceScale(currentEMA2);
|
|
12962
13290
|
}
|
|
12963
13291
|
result.push(entry);
|
|
12964
13292
|
}
|
|
@@ -13036,7 +13364,7 @@ function calculateFibonacciLevels(priceData, { lookbackPeriod = 20, retracementL
|
|
|
13036
13364
|
: swingHigh - priceRange * level;
|
|
13037
13365
|
levels.push({
|
|
13038
13366
|
level,
|
|
13039
|
-
price:
|
|
13367
|
+
price: roundToPriceScale(price),
|
|
13040
13368
|
type: "retracement",
|
|
13041
13369
|
});
|
|
13042
13370
|
});
|
|
@@ -13050,7 +13378,7 @@ function calculateFibonacciLevels(priceData, { lookbackPeriod = 20, retracementL
|
|
|
13050
13378
|
: swingHigh + priceRange * (level - 1); // For uptrend
|
|
13051
13379
|
levels.push({
|
|
13052
13380
|
level,
|
|
13053
|
-
price:
|
|
13381
|
+
price: roundToPriceScale(price),
|
|
13054
13382
|
type: "extension",
|
|
13055
13383
|
});
|
|
13056
13384
|
});
|
|
@@ -13113,9 +13441,9 @@ function calculateMACD(priceData, { shortPeriod = 12, longPeriod = 26, signalPer
|
|
|
13113
13441
|
const hist = macdValue - signalEMA;
|
|
13114
13442
|
result.push({
|
|
13115
13443
|
date: emaLong[i].date, // Use emaLong's date for alignment
|
|
13116
|
-
macd:
|
|
13117
|
-
signal:
|
|
13118
|
-
histogram:
|
|
13444
|
+
macd: roundToPriceScale(macdValue),
|
|
13445
|
+
signal: roundToPriceScale(signalEMA),
|
|
13446
|
+
histogram: roundToPriceScale(hist),
|
|
13119
13447
|
close: emaLong[i].close,
|
|
13120
13448
|
});
|
|
13121
13449
|
}
|
|
@@ -13150,9 +13478,9 @@ function calculateRSI(priceData, { period = 14 } = {}) {
|
|
|
13150
13478
|
}
|
|
13151
13479
|
avgGain = avgGain / period;
|
|
13152
13480
|
avgLoss = avgLoss / period;
|
|
13153
|
-
// Calculate RSI for the first period
|
|
13154
|
-
|
|
13155
|
-
let rsi =
|
|
13481
|
+
// Calculate RSI for the first period (total on a flat window — see
|
|
13482
|
+
// rsiFromAverages: a constant series scores the neutral 50, never NaN).
|
|
13483
|
+
let rsi = rsiFromAverages(avgGain, avgLoss);
|
|
13156
13484
|
result.push({
|
|
13157
13485
|
date: priceData[period].date,
|
|
13158
13486
|
rsi: parseFloat(rsi.toFixed(2)),
|
|
@@ -13166,8 +13494,7 @@ function calculateRSI(priceData, { period = 14 } = {}) {
|
|
|
13166
13494
|
// Use smoothed averages
|
|
13167
13495
|
avgGain = (avgGain * (period - 1) + gain) / period;
|
|
13168
13496
|
avgLoss = (avgLoss * (period - 1) + loss) / period;
|
|
13169
|
-
|
|
13170
|
-
rsi = 100 - 100 / (1 + rs);
|
|
13497
|
+
rsi = rsiFromAverages(avgGain, avgLoss);
|
|
13171
13498
|
result.push({
|
|
13172
13499
|
date: priceData[i].date,
|
|
13173
13500
|
rsi: parseFloat(rsi.toFixed(2)),
|
|
@@ -13188,6 +13515,20 @@ function calculateRSI(priceData, { period = 14 } = {}) {
|
|
|
13188
13515
|
* @returns An array of StochData objects containing the calculated %K and %D values.
|
|
13189
13516
|
*/
|
|
13190
13517
|
function calculateStochasticOscillator(priceData, { lookbackPeriod = 5, signalPeriod = 3, smoothingFactor = 3, } = {}) {
|
|
13518
|
+
// Each period is a divisor (`kSum / min(len, smoothingFactor)`) and a slice
|
|
13519
|
+
// width. A zero or fractional period therefore divides by zero or slices an
|
|
13520
|
+
// empty window, producing NaN/Infinity %K and %D — an oscillator reading that
|
|
13521
|
+
// is never true and never false. The periods are caller-supplied constants
|
|
13522
|
+
// rather than market data, so an invalid one is a programming error and is
|
|
13523
|
+
// reported as such, matching the ATR and volatility primitives.
|
|
13524
|
+
if (!Number.isInteger(lookbackPeriod) ||
|
|
13525
|
+
lookbackPeriod < 1 ||
|
|
13526
|
+
!Number.isInteger(signalPeriod) ||
|
|
13527
|
+
signalPeriod < 1 ||
|
|
13528
|
+
!Number.isInteger(smoothingFactor) ||
|
|
13529
|
+
smoothingFactor < 1) {
|
|
13530
|
+
throw new Error("calculateStochasticOscillator: lookbackPeriod, signalPeriod and smoothingFactor must be positive integers");
|
|
13531
|
+
}
|
|
13191
13532
|
if (priceData.length < lookbackPeriod) {
|
|
13192
13533
|
logIfDebug(`Insufficient data for Stochastic Oscillator calculation: required periods: ${lookbackPeriod}, but only received ${priceData.length} periods of data`);
|
|
13193
13534
|
return [];
|
|
@@ -13228,6 +13569,48 @@ function calculateStochasticOscillator(priceData, { lookbackPeriod = 5, signalPe
|
|
|
13228
13569
|
}
|
|
13229
13570
|
return result;
|
|
13230
13571
|
}
|
|
13572
|
+
/**
|
|
13573
|
+
* Collapses a cluster of nearby pivots into one volume-weighted level, or
|
|
13574
|
+
* reports that the cluster evidences no level at all.
|
|
13575
|
+
*
|
|
13576
|
+
* Both outputs are volume-weighted: the price is the volume-weighted mean of
|
|
13577
|
+
* the cluster's pivots, and the strength is the pivot count weighted by each
|
|
13578
|
+
* pivot's share of cluster volume. That weighting is undefined when the cluster
|
|
13579
|
+
* transacted no volume — `0 / 0` makes both NaN. A NaN level is strictly worse
|
|
13580
|
+
* than no level: every comparison against NaN is false, so a stop or target
|
|
13581
|
+
* placed off one is silently never triggered, leaving the position unprotected
|
|
13582
|
+
* while appearing protected.
|
|
13583
|
+
*
|
|
13584
|
+
* Zero cluster volume is a real market state rather than corrupt input — halted,
|
|
13585
|
+
* pre-market-thin and synthetic warm-up bars all report it. A support or
|
|
13586
|
+
* resistance level means price transacted enough there to turn the market, so a
|
|
13587
|
+
* cluster with no volume has not evidenced one. `SupportResistanceLevel` types
|
|
13588
|
+
* both fields as non-optional numbers, which leaves omitting the level as the
|
|
13589
|
+
* only honest way to say so.
|
|
13590
|
+
*
|
|
13591
|
+
* @param cluster - The nearby pivots to collapse into a single level.
|
|
13592
|
+
* @param currentPrice - The bar's close, which classifies the level's side.
|
|
13593
|
+
* @returns The aggregated level, or null when the cluster evidences none.
|
|
13594
|
+
*/
|
|
13595
|
+
function aggregatePivotCluster(cluster, currentPrice) {
|
|
13596
|
+
const totalVolume = cluster.reduce((sum, p) => sum + p.volume, 0);
|
|
13597
|
+
// Negated `> 0` so NaN and negative totals are rejected alongside zero: no
|
|
13598
|
+
// volume weighting survives any of them.
|
|
13599
|
+
if (!(totalVolume > 0))
|
|
13600
|
+
return null;
|
|
13601
|
+
const avgPrice = cluster.reduce((sum, p) => sum + p.price * p.volume, 0) / totalVolume;
|
|
13602
|
+
const strength = cluster.reduce((sum, p) => sum + p.count * (p.volume / totalVolume), 0);
|
|
13603
|
+
if (!Number.isFinite(avgPrice) || !Number.isFinite(strength))
|
|
13604
|
+
return null;
|
|
13605
|
+
return {
|
|
13606
|
+
// The level is a price, so its precision follows the price's magnitude
|
|
13607
|
+
// (F7.2). Strength is a count-weighted score rather than a price and keeps
|
|
13608
|
+
// the conventional 2dp.
|
|
13609
|
+
price: roundToPriceScale(avgPrice),
|
|
13610
|
+
strength: parseFloat(strength.toFixed(2)),
|
|
13611
|
+
type: avgPrice > currentPrice ? "resistance" : "support",
|
|
13612
|
+
};
|
|
13613
|
+
}
|
|
13231
13614
|
/**
|
|
13232
13615
|
* Calculates support and resistance levels based on price data.
|
|
13233
13616
|
* Support and resistance levels are price levels at which a stock tends to stop and reverse.
|
|
@@ -13248,9 +13631,22 @@ function calculateSupportAndResistance(priceData, { maxLevels = 5, lookbackPerio
|
|
|
13248
13631
|
const priceChanges = analysisWindow
|
|
13249
13632
|
.slice(1)
|
|
13250
13633
|
.map((bar, idx) => Math.abs(bar.close - analysisWindow[idx].close));
|
|
13251
|
-
|
|
13252
|
-
|
|
13253
|
-
|
|
13634
|
+
// A single-bar window produces no price changes to average, and a
|
|
13635
|
+
// non-positive reference close cannot scale one — `0 / 0` and `x / 0` make
|
|
13636
|
+
// the relative volatility NaN or Infinity. Volatility is the sole input to
|
|
13637
|
+
// both the pivot sensitivity and the level-grouping gap below, so a
|
|
13638
|
+
// non-finite value silently disables every comparison that depends on it
|
|
13639
|
+
// (each is false against NaN). Unmeasurable volatility resolves to zero,
|
|
13640
|
+
// under which each pivot stands as its own level instead of being merged on
|
|
13641
|
+
// a meaningless ratio.
|
|
13642
|
+
const referenceClose = analysisWindow[0].close;
|
|
13643
|
+
const avgPriceChange = priceChanges.length > 0
|
|
13644
|
+
? priceChanges.reduce((sum, change) => sum + change, 0) /
|
|
13645
|
+
priceChanges.length
|
|
13646
|
+
: 0;
|
|
13647
|
+
const volatility = referenceClose > 0 && Number.isFinite(avgPriceChange)
|
|
13648
|
+
? avgPriceChange / referenceClose
|
|
13649
|
+
: 0; // Relative volatility
|
|
13254
13650
|
// **Adjust Sensitivity and minGapBetweenLevels Dynamically**
|
|
13255
13651
|
const sensitivity = volatility * 2; // Adjust the multiplier as needed
|
|
13256
13652
|
const minGapBetweenLevels = volatility * 100; // Convert to percentage
|
|
@@ -13259,8 +13655,16 @@ function calculateSupportAndResistance(priceData, { maxLevels = 5, lookbackPerio
|
|
|
13259
13655
|
const curr = analysisWindow[j];
|
|
13260
13656
|
const prevBar = analysisWindow[j - 1];
|
|
13261
13657
|
const nextBar = analysisWindow[j + 1];
|
|
13658
|
+
// A pivot is matched against existing candidates by a *relative* gap
|
|
13659
|
+
// measured against its own price, so a non-positive reference price makes
|
|
13660
|
+
// that ratio meaningless: zero divides to NaN or Infinity (which never
|
|
13661
|
+
// compares below the sensitivity, so the pivot never merges), and a
|
|
13662
|
+
// negative price inverts the comparison (so everything merges). A bar
|
|
13663
|
+
// without a positive high or low carries no tradeable level either way.
|
|
13262
13664
|
// Check for high pivot
|
|
13263
|
-
if (curr.high >
|
|
13665
|
+
if (curr.high > 0 &&
|
|
13666
|
+
curr.high > prevBar.high &&
|
|
13667
|
+
curr.high > nextBar.high) {
|
|
13264
13668
|
const existingPivot = pivotPoints.find((p) => Math.abs(p.price - curr.high) / curr.high < sensitivity);
|
|
13265
13669
|
if (existingPivot) {
|
|
13266
13670
|
existingPivot.count++;
|
|
@@ -13271,7 +13675,7 @@ function calculateSupportAndResistance(priceData, { maxLevels = 5, lookbackPerio
|
|
|
13271
13675
|
}
|
|
13272
13676
|
}
|
|
13273
13677
|
// Check for low pivot
|
|
13274
|
-
if (curr.low < prevBar.low && curr.low < nextBar.low) {
|
|
13678
|
+
if (curr.low > 0 && curr.low < prevBar.low && curr.low < nextBar.low) {
|
|
13275
13679
|
const existingPivot = pivotPoints.find((p) => Math.abs(p.price - curr.low) / curr.low < sensitivity);
|
|
13276
13680
|
if (existingPivot) {
|
|
13277
13681
|
existingPivot.count++;
|
|
@@ -13301,33 +13705,17 @@ function calculateSupportAndResistance(priceData, { maxLevels = 5, lookbackPerio
|
|
|
13301
13705
|
}
|
|
13302
13706
|
else {
|
|
13303
13707
|
// Process current group
|
|
13304
|
-
|
|
13305
|
-
|
|
13306
|
-
|
|
13307
|
-
totalVolume;
|
|
13308
|
-
const totalStrength = currentGroup.reduce((sum, p) => sum + p.count * (p.volume / totalVolume), 0);
|
|
13309
|
-
levels.push({
|
|
13310
|
-
price: parseFloat(avgPrice.toFixed(2)),
|
|
13311
|
-
strength: parseFloat(totalStrength.toFixed(2)),
|
|
13312
|
-
type: avgPrice > currentPrice ? "resistance" : "support",
|
|
13313
|
-
});
|
|
13314
|
-
}
|
|
13708
|
+
const level = aggregatePivotCluster(currentGroup, currentPrice);
|
|
13709
|
+
if (level)
|
|
13710
|
+
levels.push(level);
|
|
13315
13711
|
currentGroup = [pivotPoints[j]];
|
|
13316
13712
|
}
|
|
13317
13713
|
}
|
|
13318
13714
|
}
|
|
13319
13715
|
// Process final group
|
|
13320
|
-
|
|
13321
|
-
|
|
13322
|
-
|
|
13323
|
-
totalVolume;
|
|
13324
|
-
const totalStrength = currentGroup.reduce((sum, p) => sum + p.count * (p.volume / totalVolume), 0);
|
|
13325
|
-
levels.push({
|
|
13326
|
-
price: parseFloat(avgPrice.toFixed(2)),
|
|
13327
|
-
strength: parseFloat(totalStrength.toFixed(2)),
|
|
13328
|
-
type: avgPrice > currentPrice ? "resistance" : "support",
|
|
13329
|
-
});
|
|
13330
|
-
}
|
|
13716
|
+
const finalGroupLevel = aggregatePivotCluster(currentGroup, currentPrice);
|
|
13717
|
+
if (finalGroupLevel)
|
|
13718
|
+
levels.push(finalGroupLevel);
|
|
13331
13719
|
// Sort by strength and limit
|
|
13332
13720
|
const finalLevels = levels
|
|
13333
13721
|
.sort((a, b) => b.strength - a.strength)
|
|
@@ -53774,7 +54162,7 @@ async function createTrailingStop(client, params) {
|
|
|
53774
54162
|
log$g(`Trailing stop creation failed for ${params.symbol}: ${err.message}`, {
|
|
53775
54163
|
type: "error",
|
|
53776
54164
|
});
|
|
53777
|
-
throw new Error(`Failed to create trailing stop for ${params.symbol}: ${err.message}`);
|
|
54165
|
+
throw enrichAlpacaError(new Error(`Failed to create trailing stop for ${params.symbol}: ${err.message}`), error);
|
|
53778
54166
|
}
|
|
53779
54167
|
}
|
|
53780
54168
|
/**
|
|
@@ -53840,7 +54228,11 @@ async function updateTrailingStop(client, orderId, updates) {
|
|
|
53840
54228
|
log$g(`Trailing stop update failed for ${orderId}: ${err.message}`, {
|
|
53841
54229
|
type: "error",
|
|
53842
54230
|
});
|
|
53843
|
-
|
|
54231
|
+
// Preserve Alpaca's `response.data` (numeric code `42210000` etc.) that the
|
|
54232
|
+
// SDK reduces to a bare "status code NNN" message. This is THE trailing-stop
|
|
54233
|
+
// modify path; dropping the code here left the consumer unable to tell a
|
|
54234
|
+
// stale-order reject from a benign race, blind-failing the profit lock.
|
|
54235
|
+
throw enrichAlpacaError(new Error(`Failed to update trailing stop ${orderId}: ${err.message}`), error);
|
|
53844
54236
|
}
|
|
53845
54237
|
}
|
|
53846
54238
|
/**
|
|
@@ -53881,7 +54273,7 @@ async function getTrailingStopHWM(client, orderId) {
|
|
|
53881
54273
|
log$g(`Failed to get trailing stop HWM for ${orderId}: ${err.message}`, {
|
|
53882
54274
|
type: "error",
|
|
53883
54275
|
});
|
|
53884
|
-
throw new Error(`Failed to get trailing stop HWM for ${orderId}: ${err.message}`);
|
|
54276
|
+
throw enrichAlpacaError(new Error(`Failed to get trailing stop HWM for ${orderId}: ${err.message}`), error);
|
|
53885
54277
|
}
|
|
53886
54278
|
}
|
|
53887
54279
|
/**
|
|
@@ -53910,12 +54302,12 @@ async function cancelTrailingStop(client, orderId) {
|
|
|
53910
54302
|
log$g(`Trailing stop ${orderId} is not cancelable (may already be filled or canceled)`, {
|
|
53911
54303
|
type: "warn",
|
|
53912
54304
|
});
|
|
53913
|
-
throw new Error(`Trailing stop ${orderId} is not cancelable: order may already be filled or canceled`);
|
|
54305
|
+
throw enrichAlpacaError(new Error(`Trailing stop ${orderId} is not cancelable: order may already be filled or canceled`), error);
|
|
53914
54306
|
}
|
|
53915
54307
|
log$g(`Failed to cancel trailing stop ${orderId}: ${err.message}`, {
|
|
53916
54308
|
type: "error",
|
|
53917
54309
|
});
|
|
53918
|
-
throw new Error(`Failed to cancel trailing stop ${orderId}: ${err.message}`);
|
|
54310
|
+
throw enrichAlpacaError(new Error(`Failed to cancel trailing stop ${orderId}: ${err.message}`), error);
|
|
53919
54311
|
}
|
|
53920
54312
|
}
|
|
53921
54313
|
/**
|
|
@@ -53999,9 +54391,14 @@ async function createPortfolioTrailingStops(client, params) {
|
|
|
53999
54391
|
}
|
|
54000
54392
|
catch (err) {
|
|
54001
54393
|
const errorMessage = err.message;
|
|
54002
|
-
|
|
54394
|
+
// Preserve the broker's numeric code (e.g. 42210000) rather than
|
|
54395
|
+
// reducing the swallowed per-item failure to its flattened message —
|
|
54396
|
+
// this loop only logs failures, so the log is the preservation target.
|
|
54397
|
+
const brokerCode = getAlpacaBrokerErrorCode(err);
|
|
54398
|
+
errors.push({ symbol, error: errorMessage, brokerCode });
|
|
54003
54399
|
log$g(`Failed to create trailing stop for ${symbol}: ${errorMessage}`, {
|
|
54004
54400
|
type: "error",
|
|
54401
|
+
metadata: { brokerCode },
|
|
54005
54402
|
});
|
|
54006
54403
|
}
|
|
54007
54404
|
}
|
|
@@ -54011,7 +54408,9 @@ async function createPortfolioTrailingStops(client, params) {
|
|
|
54011
54408
|
const skippedCount = positions.length - successCount - failureCount;
|
|
54012
54409
|
log$g(`Portfolio trailing stops complete: ${successCount} created, ${failureCount} failed, ${skippedCount} skipped`, { type: "info" });
|
|
54013
54410
|
if (errors.length > 0) {
|
|
54014
|
-
log$g(`Failed symbols: ${errors
|
|
54411
|
+
log$g(`Failed symbols: ${errors
|
|
54412
|
+
.map((e) => `${e.symbol} (${e.error}${e.brokerCode !== null ? `, code ${e.brokerCode}` : ""})`)
|
|
54413
|
+
.join(", ")}`, {
|
|
54015
54414
|
type: "warn",
|
|
54016
54415
|
});
|
|
54017
54416
|
}
|
|
@@ -54022,7 +54421,7 @@ async function createPortfolioTrailingStops(client, params) {
|
|
|
54022
54421
|
log$g(`Failed to create portfolio trailing stops: ${err.message}`, {
|
|
54023
54422
|
type: "error",
|
|
54024
54423
|
});
|
|
54025
|
-
throw new Error(`Failed to create portfolio trailing stops: ${err.message}`);
|
|
54424
|
+
throw enrichAlpacaError(new Error(`Failed to create portfolio trailing stops: ${err.message}`), error);
|
|
54026
54425
|
}
|
|
54027
54426
|
}
|
|
54028
54427
|
/**
|
|
@@ -54061,7 +54460,7 @@ async function getOpenTrailingStops(client, symbol) {
|
|
|
54061
54460
|
catch (error) {
|
|
54062
54461
|
const err = error;
|
|
54063
54462
|
log$g(`Failed to get open trailing stops: ${err.message}`, { type: "error" });
|
|
54064
|
-
throw new Error(`Failed to get open trailing stops: ${err.message}`);
|
|
54463
|
+
throw enrichAlpacaError(new Error(`Failed to get open trailing stops: ${err.message}`), error);
|
|
54065
54464
|
}
|
|
54066
54465
|
}
|
|
54067
54466
|
/**
|
|
@@ -54109,7 +54508,10 @@ async function cancelTrailingStopsForSymbol(client, symbol) {
|
|
|
54109
54508
|
canceledCount++;
|
|
54110
54509
|
}
|
|
54111
54510
|
catch (err) {
|
|
54112
|
-
|
|
54511
|
+
// Keep the broker's numeric code alongside the message so the swallowed
|
|
54512
|
+
// per-item cancel failure stays diagnosable in the summary log.
|
|
54513
|
+
const brokerCode = getAlpacaBrokerErrorCode(err);
|
|
54514
|
+
errors.push(`${order.id}: ${err.message}${brokerCode !== null ? ` (code ${brokerCode})` : ""}`);
|
|
54113
54515
|
}
|
|
54114
54516
|
}
|
|
54115
54517
|
if (errors.length > 0) {
|
|
@@ -58346,7 +58748,12 @@ async function resolveDuplicateSubmission(client, clientOrderId, symbol, cause)
|
|
|
58346
58748
|
catch (lookupError) {
|
|
58347
58749
|
const reason = lookupError instanceof Error ? lookupError.message : String(lookupError);
|
|
58348
58750
|
log$6(`Duplicate-order lookup failed for ${clientOrderId}; failing closed (no resubmit): ${reason}`, { type: "error", symbol, metadata: { clientOrderId } });
|
|
58349
|
-
|
|
58751
|
+
// The typed error represents the ORIGINAL duplicate rejection, so its broker
|
|
58752
|
+
// payload must come from `cause` (the 422), not from the lookup failure.
|
|
58753
|
+
// Chain the lookup error ahead of the original 422 (and carry the 422's
|
|
58754
|
+
// normalized detail onto it) so both are diagnosable and
|
|
58755
|
+
// getAlpacaBrokerErrorCode still resolves the duplicate code.
|
|
58756
|
+
throw new DuplicateClientOrderIdError(`Duplicate client_order_id "${clientOrderId}" rejected by Alpaca and the existing-order lookup failed; refusing to resubmit (possible live duplicate)`, clientOrderId, false, enrichAlpacaError(lookupError instanceof Error ? lookupError : new Error(reason), cause));
|
|
58350
58757
|
}
|
|
58351
58758
|
if (existing && !TERMINAL_DEAD_ORDER_STATUSES.has(existing.status)) {
|
|
58352
58759
|
log$6(`client_order_id ${clientOrderId} already submitted (status=${existing.status}); returning existing order ${existing.id} as idempotent success`, {
|
|
@@ -58480,7 +58887,7 @@ async function createOrder(client, params) {
|
|
|
58480
58887
|
symbol,
|
|
58481
58888
|
metadata: { params: submission },
|
|
58482
58889
|
});
|
|
58483
|
-
throw new Error(`Failed to create ${type} order for ${symbol}: ${errorMessage}`);
|
|
58890
|
+
throw enrichAlpacaError(new Error(`Failed to create ${type} order for ${symbol}: ${errorMessage}`), error);
|
|
58484
58891
|
}
|
|
58485
58892
|
}
|
|
58486
58893
|
/**
|
|
@@ -58509,7 +58916,7 @@ async function getOrder(client, orderId) {
|
|
|
58509
58916
|
catch (error) {
|
|
58510
58917
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
58511
58918
|
log$6(`Failed to fetch order ${orderId}: ${errorMessage}`, { type: "error" });
|
|
58512
|
-
throw new Error(`Failed to fetch order ${orderId}: ${errorMessage}`);
|
|
58919
|
+
throw enrichAlpacaError(new Error(`Failed to fetch order ${orderId}: ${errorMessage}`), error);
|
|
58513
58920
|
}
|
|
58514
58921
|
}
|
|
58515
58922
|
/**
|
|
@@ -58572,7 +58979,7 @@ async function getOrders(client, params = {}) {
|
|
|
58572
58979
|
catch (error) {
|
|
58573
58980
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
58574
58981
|
log$6(`Failed to fetch orders: ${errorMessage}`, { type: "error" });
|
|
58575
|
-
throw new Error(`Failed to fetch orders: ${errorMessage}`);
|
|
58982
|
+
throw enrichAlpacaError(new Error(`Failed to fetch orders: ${errorMessage}`), error);
|
|
58576
58983
|
}
|
|
58577
58984
|
}
|
|
58578
58985
|
/**
|
|
@@ -58602,16 +59009,16 @@ async function cancelOrder(client, orderId) {
|
|
|
58602
59009
|
log$6(`Order ${orderId} is not cancelable (may already be filled or canceled)`, {
|
|
58603
59010
|
type: "warn",
|
|
58604
59011
|
});
|
|
58605
|
-
throw new Error(`Order ${orderId} is not cancelable`);
|
|
59012
|
+
throw enrichAlpacaError(new Error(`Order ${orderId} is not cancelable`), error);
|
|
58606
59013
|
}
|
|
58607
59014
|
if (errorMessage.includes("404") || errorMessage.includes("not found")) {
|
|
58608
59015
|
log$6(`Order ${orderId} not found`, { type: "error" });
|
|
58609
|
-
throw new Error(`Order ${orderId} not found`);
|
|
59016
|
+
throw enrichAlpacaError(new Error(`Order ${orderId} not found`), error);
|
|
58610
59017
|
}
|
|
58611
59018
|
log$6(`Failed to cancel order ${orderId}: ${errorMessage}`, {
|
|
58612
59019
|
type: "error",
|
|
58613
59020
|
});
|
|
58614
|
-
throw new Error(`Failed to cancel order ${orderId}: ${errorMessage}`);
|
|
59021
|
+
throw enrichAlpacaError(new Error(`Failed to cancel order ${orderId}: ${errorMessage}`), error);
|
|
58615
59022
|
}
|
|
58616
59023
|
}
|
|
58617
59024
|
/**
|
|
@@ -58654,7 +59061,7 @@ async function cancelAllOrders(client) {
|
|
|
58654
59061
|
catch (error) {
|
|
58655
59062
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
58656
59063
|
log$6(`Failed to cancel all orders: ${errorMessage}`, { type: "error" });
|
|
58657
|
-
throw new Error(`Failed to cancel all orders: ${errorMessage}`);
|
|
59064
|
+
throw enrichAlpacaError(new Error(`Failed to cancel all orders: ${errorMessage}`), error);
|
|
58658
59065
|
}
|
|
58659
59066
|
}
|
|
58660
59067
|
/**
|
|
@@ -58712,16 +59119,16 @@ async function replaceOrder(client, orderId, params) {
|
|
|
58712
59119
|
log$6(`Order ${orderId} cannot be replaced (may already be filled)`, {
|
|
58713
59120
|
type: "error",
|
|
58714
59121
|
});
|
|
58715
|
-
throw new Error(`Order ${orderId} cannot be replaced: order may already be filled or canceled`);
|
|
59122
|
+
throw enrichAlpacaError(new Error(`Order ${orderId} cannot be replaced: order may already be filled or canceled`), error);
|
|
58716
59123
|
}
|
|
58717
59124
|
if (errorMessage.includes("404")) {
|
|
58718
59125
|
log$6(`Order ${orderId} not found`, { type: "error" });
|
|
58719
|
-
throw new Error(`Order ${orderId} not found`);
|
|
59126
|
+
throw enrichAlpacaError(new Error(`Order ${orderId} not found`), error);
|
|
58720
59127
|
}
|
|
58721
59128
|
log$6(`Failed to replace order ${orderId}: ${errorMessage}`, {
|
|
58722
59129
|
type: "error",
|
|
58723
59130
|
});
|
|
58724
|
-
throw new Error(`Failed to replace order ${orderId}: ${errorMessage}`);
|
|
59131
|
+
throw enrichAlpacaError(new Error(`Failed to replace order ${orderId}: ${errorMessage}`), error);
|
|
58725
59132
|
}
|
|
58726
59133
|
}
|
|
58727
59134
|
/**
|
|
@@ -58810,7 +59217,7 @@ async function getOrderByClientId(client, clientOrderId) {
|
|
|
58810
59217
|
log$6(`Failed to fetch order by client_order_id ${clientOrderId}: ${errorMessage}`, {
|
|
58811
59218
|
type: "error",
|
|
58812
59219
|
});
|
|
58813
|
-
throw new Error(`Failed to fetch order by client_order_id ${clientOrderId}: ${errorMessage}`);
|
|
59220
|
+
throw enrichAlpacaError(new Error(`Failed to fetch order by client_order_id ${clientOrderId}: ${errorMessage}`), error);
|
|
58814
59221
|
}
|
|
58815
59222
|
}
|
|
58816
59223
|
|
|
@@ -71770,8 +72177,10 @@ exports.createTimeoutSignal = createTimeoutSignal;
|
|
|
71770
72177
|
exports.createTrailingStop = createTrailingStop;
|
|
71771
72178
|
exports.createVerticalSpread = createVerticalSpread$1;
|
|
71772
72179
|
exports.createVerticalSpreadAdvanced = createVerticalSpread;
|
|
72180
|
+
exports.enrichAlpacaError = enrichAlpacaError;
|
|
71773
72181
|
exports.entryWithPercentStopLoss = entryWithPercentStopLoss;
|
|
71774
72182
|
exports.exerciseOption = exerciseOption;
|
|
72183
|
+
exports.extractAlpacaBrokerError = extractAlpacaBrokerError;
|
|
71775
72184
|
exports.extractGreeks = extractGreeks;
|
|
71776
72185
|
exports.filterByExpiration = filterByExpiration;
|
|
71777
72186
|
exports.filterByStrike = filterByStrike;
|
|
@@ -71789,6 +72198,8 @@ exports.getAccountDetails = getAccountDetails;
|
|
|
71789
72198
|
exports.getAccountSummary = getAccountSummary;
|
|
71790
72199
|
exports.getAgentPoolStatus = getAgentPoolStatus;
|
|
71791
72200
|
exports.getAllOrders = getAllOrders;
|
|
72201
|
+
exports.getAlpacaBrokerErrorCode = getAlpacaBrokerErrorCode;
|
|
72202
|
+
exports.getAlpacaBrokerErrorDetail = getAlpacaBrokerErrorDetail;
|
|
71792
72203
|
exports.getAlpacaCalendar = getAlpacaCalendar;
|
|
71793
72204
|
exports.getAlpacaClock = getAlpacaClock;
|
|
71794
72205
|
exports.getAverageDailyVolume = getAverageDailyVolume;
|