@adaptic/utils 0.1.41 → 0.1.42
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 +325 -207
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +323 -208
- package/dist/index.mjs.map +1 -1
- package/dist/types/alpaca/index.d.ts +2 -0
- package/dist/types/alpaca/index.d.ts.map +1 -1
- package/dist/types/alpaca/trading/clock.d.ts +99 -0
- package/dist/types/alpaca/trading/clock.d.ts.map +1 -0
- package/dist/types/alpaca/trading/index.d.ts +2 -0
- package/dist/types/alpaca/trading/index.d.ts.map +1 -1
- package/dist/types/index.d.ts +6 -2
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -12260,13 +12260,13 @@ class DisplayManager {
|
|
|
12260
12260
|
* @param options.symbol The trading symbol associated with this log.
|
|
12261
12261
|
* @param options.logToFile Force logging to a file even when no symbol is provided.
|
|
12262
12262
|
*/
|
|
12263
|
-
function log$
|
|
12263
|
+
function log$m(message, options = { source: "Server", type: "info" }) {
|
|
12264
12264
|
const displayManager = DisplayManager.getInstance();
|
|
12265
12265
|
displayManager.log(message, options);
|
|
12266
12266
|
}
|
|
12267
12267
|
|
|
12268
|
-
const log$
|
|
12269
|
-
log$
|
|
12268
|
+
const log$l = (message, options = { type: "info" }) => {
|
|
12269
|
+
log$m(message, { ...options, source: "AlpacaMarketDataAPI" });
|
|
12270
12270
|
};
|
|
12271
12271
|
// Default settings for market data API
|
|
12272
12272
|
const DEFAULT_ADJUSTMENT = "all";
|
|
@@ -12396,7 +12396,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12396
12396
|
this.cryptoWs = ws;
|
|
12397
12397
|
}
|
|
12398
12398
|
ws.on("open", () => {
|
|
12399
|
-
log$
|
|
12399
|
+
log$l(`${streamType} stream connected`, { type: "info" });
|
|
12400
12400
|
const authMessage = {
|
|
12401
12401
|
action: "auth",
|
|
12402
12402
|
key: process.env.ALPACA_API_KEY,
|
|
@@ -12411,36 +12411,36 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12411
12411
|
messages = JSON.parse(rawData);
|
|
12412
12412
|
}
|
|
12413
12413
|
catch (e) {
|
|
12414
|
-
log$
|
|
12414
|
+
log$l(`${streamType} stream received invalid JSON: ${rawData.substring(0, 200)}`, { type: "error" });
|
|
12415
12415
|
return;
|
|
12416
12416
|
}
|
|
12417
12417
|
for (const message of messages) {
|
|
12418
12418
|
if (message.T === "success" && message.msg === "authenticated") {
|
|
12419
|
-
log$
|
|
12419
|
+
log$l(`${streamType} stream authenticated`, { type: "info" });
|
|
12420
12420
|
this.sendSubscription(streamType);
|
|
12421
12421
|
}
|
|
12422
12422
|
else if (message.T === "success" && message.msg === "connected") {
|
|
12423
|
-
log$
|
|
12423
|
+
log$l(`${streamType} stream connected message received`, {
|
|
12424
12424
|
type: "debug",
|
|
12425
12425
|
});
|
|
12426
12426
|
}
|
|
12427
12427
|
else if (message.T === "subscription") {
|
|
12428
|
-
log$
|
|
12428
|
+
log$l(`${streamType} subscription confirmed: trades=${message.trades?.length || 0}, quotes=${message.quotes?.length || 0}, bars=${message.bars?.length || 0}`, { type: "info" });
|
|
12429
12429
|
}
|
|
12430
12430
|
else if (message.T === "error") {
|
|
12431
|
-
log$
|
|
12431
|
+
log$l(`${streamType} stream error: ${message.msg} (code: ${message.code}, raw: ${JSON.stringify(message)})`, { type: "error" });
|
|
12432
12432
|
}
|
|
12433
12433
|
else if (message.S) {
|
|
12434
12434
|
super.emit(`${streamType}-${message.T}`, message);
|
|
12435
12435
|
super.emit(`${streamType}-data`, message);
|
|
12436
12436
|
}
|
|
12437
12437
|
else {
|
|
12438
|
-
log$
|
|
12438
|
+
log$l(`${streamType} received unknown message type: ${JSON.stringify(message)}`, { type: "debug" });
|
|
12439
12439
|
}
|
|
12440
12440
|
}
|
|
12441
12441
|
});
|
|
12442
12442
|
ws.on("close", () => {
|
|
12443
|
-
log$
|
|
12443
|
+
log$l(`${streamType} stream disconnected`, { type: "warn" });
|
|
12444
12444
|
if (streamType === "stock") {
|
|
12445
12445
|
this.stockWs = null;
|
|
12446
12446
|
}
|
|
@@ -12453,7 +12453,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12453
12453
|
// Optional: implement reconnect logic
|
|
12454
12454
|
});
|
|
12455
12455
|
ws.on("error", (error) => {
|
|
12456
|
-
log$
|
|
12456
|
+
log$l(`${streamType} stream error: ${error.message}`, { type: "error" });
|
|
12457
12457
|
});
|
|
12458
12458
|
}
|
|
12459
12459
|
sendSubscription(streamType) {
|
|
@@ -12471,7 +12471,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12471
12471
|
ws = this.cryptoWs;
|
|
12472
12472
|
subscriptions = this.cryptoSubscriptions;
|
|
12473
12473
|
}
|
|
12474
|
-
log$
|
|
12474
|
+
log$l(`sendSubscription called for ${streamType} (wsReady=${ws?.readyState === WebSocket.OPEN}, trades=${subscriptions.trades?.length || 0}, quotes=${subscriptions.quotes?.length || 0}, bars=${subscriptions.bars?.length || 0})`, {
|
|
12475
12475
|
type: "debug",
|
|
12476
12476
|
});
|
|
12477
12477
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
@@ -12491,19 +12491,19 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12491
12491
|
...subMessagePayload,
|
|
12492
12492
|
};
|
|
12493
12493
|
const messageJson = JSON.stringify(subMessage);
|
|
12494
|
-
log$
|
|
12494
|
+
log$l(`Sending ${streamType} subscription: ${messageJson}`, {
|
|
12495
12495
|
type: "info",
|
|
12496
12496
|
});
|
|
12497
12497
|
ws.send(messageJson);
|
|
12498
12498
|
}
|
|
12499
12499
|
else {
|
|
12500
|
-
log$
|
|
12500
|
+
log$l(`No ${streamType} subscriptions to send (all arrays empty)`, {
|
|
12501
12501
|
type: "debug",
|
|
12502
12502
|
});
|
|
12503
12503
|
}
|
|
12504
12504
|
}
|
|
12505
12505
|
else {
|
|
12506
|
-
log$
|
|
12506
|
+
log$l(`Cannot send ${streamType} subscription: WebSocket not ready`, {
|
|
12507
12507
|
type: "warn",
|
|
12508
12508
|
});
|
|
12509
12509
|
}
|
|
@@ -12633,7 +12633,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12633
12633
|
});
|
|
12634
12634
|
if (!response.ok) {
|
|
12635
12635
|
const errorText = await response.text();
|
|
12636
|
-
log$
|
|
12636
|
+
log$l(`Market Data API error (${response.status}): ${errorText}`, {
|
|
12637
12637
|
type: "error",
|
|
12638
12638
|
});
|
|
12639
12639
|
throw new Error(`Market Data API error (${response.status}): ${errorText}`);
|
|
@@ -12643,9 +12643,9 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12643
12643
|
}
|
|
12644
12644
|
catch (err) {
|
|
12645
12645
|
const error = err;
|
|
12646
|
-
log$
|
|
12646
|
+
log$l(`Error in makeRequest: ${error.message}. Endpoint: ${endpoint}. Url: ${url.toString()}`, { type: "error" });
|
|
12647
12647
|
if (error instanceof TypeError) {
|
|
12648
|
-
log$
|
|
12648
|
+
log$l(`Network error details: ${error.stack}`, { type: "error" });
|
|
12649
12649
|
}
|
|
12650
12650
|
throw error;
|
|
12651
12651
|
}
|
|
@@ -12669,7 +12669,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12669
12669
|
symbols.forEach((symbol) => {
|
|
12670
12670
|
allBars[symbol] = [];
|
|
12671
12671
|
});
|
|
12672
|
-
log$
|
|
12672
|
+
log$l(`Starting historical bars fetch for ${symbolsStr} (${params.timeframe}, ${params.start || "no start"} to ${params.end || "no end"})`, {
|
|
12673
12673
|
type: "info",
|
|
12674
12674
|
});
|
|
12675
12675
|
while (hasMorePages) {
|
|
@@ -12682,7 +12682,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12682
12682
|
};
|
|
12683
12683
|
const response = await this.makeRequest("/stocks/bars", "GET", requestParams);
|
|
12684
12684
|
if (!response.bars) {
|
|
12685
|
-
log$
|
|
12685
|
+
log$l(`No bars data found in response for ${symbolsStr}`, {
|
|
12686
12686
|
type: "warn",
|
|
12687
12687
|
});
|
|
12688
12688
|
break;
|
|
@@ -12718,12 +12718,12 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12718
12718
|
const dateRangeStr = earliestTimestamp && latestTimestamp
|
|
12719
12719
|
? `${earliestTimestamp.toLocaleDateString("en-US", { timeZone: "America/New_York" })} to ${latestTimestamp.toLocaleDateString("en-US", { timeZone: "America/New_York" })}`
|
|
12720
12720
|
: "unknown range";
|
|
12721
|
-
log$
|
|
12721
|
+
log$l(`Page ${pageCount}: Fetched ${pageBarsCount.toLocaleString()} bars (total: ${totalBarsCount.toLocaleString()}) for ${symbolsStr}, date range: ${dateRangeStr}${hasMorePages ? ", more pages available" : ", complete"}`, {
|
|
12722
12722
|
type: "info",
|
|
12723
12723
|
});
|
|
12724
12724
|
// Prevent infinite loops
|
|
12725
12725
|
if (pageCount > 1000) {
|
|
12726
|
-
log$
|
|
12726
|
+
log$l(`Stopping pagination after ${pageCount} pages to prevent infinite loop`, { type: "warn" });
|
|
12727
12727
|
break;
|
|
12728
12728
|
}
|
|
12729
12729
|
}
|
|
@@ -12731,7 +12731,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12731
12731
|
const symbolCounts = Object.entries(allBars)
|
|
12732
12732
|
.map(([symbol, bars]) => `${symbol}: ${bars.length}`)
|
|
12733
12733
|
.join(", ");
|
|
12734
|
-
log$
|
|
12734
|
+
log$l(`Historical bars fetch complete: ${totalBarsCount.toLocaleString()} total bars across ${pageCount} pages (${symbolCounts})`, {
|
|
12735
12735
|
type: "info",
|
|
12736
12736
|
});
|
|
12737
12737
|
return {
|
|
@@ -12787,7 +12787,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12787
12787
|
async getLatestQuotes(symbols, feed, currency) {
|
|
12788
12788
|
// Return empty response if symbols array is empty to avoid API error
|
|
12789
12789
|
if (!symbols || symbols.length === 0) {
|
|
12790
|
-
log$
|
|
12790
|
+
log$l("No symbols provided to getLatestQuotes, returning empty response", {
|
|
12791
12791
|
type: "warn",
|
|
12792
12792
|
});
|
|
12793
12793
|
return {
|
|
@@ -12831,7 +12831,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
12831
12831
|
limit: 1,
|
|
12832
12832
|
});
|
|
12833
12833
|
if (!response.bars[symbol] || response.bars[symbol].length === 0) {
|
|
12834
|
-
log$
|
|
12834
|
+
log$l(`No previous close data available for ${symbol}`, {
|
|
12835
12835
|
type: "error",
|
|
12836
12836
|
symbol,
|
|
12837
12837
|
});
|
|
@@ -13008,7 +13008,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
13008
13008
|
symbols.forEach((symbol) => {
|
|
13009
13009
|
allBars[symbol] = [];
|
|
13010
13010
|
});
|
|
13011
|
-
log$
|
|
13011
|
+
log$l(`Starting historical options bars fetch for ${symbolsStr} (${params.timeframe}, ${params.start || "no start"} to ${params.end || "no end"})`, {
|
|
13012
13012
|
type: "info",
|
|
13013
13013
|
});
|
|
13014
13014
|
while (hasMorePages) {
|
|
@@ -13019,7 +13019,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
13019
13019
|
};
|
|
13020
13020
|
const response = await this.makeRequest("/options/bars", "GET", requestParams, "v1beta1");
|
|
13021
13021
|
if (!response.bars) {
|
|
13022
|
-
log$
|
|
13022
|
+
log$l(`No options bars data found in response for ${symbolsStr}`, {
|
|
13023
13023
|
type: "warn",
|
|
13024
13024
|
});
|
|
13025
13025
|
break;
|
|
@@ -13051,12 +13051,12 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
13051
13051
|
const dateRangeStr = earliestTimestamp && latestTimestamp
|
|
13052
13052
|
? `${earliestTimestamp.toLocaleDateString("en-US", { timeZone: "America/New_York" })} to ${latestTimestamp.toLocaleDateString("en-US", { timeZone: "America/New_York" })}`
|
|
13053
13053
|
: "unknown range";
|
|
13054
|
-
log$
|
|
13054
|
+
log$l(`Page ${pageCount}: Fetched ${pageBarsCount.toLocaleString()} option bars (total: ${totalBarsCount.toLocaleString()}) for ${symbolsStr}, date range: ${dateRangeStr}${hasMorePages ? ", more pages available" : ", complete"}`, {
|
|
13055
13055
|
type: "info",
|
|
13056
13056
|
});
|
|
13057
13057
|
// Prevent infinite loops
|
|
13058
13058
|
if (pageCount > 1000) {
|
|
13059
|
-
log$
|
|
13059
|
+
log$l(`Stopping options bars pagination after ${pageCount} pages to prevent infinite loop`, { type: "warn" });
|
|
13060
13060
|
break;
|
|
13061
13061
|
}
|
|
13062
13062
|
}
|
|
@@ -13064,7 +13064,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
13064
13064
|
const symbolCounts = Object.entries(allBars)
|
|
13065
13065
|
.map(([symbol, bars]) => `${symbol}: ${bars.length}`)
|
|
13066
13066
|
.join(", ");
|
|
13067
|
-
log$
|
|
13067
|
+
log$l(`Historical options bars fetch complete: ${totalBarsCount.toLocaleString()} total bars across ${pageCount} pages (${symbolCounts})`, {
|
|
13068
13068
|
type: "info",
|
|
13069
13069
|
});
|
|
13070
13070
|
return {
|
|
@@ -13092,7 +13092,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
13092
13092
|
symbols.forEach((symbol) => {
|
|
13093
13093
|
allTrades[symbol] = [];
|
|
13094
13094
|
});
|
|
13095
|
-
log$
|
|
13095
|
+
log$l(`Starting historical options trades fetch for ${symbolsStr} (${params.start || "no start"} to ${params.end || "no end"})`, {
|
|
13096
13096
|
type: "info",
|
|
13097
13097
|
});
|
|
13098
13098
|
while (hasMorePages) {
|
|
@@ -13103,7 +13103,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
13103
13103
|
};
|
|
13104
13104
|
const response = await this.makeRequest("/options/trades", "GET", requestParams, "v1beta1");
|
|
13105
13105
|
if (!response.trades) {
|
|
13106
|
-
log$
|
|
13106
|
+
log$l(`No options trades data found in response for ${symbolsStr}`, {
|
|
13107
13107
|
type: "warn",
|
|
13108
13108
|
});
|
|
13109
13109
|
break;
|
|
@@ -13135,12 +13135,12 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
13135
13135
|
const dateRangeStr = earliestTimestamp && latestTimestamp
|
|
13136
13136
|
? `${earliestTimestamp.toLocaleDateString("en-US", { timeZone: "America/New_York" })} to ${latestTimestamp.toLocaleDateString("en-US", { timeZone: "America/New_York" })}`
|
|
13137
13137
|
: "unknown range";
|
|
13138
|
-
log$
|
|
13138
|
+
log$l(`Page ${pageCount}: Fetched ${pageTradesCount.toLocaleString()} option trades (total: ${totalTradesCount.toLocaleString()}) for ${symbolsStr}, date range: ${dateRangeStr}${hasMorePages ? ", more pages available" : ", complete"}`, {
|
|
13139
13139
|
type: "info",
|
|
13140
13140
|
});
|
|
13141
13141
|
// Prevent infinite loops
|
|
13142
13142
|
if (pageCount > 1000) {
|
|
13143
|
-
log$
|
|
13143
|
+
log$l(`Stopping options trades pagination after ${pageCount} pages to prevent infinite loop`, { type: "warn" });
|
|
13144
13144
|
break;
|
|
13145
13145
|
}
|
|
13146
13146
|
}
|
|
@@ -13148,7 +13148,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
13148
13148
|
const symbolCounts = Object.entries(allTrades)
|
|
13149
13149
|
.map(([symbol, trades]) => `${symbol}: ${trades.length}`)
|
|
13150
13150
|
.join(", ");
|
|
13151
|
-
log$
|
|
13151
|
+
log$l(`Historical options trades fetch complete: ${totalTradesCount.toLocaleString()} total trades across ${pageCount} pages (${symbolCounts})`, {
|
|
13152
13152
|
type: "info",
|
|
13153
13153
|
});
|
|
13154
13154
|
return {
|
|
@@ -13308,14 +13308,14 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
13308
13308
|
...(pageToken && { page_token: pageToken }),
|
|
13309
13309
|
});
|
|
13310
13310
|
const url = `${this.v1beta1url}/news?${queryParams}`;
|
|
13311
|
-
log$
|
|
13311
|
+
log$l(`Fetching news from: ${url}`, { type: "debug", symbol });
|
|
13312
13312
|
const response = await fetch(url, {
|
|
13313
13313
|
method: "GET",
|
|
13314
13314
|
headers: this.headers,
|
|
13315
13315
|
});
|
|
13316
13316
|
if (!response.ok) {
|
|
13317
13317
|
const errorText = await response.text();
|
|
13318
|
-
log$
|
|
13318
|
+
log$l(`Alpaca news API error (${response.status}): ${errorText}`, {
|
|
13319
13319
|
type: "error",
|
|
13320
13320
|
symbol,
|
|
13321
13321
|
});
|
|
@@ -13323,7 +13323,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
13323
13323
|
}
|
|
13324
13324
|
const data = await response.json();
|
|
13325
13325
|
if (!data.news || !Array.isArray(data.news)) {
|
|
13326
|
-
log$
|
|
13326
|
+
log$l(`No news data found in Alpaca response for ${symbol}`, {
|
|
13327
13327
|
type: "warn",
|
|
13328
13328
|
symbol,
|
|
13329
13329
|
});
|
|
@@ -13345,7 +13345,7 @@ class AlpacaMarketDataAPI extends EventEmitter {
|
|
|
13345
13345
|
fetchedCount = newsArticles.length;
|
|
13346
13346
|
pageToken = data.next_page_token || null;
|
|
13347
13347
|
hasMorePages = !!pageToken && (!maxLimit || fetchedCount < maxLimit);
|
|
13348
|
-
log$
|
|
13348
|
+
log$l(`Fetched ${transformedNews.length} news articles (total: ${fetchedCount}) for ${symbol}. More pages: ${hasMorePages}`, { type: "debug", symbol });
|
|
13349
13349
|
if (maxLimit && fetchedCount >= maxLimit) {
|
|
13350
13350
|
newsArticles = newsArticles.slice(0, maxLimit);
|
|
13351
13351
|
break;
|
|
@@ -13422,7 +13422,7 @@ class AlpacaTradingAPI {
|
|
|
13422
13422
|
if (this.debugLogging && options.type === "debug") {
|
|
13423
13423
|
return;
|
|
13424
13424
|
}
|
|
13425
|
-
log$
|
|
13425
|
+
log$m(message, {
|
|
13426
13426
|
...options,
|
|
13427
13427
|
source: "AlpacaTradingAPI",
|
|
13428
13428
|
account: this.credentials.accountName,
|
|
@@ -37006,19 +37006,19 @@ function requireCalendar () {
|
|
|
37006
37006
|
return calendar;
|
|
37007
37007
|
}
|
|
37008
37008
|
|
|
37009
|
-
var clock;
|
|
37009
|
+
var clock$2;
|
|
37010
37010
|
var hasRequiredClock;
|
|
37011
37011
|
|
|
37012
37012
|
function requireClock () {
|
|
37013
|
-
if (hasRequiredClock) return clock;
|
|
37013
|
+
if (hasRequiredClock) return clock$2;
|
|
37014
37014
|
hasRequiredClock = 1;
|
|
37015
37015
|
function get() {
|
|
37016
37016
|
return this.sendRequest("/clock");
|
|
37017
37017
|
}
|
|
37018
|
-
clock = {
|
|
37018
|
+
clock$2 = {
|
|
37019
37019
|
get,
|
|
37020
37020
|
};
|
|
37021
|
-
return clock;
|
|
37021
|
+
return clock$2;
|
|
37022
37022
|
}
|
|
37023
37023
|
|
|
37024
37024
|
var asset;
|
|
@@ -53225,8 +53225,8 @@ var Alpaca = /*@__PURE__*/getDefaultExportFromCjs(distExports);
|
|
|
53225
53225
|
* Alpaca SDK Client Factory
|
|
53226
53226
|
* Provides unified access to Alpaca Trading API using official SDK
|
|
53227
53227
|
*/
|
|
53228
|
-
const log$
|
|
53229
|
-
log$
|
|
53228
|
+
const log$k = (message, options = { type: "info" }) => {
|
|
53229
|
+
log$m(message, { ...options, source: "AlpacaClient" });
|
|
53230
53230
|
};
|
|
53231
53231
|
/**
|
|
53232
53232
|
* AlpacaClient wraps the official SDK with additional features:
|
|
@@ -53257,7 +53257,7 @@ class AlpacaClient {
|
|
|
53257
53257
|
"APCA-API-SECRET-KEY": config.apiSecret,
|
|
53258
53258
|
"Content-Type": "application/json",
|
|
53259
53259
|
};
|
|
53260
|
-
log$
|
|
53260
|
+
log$k(`AlpacaClient initialized (${config.accountType} mode)`, {
|
|
53261
53261
|
type: "info",
|
|
53262
53262
|
});
|
|
53263
53263
|
}
|
|
@@ -53295,7 +53295,7 @@ class AlpacaClient {
|
|
|
53295
53295
|
}
|
|
53296
53296
|
catch (error) {
|
|
53297
53297
|
this.isConnected = false;
|
|
53298
|
-
log$
|
|
53298
|
+
log$k(`Credential validation failed: ${error.message}`, {
|
|
53299
53299
|
type: "error",
|
|
53300
53300
|
});
|
|
53301
53301
|
throw error;
|
|
@@ -53355,7 +53355,7 @@ class AlpacaClient {
|
|
|
53355
53355
|
}
|
|
53356
53356
|
catch (error) {
|
|
53357
53357
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
53358
|
-
log$
|
|
53358
|
+
log$k(`API request to ${endpoint} failed: ${errorMessage}`, {
|
|
53359
53359
|
type: "error",
|
|
53360
53360
|
});
|
|
53361
53361
|
throw error;
|
|
@@ -53371,7 +53371,7 @@ const clientCache = new Map();
|
|
|
53371
53371
|
function createAlpacaClient(config) {
|
|
53372
53372
|
const cacheKey = `${config.apiKey}-${config.accountType}`;
|
|
53373
53373
|
if (clientCache.has(cacheKey)) {
|
|
53374
|
-
log$
|
|
53374
|
+
log$k(`Returning cached client for ${config.accountType}`, { type: "debug" });
|
|
53375
53375
|
return clientCache.get(cacheKey);
|
|
53376
53376
|
}
|
|
53377
53377
|
const client = new AlpacaClient(config);
|
|
@@ -53399,7 +53399,7 @@ function createClientFromEnv() {
|
|
|
53399
53399
|
*/
|
|
53400
53400
|
function clearClientCache() {
|
|
53401
53401
|
clientCache.clear();
|
|
53402
|
-
log$
|
|
53402
|
+
log$k("Client cache cleared", { type: "info" });
|
|
53403
53403
|
}
|
|
53404
53404
|
|
|
53405
53405
|
// src/alpaca/trading/bracket-orders.ts
|
|
@@ -53409,8 +53409,8 @@ function clearClientCache() {
|
|
|
53409
53409
|
* @param message - The message to log.
|
|
53410
53410
|
* @param options - Optional logging options.
|
|
53411
53411
|
*/
|
|
53412
|
-
const log$
|
|
53413
|
-
log$
|
|
53412
|
+
const log$j = (message, options = { type: "info" }) => {
|
|
53413
|
+
log$m(message, { ...options, source: "BracketOrders" });
|
|
53414
53414
|
};
|
|
53415
53415
|
/**
|
|
53416
53416
|
* Validates bracket order parameters.
|
|
@@ -53439,13 +53439,13 @@ function validateBracketOrderParams(params) {
|
|
|
53439
53439
|
// For a buy order, take profit should be higher than entry, stop loss lower
|
|
53440
53440
|
params.limitPrice || params.takeProfit.limitPrice; // Use a reference price
|
|
53441
53441
|
if (params.takeProfit.limitPrice <= params.stopLoss.stopPrice) {
|
|
53442
|
-
log$
|
|
53442
|
+
log$j("Warning: Take profit price should typically be higher than stop loss price for buy orders", { type: "warn" });
|
|
53443
53443
|
}
|
|
53444
53444
|
}
|
|
53445
53445
|
else {
|
|
53446
53446
|
// For a sell order, take profit should be lower than entry, stop loss higher
|
|
53447
53447
|
if (params.takeProfit.limitPrice >= params.stopLoss.stopPrice) {
|
|
53448
|
-
log$
|
|
53448
|
+
log$j("Warning: Take profit price should typically be lower than stop loss price for sell orders", { type: "warn" });
|
|
53449
53449
|
}
|
|
53450
53450
|
}
|
|
53451
53451
|
}
|
|
@@ -53492,12 +53492,12 @@ function roundPriceForAlpaca$4(price) {
|
|
|
53492
53492
|
* ```
|
|
53493
53493
|
*/
|
|
53494
53494
|
async function createBracketOrder(executor, params) {
|
|
53495
|
-
log$
|
|
53495
|
+
log$j(`Creating bracket order: ${params.side} ${params.qty} ${params.symbol}`, {
|
|
53496
53496
|
type: "info",
|
|
53497
53497
|
});
|
|
53498
|
-
log$
|
|
53499
|
-
log$
|
|
53500
|
-
log$
|
|
53498
|
+
log$j(` Entry: ${params.type}${params.limitPrice ? ` @ $${params.limitPrice}` : ""}`, { type: "debug" });
|
|
53499
|
+
log$j(` Take Profit: $${params.takeProfit.limitPrice}`, { type: "debug" });
|
|
53500
|
+
log$j(` Stop Loss: $${params.stopLoss.stopPrice}${params.stopLoss.limitPrice ? ` (limit $${params.stopLoss.limitPrice})` : ""}`, { type: "debug" });
|
|
53501
53501
|
// Validate parameters
|
|
53502
53502
|
validateBracketOrderParams(params);
|
|
53503
53503
|
try {
|
|
@@ -53533,8 +53533,8 @@ async function createBracketOrder(executor, params) {
|
|
|
53533
53533
|
}
|
|
53534
53534
|
// Execute the order
|
|
53535
53535
|
const order = await executor.createOrder(orderParams);
|
|
53536
|
-
log$
|
|
53537
|
-
log$
|
|
53536
|
+
log$j(`Bracket order created successfully: ${order.id}`, { type: "info" });
|
|
53537
|
+
log$j(` Order status: ${order.status}`, { type: "debug" });
|
|
53538
53538
|
// Parse the legs from the response
|
|
53539
53539
|
const legs = order.legs || [];
|
|
53540
53540
|
// Find take profit leg - it's a limit order at the take profit price
|
|
@@ -53543,10 +53543,10 @@ async function createBracketOrder(executor, params) {
|
|
|
53543
53543
|
// Find stop loss leg - it's a stop or stop_limit order
|
|
53544
53544
|
const stopLossLeg = legs.find((leg) => leg.type === "stop" || leg.type === "stop_limit") || null;
|
|
53545
53545
|
if (takeProfitLeg) {
|
|
53546
|
-
log$
|
|
53546
|
+
log$j(` Take profit leg ID: ${takeProfitLeg.id}`, { type: "debug" });
|
|
53547
53547
|
}
|
|
53548
53548
|
if (stopLossLeg) {
|
|
53549
|
-
log$
|
|
53549
|
+
log$j(` Stop loss leg ID: ${stopLossLeg.id}`, { type: "debug" });
|
|
53550
53550
|
}
|
|
53551
53551
|
return {
|
|
53552
53552
|
entryOrder: order,
|
|
@@ -53557,7 +53557,7 @@ async function createBracketOrder(executor, params) {
|
|
|
53557
53557
|
}
|
|
53558
53558
|
catch (error) {
|
|
53559
53559
|
const err = error;
|
|
53560
|
-
log$
|
|
53560
|
+
log$j(`Bracket order failed: ${err.message}`, { type: "error" });
|
|
53561
53561
|
throw new Error(`Failed to create bracket order for ${params.symbol}: ${err.message}`);
|
|
53562
53562
|
}
|
|
53563
53563
|
}
|
|
@@ -53589,9 +53589,9 @@ async function createBracketOrder(executor, params) {
|
|
|
53589
53589
|
* ```
|
|
53590
53590
|
*/
|
|
53591
53591
|
async function createProtectiveBracket(executor, params) {
|
|
53592
|
-
log$
|
|
53593
|
-
log$
|
|
53594
|
-
log$
|
|
53592
|
+
log$j(`Creating protective bracket for ${params.symbol}: ${params.qty} shares`, { type: "info" });
|
|
53593
|
+
log$j(` Take Profit: $${params.takeProfit.limitPrice}`, { type: "debug" });
|
|
53594
|
+
log$j(` Stop Loss: $${params.stopLoss.stopPrice}${params.stopLoss.limitPrice ? ` (limit $${params.stopLoss.limitPrice})` : ""}`, { type: "debug" });
|
|
53595
53595
|
// Validate parameters
|
|
53596
53596
|
if (!params.symbol || params.symbol.trim() === "") {
|
|
53597
53597
|
throw new Error("Symbol is required for protective bracket");
|
|
@@ -53607,7 +53607,7 @@ async function createProtectiveBracket(executor, params) {
|
|
|
53607
53607
|
}
|
|
53608
53608
|
// For a protective sell bracket, take profit should be higher than stop loss
|
|
53609
53609
|
if (params.takeProfit.limitPrice <= params.stopLoss.stopPrice) {
|
|
53610
|
-
log$
|
|
53610
|
+
log$j("Warning: Take profit price should be higher than stop loss price for protective sell bracket", { type: "warn" });
|
|
53611
53611
|
}
|
|
53612
53612
|
try {
|
|
53613
53613
|
// Build the OCO order parameters
|
|
@@ -53628,7 +53628,7 @@ async function createProtectiveBracket(executor, params) {
|
|
|
53628
53628
|
};
|
|
53629
53629
|
// Execute the order
|
|
53630
53630
|
const order = await executor.createOrder(orderParams);
|
|
53631
|
-
log$
|
|
53631
|
+
log$j(`Protective bracket created successfully: ${order.id}`, {
|
|
53632
53632
|
type: "info",
|
|
53633
53633
|
});
|
|
53634
53634
|
// Parse the legs from the response
|
|
@@ -53646,7 +53646,7 @@ async function createProtectiveBracket(executor, params) {
|
|
|
53646
53646
|
}
|
|
53647
53647
|
catch (error) {
|
|
53648
53648
|
const err = error;
|
|
53649
|
-
log$
|
|
53649
|
+
log$j(`Protective bracket failed: ${err.message}`, { type: "error" });
|
|
53650
53650
|
throw new Error(`Failed to create protective bracket for ${params.symbol}: ${err.message}`);
|
|
53651
53651
|
}
|
|
53652
53652
|
}
|
|
@@ -53684,8 +53684,8 @@ var bracketOrders$1 = /*#__PURE__*/Object.freeze({
|
|
|
53684
53684
|
default: bracketOrders
|
|
53685
53685
|
});
|
|
53686
53686
|
|
|
53687
|
-
const log$
|
|
53688
|
-
log$
|
|
53687
|
+
const log$i = (message, options = { type: "info" }) => {
|
|
53688
|
+
log$m(message, { ...options, source: "Account" });
|
|
53689
53689
|
};
|
|
53690
53690
|
/**
|
|
53691
53691
|
* Get account details from Alpaca
|
|
@@ -53693,16 +53693,16 @@ const log$h = (message, options = { type: "info" }) => {
|
|
|
53693
53693
|
* @returns Promise resolving to account details
|
|
53694
53694
|
*/
|
|
53695
53695
|
async function getAccountDetails(client) {
|
|
53696
|
-
log$
|
|
53696
|
+
log$i("Fetching account details");
|
|
53697
53697
|
try {
|
|
53698
53698
|
const sdk = client.getSDK();
|
|
53699
53699
|
const account = await sdk.getAccount();
|
|
53700
|
-
log$
|
|
53700
|
+
log$i(`Account details fetched successfully for account ${account.account_number}`);
|
|
53701
53701
|
return account;
|
|
53702
53702
|
}
|
|
53703
53703
|
catch (error) {
|
|
53704
53704
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
53705
|
-
log$
|
|
53705
|
+
log$i(`Failed to fetch account details: ${errorMessage}`, { type: "error" });
|
|
53706
53706
|
throw error;
|
|
53707
53707
|
}
|
|
53708
53708
|
}
|
|
@@ -53712,16 +53712,16 @@ async function getAccountDetails(client) {
|
|
|
53712
53712
|
* @returns Promise resolving to account configuration
|
|
53713
53713
|
*/
|
|
53714
53714
|
async function getAccountConfiguration(client) {
|
|
53715
|
-
log$
|
|
53715
|
+
log$i("Fetching account configuration");
|
|
53716
53716
|
try {
|
|
53717
53717
|
const sdk = client.getSDK();
|
|
53718
53718
|
const config = await sdk.getAccountConfigurations();
|
|
53719
|
-
log$
|
|
53719
|
+
log$i("Account configuration fetched successfully");
|
|
53720
53720
|
return config;
|
|
53721
53721
|
}
|
|
53722
53722
|
catch (error) {
|
|
53723
53723
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
53724
|
-
log$
|
|
53724
|
+
log$i(`Failed to fetch account configuration: ${errorMessage}`, {
|
|
53725
53725
|
type: "error",
|
|
53726
53726
|
});
|
|
53727
53727
|
throw error;
|
|
@@ -53734,16 +53734,16 @@ async function getAccountConfiguration(client) {
|
|
|
53734
53734
|
* @returns Promise resolving to updated account configuration
|
|
53735
53735
|
*/
|
|
53736
53736
|
async function updateAccountConfiguration(client, config) {
|
|
53737
|
-
log$
|
|
53737
|
+
log$i("Updating account configuration");
|
|
53738
53738
|
try {
|
|
53739
53739
|
const sdk = client.getSDK();
|
|
53740
53740
|
const updatedConfig = await sdk.updateAccountConfigurations(config);
|
|
53741
|
-
log$
|
|
53741
|
+
log$i("Account configuration updated successfully");
|
|
53742
53742
|
return updatedConfig;
|
|
53743
53743
|
}
|
|
53744
53744
|
catch (error) {
|
|
53745
53745
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
53746
|
-
log$
|
|
53746
|
+
log$i(`Failed to update account configuration: ${errorMessage}`, {
|
|
53747
53747
|
type: "error",
|
|
53748
53748
|
});
|
|
53749
53749
|
throw error;
|
|
@@ -53756,17 +53756,17 @@ async function updateAccountConfiguration(client, config) {
|
|
|
53756
53756
|
* @returns Promise resolving to portfolio history response
|
|
53757
53757
|
*/
|
|
53758
53758
|
async function getPortfolioHistory(client, params) {
|
|
53759
|
-
log$
|
|
53759
|
+
log$i(`Fetching portfolio history with period: ${params.period || "default"}, timeframe: ${params.timeframe || "default"}`);
|
|
53760
53760
|
try {
|
|
53761
53761
|
const sdk = client.getSDK();
|
|
53762
53762
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
53763
53763
|
const history = await sdk.getPortfolioHistory(params);
|
|
53764
|
-
log$
|
|
53764
|
+
log$i(`Portfolio history fetched successfully with ${history.equity?.length || 0} data points`);
|
|
53765
53765
|
return history;
|
|
53766
53766
|
}
|
|
53767
53767
|
catch (error) {
|
|
53768
53768
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
53769
|
-
log$
|
|
53769
|
+
log$i(`Failed to fetch portfolio history: ${errorMessage}`, {
|
|
53770
53770
|
type: "error",
|
|
53771
53771
|
});
|
|
53772
53772
|
throw error;
|
|
@@ -53778,7 +53778,7 @@ async function getPortfolioHistory(client, params) {
|
|
|
53778
53778
|
* @returns Promise resolving to trading eligibility status
|
|
53779
53779
|
*/
|
|
53780
53780
|
async function checkTradingEligibility(client) {
|
|
53781
|
-
log$
|
|
53781
|
+
log$i("Checking trading eligibility");
|
|
53782
53782
|
try {
|
|
53783
53783
|
const account = await getAccountDetails(client);
|
|
53784
53784
|
const reasons = [];
|
|
@@ -53817,12 +53817,12 @@ async function checkTradingEligibility(client) {
|
|
|
53817
53817
|
dayTradeCount: account.daytrade_count,
|
|
53818
53818
|
isPatternDayTrader: account.pattern_day_trader,
|
|
53819
53819
|
};
|
|
53820
|
-
log$
|
|
53820
|
+
log$i(`Trading eligibility check complete: canTrade=${canTrade}${reasons.length > 0 ? `, reasons: ${reasons.join("; ")}` : ""}`);
|
|
53821
53821
|
return eligibility;
|
|
53822
53822
|
}
|
|
53823
53823
|
catch (error) {
|
|
53824
53824
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
53825
|
-
log$
|
|
53825
|
+
log$i(`Failed to check trading eligibility: ${errorMessage}`, {
|
|
53826
53826
|
type: "error",
|
|
53827
53827
|
});
|
|
53828
53828
|
throw error;
|
|
@@ -53834,7 +53834,7 @@ async function checkTradingEligibility(client) {
|
|
|
53834
53834
|
* @returns Promise resolving to buying power breakdown
|
|
53835
53835
|
*/
|
|
53836
53836
|
async function getBuyingPower(client) {
|
|
53837
|
-
log$
|
|
53837
|
+
log$i("Fetching buying power breakdown");
|
|
53838
53838
|
try {
|
|
53839
53839
|
const account = await getAccountDetails(client);
|
|
53840
53840
|
const breakdown = {
|
|
@@ -53846,12 +53846,12 @@ async function getBuyingPower(client) {
|
|
|
53846
53846
|
// Crypto buying power is typically equal to cash for spot trading
|
|
53847
53847
|
cryptoBuyingPower: parseFloat(account.cash),
|
|
53848
53848
|
};
|
|
53849
|
-
log$
|
|
53849
|
+
log$i(`Buying power breakdown: cash=$${breakdown.cash.toFixed(2)}, dayTrading=$${breakdown.dayTradingBuyingPower.toFixed(2)}, regT=$${breakdown.regtBuyingPower.toFixed(2)}`);
|
|
53850
53850
|
return breakdown;
|
|
53851
53851
|
}
|
|
53852
53852
|
catch (error) {
|
|
53853
53853
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
53854
|
-
log$
|
|
53854
|
+
log$i(`Failed to fetch buying power: ${errorMessage}`, { type: "error" });
|
|
53855
53855
|
throw error;
|
|
53856
53856
|
}
|
|
53857
53857
|
}
|
|
@@ -53861,16 +53861,16 @@ async function getBuyingPower(client) {
|
|
|
53861
53861
|
* @returns Promise resolving to options trading level (0-3)
|
|
53862
53862
|
*/
|
|
53863
53863
|
async function getOptionsTradingLevel(client) {
|
|
53864
|
-
log$
|
|
53864
|
+
log$i("Fetching options trading level");
|
|
53865
53865
|
try {
|
|
53866
53866
|
const account = await getAccountDetails(client);
|
|
53867
53867
|
const level = account.options_trading_level || 0;
|
|
53868
|
-
log$
|
|
53868
|
+
log$i(`Options trading level: ${level}`);
|
|
53869
53869
|
return level;
|
|
53870
53870
|
}
|
|
53871
53871
|
catch (error) {
|
|
53872
53872
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
53873
|
-
log$
|
|
53873
|
+
log$i(`Failed to fetch options trading level: ${errorMessage}`, {
|
|
53874
53874
|
type: "error",
|
|
53875
53875
|
});
|
|
53876
53876
|
throw error;
|
|
@@ -53882,7 +53882,7 @@ async function getOptionsTradingLevel(client) {
|
|
|
53882
53882
|
* @returns Promise resolving to PDT status
|
|
53883
53883
|
*/
|
|
53884
53884
|
async function getPDTStatus(client) {
|
|
53885
|
-
log$
|
|
53885
|
+
log$i("Fetching PDT status");
|
|
53886
53886
|
try {
|
|
53887
53887
|
const account = await getAccountDetails(client);
|
|
53888
53888
|
const equity = parseFloat(account.equity);
|
|
@@ -53915,12 +53915,12 @@ async function getPDTStatus(client) {
|
|
|
53915
53915
|
dayTradesRemaining: dayTradesRemaining === Infinity ? -1 : dayTradesRemaining, // Use -1 for unlimited
|
|
53916
53916
|
canDayTrade,
|
|
53917
53917
|
};
|
|
53918
|
-
log$
|
|
53918
|
+
log$i(`PDT status: isPDT=${isPDT}, dayTradeCount=${dayTradeCount}, remaining=${dayTradesRemaining === Infinity ? "unlimited" : dayTradesRemaining}`);
|
|
53919
53919
|
return status;
|
|
53920
53920
|
}
|
|
53921
53921
|
catch (error) {
|
|
53922
53922
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
53923
|
-
log$
|
|
53923
|
+
log$i(`Failed to fetch PDT status: ${errorMessage}`, { type: "error" });
|
|
53924
53924
|
throw error;
|
|
53925
53925
|
}
|
|
53926
53926
|
}
|
|
@@ -53932,7 +53932,7 @@ async function getPDTStatus(client) {
|
|
|
53932
53932
|
* @returns Promise resolving to array of daily returns
|
|
53933
53933
|
*/
|
|
53934
53934
|
async function getDailyReturns(client, period = "1M") {
|
|
53935
|
-
log$
|
|
53935
|
+
log$i(`Calculating daily returns for period: ${period}`);
|
|
53936
53936
|
try {
|
|
53937
53937
|
const history = await getPortfolioHistory(client, {
|
|
53938
53938
|
period,
|
|
@@ -53941,7 +53941,7 @@ async function getDailyReturns(client, period = "1M") {
|
|
|
53941
53941
|
if (!history.timestamp ||
|
|
53942
53942
|
!history.equity ||
|
|
53943
53943
|
history.timestamp.length === 0) {
|
|
53944
|
-
log$
|
|
53944
|
+
log$i("No portfolio history data available", { type: "warn" });
|
|
53945
53945
|
return [];
|
|
53946
53946
|
}
|
|
53947
53947
|
const dailyReturns = [];
|
|
@@ -53964,12 +53964,12 @@ async function getDailyReturns(client, period = "1M") {
|
|
|
53964
53964
|
dailyReturn,
|
|
53965
53965
|
});
|
|
53966
53966
|
}
|
|
53967
|
-
log$
|
|
53967
|
+
log$i(`Calculated ${dailyReturns.length} daily returns`);
|
|
53968
53968
|
return dailyReturns;
|
|
53969
53969
|
}
|
|
53970
53970
|
catch (error) {
|
|
53971
53971
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
53972
|
-
log$
|
|
53972
|
+
log$i(`Failed to calculate daily returns: ${errorMessage}`, {
|
|
53973
53973
|
type: "error",
|
|
53974
53974
|
});
|
|
53975
53975
|
throw error;
|
|
@@ -53982,7 +53982,7 @@ async function getDailyReturns(client, period = "1M") {
|
|
|
53982
53982
|
* @returns Promise resolving to period performance metrics
|
|
53983
53983
|
*/
|
|
53984
53984
|
async function calculatePeriodPerformance(client, period = "1M") {
|
|
53985
|
-
log$
|
|
53985
|
+
log$i(`Calculating period performance for: ${period}`);
|
|
53986
53986
|
try {
|
|
53987
53987
|
const dailyReturns = await getDailyReturns(client, period);
|
|
53988
53988
|
if (dailyReturns.length < 2) {
|
|
@@ -54048,12 +54048,12 @@ async function calculatePeriodPerformance(client, period = "1M") {
|
|
|
54048
54048
|
losingDays,
|
|
54049
54049
|
winRate,
|
|
54050
54050
|
};
|
|
54051
|
-
log$
|
|
54051
|
+
log$i(`Period performance: totalReturn=${totalReturnPct.toFixed(2)}%, maxDrawdown=${maxDrawdownPct.toFixed(2)}%, sharpe=${sharpeRatio?.toFixed(2) || "N/A"}`);
|
|
54052
54052
|
return performance;
|
|
54053
54053
|
}
|
|
54054
54054
|
catch (error) {
|
|
54055
54055
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
54056
|
-
log$
|
|
54056
|
+
log$i(`Failed to calculate period performance: ${errorMessage}`, {
|
|
54057
54057
|
type: "error",
|
|
54058
54058
|
});
|
|
54059
54059
|
throw error;
|
|
@@ -54066,13 +54066,13 @@ async function calculatePeriodPerformance(client, period = "1M") {
|
|
|
54066
54066
|
* @returns Promise resolving to equity curve data points
|
|
54067
54067
|
*/
|
|
54068
54068
|
async function getEquityCurve(client, params = { period: "1M", timeframe: "1D" }) {
|
|
54069
|
-
log$
|
|
54069
|
+
log$i(`Fetching equity curve with period: ${params.period || "default"}`);
|
|
54070
54070
|
try {
|
|
54071
54071
|
const history = await getPortfolioHistory(client, params);
|
|
54072
54072
|
if (!history.timestamp ||
|
|
54073
54073
|
!history.equity ||
|
|
54074
54074
|
history.timestamp.length === 0) {
|
|
54075
|
-
log$
|
|
54075
|
+
log$i("No portfolio history data available for equity curve", {
|
|
54076
54076
|
type: "warn",
|
|
54077
54077
|
});
|
|
54078
54078
|
return [];
|
|
@@ -54094,12 +54094,12 @@ async function getEquityCurve(client, params = { period: "1M", timeframe: "1D" }
|
|
|
54094
54094
|
cumulativeReturn,
|
|
54095
54095
|
});
|
|
54096
54096
|
}
|
|
54097
|
-
log$
|
|
54097
|
+
log$i(`Generated equity curve with ${curve.length} data points`);
|
|
54098
54098
|
return curve;
|
|
54099
54099
|
}
|
|
54100
54100
|
catch (error) {
|
|
54101
54101
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
54102
|
-
log$
|
|
54102
|
+
log$i(`Failed to get equity curve: ${errorMessage}`, { type: "error" });
|
|
54103
54103
|
throw error;
|
|
54104
54104
|
}
|
|
54105
54105
|
}
|
|
@@ -54109,7 +54109,7 @@ async function getEquityCurve(client, params = { period: "1M", timeframe: "1D" }
|
|
|
54109
54109
|
* @returns Promise resolving to account summary
|
|
54110
54110
|
*/
|
|
54111
54111
|
async function getAccountSummary(client) {
|
|
54112
|
-
log$
|
|
54112
|
+
log$i("Fetching account summary");
|
|
54113
54113
|
try {
|
|
54114
54114
|
const account = await getAccountDetails(client);
|
|
54115
54115
|
const equity = parseFloat(account.equity);
|
|
@@ -54126,12 +54126,12 @@ async function getAccountSummary(client) {
|
|
|
54126
54126
|
todayProfitLoss,
|
|
54127
54127
|
todayProfitLossPct,
|
|
54128
54128
|
};
|
|
54129
|
-
log$
|
|
54129
|
+
log$i(`Account summary: equity=$${summary.equity.toFixed(2)}, cash=$${summary.cash.toFixed(2)}, todayP/L=${summary.todayProfitLossPct.toFixed(2)}%`);
|
|
54130
54130
|
return summary;
|
|
54131
54131
|
}
|
|
54132
54132
|
catch (error) {
|
|
54133
54133
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
54134
|
-
log$
|
|
54134
|
+
log$i(`Failed to get account summary: ${errorMessage}`, { type: "error" });
|
|
54135
54135
|
throw error;
|
|
54136
54136
|
}
|
|
54137
54137
|
}
|
|
@@ -54141,17 +54141,17 @@ async function getAccountSummary(client) {
|
|
|
54141
54141
|
* @returns Promise resolving to boolean indicating margin status
|
|
54142
54142
|
*/
|
|
54143
54143
|
async function isMarginAccount(client) {
|
|
54144
|
-
log$
|
|
54144
|
+
log$i("Checking margin account status");
|
|
54145
54145
|
try {
|
|
54146
54146
|
const account = await getAccountDetails(client);
|
|
54147
54147
|
// Multiplier > 1 indicates margin account
|
|
54148
54148
|
const isMargin = account.multiplier !== "1";
|
|
54149
|
-
log$
|
|
54149
|
+
log$i(`Margin account: ${isMargin} (multiplier: ${account.multiplier})`);
|
|
54150
54150
|
return isMargin;
|
|
54151
54151
|
}
|
|
54152
54152
|
catch (error) {
|
|
54153
54153
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
54154
|
-
log$
|
|
54154
|
+
log$i(`Failed to check margin account status: ${errorMessage}`, {
|
|
54155
54155
|
type: "error",
|
|
54156
54156
|
});
|
|
54157
54157
|
throw error;
|
|
@@ -54163,7 +54163,7 @@ async function isMarginAccount(client) {
|
|
|
54163
54163
|
* @returns Promise resolving to margin information
|
|
54164
54164
|
*/
|
|
54165
54165
|
async function getMarginInfo(client) {
|
|
54166
|
-
log$
|
|
54166
|
+
log$i("Fetching margin information");
|
|
54167
54167
|
try {
|
|
54168
54168
|
const account = await getAccountDetails(client);
|
|
54169
54169
|
const initialMargin = parseFloat(account.initial_margin);
|
|
@@ -54179,12 +54179,12 @@ async function getMarginInfo(client) {
|
|
|
54179
54179
|
sma: parseFloat(account.sma),
|
|
54180
54180
|
marginCallAmount,
|
|
54181
54181
|
};
|
|
54182
|
-
log$
|
|
54182
|
+
log$i(`Margin info: multiplier=${marginInfo.multiplier}, initialMargin=$${marginInfo.initialMargin.toFixed(2)}, maintenanceMargin=$${marginInfo.maintenanceMargin.toFixed(2)}`);
|
|
54183
54183
|
return marginInfo;
|
|
54184
54184
|
}
|
|
54185
54185
|
catch (error) {
|
|
54186
54186
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
54187
|
-
log$
|
|
54187
|
+
log$i(`Failed to get margin information: ${errorMessage}`, { type: "error" });
|
|
54188
54188
|
throw error;
|
|
54189
54189
|
}
|
|
54190
54190
|
}
|
|
@@ -54232,8 +54232,8 @@ var account$1 = /*#__PURE__*/Object.freeze({
|
|
|
54232
54232
|
*
|
|
54233
54233
|
* @module order-utils
|
|
54234
54234
|
*/
|
|
54235
|
-
const log$
|
|
54236
|
-
log$
|
|
54235
|
+
const log$h = (message, options = { type: "info" }) => {
|
|
54236
|
+
log$m(message, { ...options, source: "OrderUtils" });
|
|
54237
54237
|
};
|
|
54238
54238
|
/**
|
|
54239
54239
|
* Default delay between pagination requests to avoid rate limits (in milliseconds)
|
|
@@ -54327,7 +54327,7 @@ function buildOrderQueryParams(params) {
|
|
|
54327
54327
|
async function getOrdersBySymbol(client, symbol, params = {}) {
|
|
54328
54328
|
const sdk = client.getSDK();
|
|
54329
54329
|
try {
|
|
54330
|
-
log$
|
|
54330
|
+
log$h(`Fetching orders for symbol: ${symbol}`, {
|
|
54331
54331
|
type: "debug",
|
|
54332
54332
|
metadata: { symbol, ...params },
|
|
54333
54333
|
});
|
|
@@ -54350,14 +54350,14 @@ async function getOrdersBySymbol(client, symbol, params = {}) {
|
|
|
54350
54350
|
if (params.side)
|
|
54351
54351
|
queryParams.side = params.side;
|
|
54352
54352
|
const orders = await sdk.getOrders(queryParams);
|
|
54353
|
-
log$
|
|
54353
|
+
log$h(`Found ${orders.length} orders for ${symbol}`, {
|
|
54354
54354
|
type: "debug",
|
|
54355
54355
|
metadata: { symbol, count: orders.length },
|
|
54356
54356
|
});
|
|
54357
54357
|
return orders;
|
|
54358
54358
|
}
|
|
54359
54359
|
catch (error) {
|
|
54360
|
-
log$
|
|
54360
|
+
log$h(`Error fetching orders for symbol ${symbol}: ${error.message}`, {
|
|
54361
54361
|
type: "error",
|
|
54362
54362
|
metadata: { symbol, error: error.message },
|
|
54363
54363
|
});
|
|
@@ -54380,7 +54380,7 @@ async function getOrdersBySymbol(client, symbol, params = {}) {
|
|
|
54380
54380
|
async function getOpenOrders$1(client, params = {}) {
|
|
54381
54381
|
const sdk = client.getSDK();
|
|
54382
54382
|
try {
|
|
54383
|
-
log$
|
|
54383
|
+
log$h("Fetching open orders", { type: "debug" });
|
|
54384
54384
|
// Build query parameters as Record<string, unknown> to match SDK expectations
|
|
54385
54385
|
const queryParams = {
|
|
54386
54386
|
status: "open",
|
|
@@ -54401,14 +54401,14 @@ async function getOpenOrders$1(client, params = {}) {
|
|
|
54401
54401
|
if (params.side)
|
|
54402
54402
|
queryParams.side = params.side;
|
|
54403
54403
|
const orders = await sdk.getOrders(queryParams);
|
|
54404
|
-
log$
|
|
54404
|
+
log$h(`Found ${orders.length} open orders`, {
|
|
54405
54405
|
type: "debug",
|
|
54406
54406
|
metadata: { count: orders.length },
|
|
54407
54407
|
});
|
|
54408
54408
|
return orders;
|
|
54409
54409
|
}
|
|
54410
54410
|
catch (error) {
|
|
54411
|
-
log$
|
|
54411
|
+
log$h(`Error fetching open orders: ${error.message}`, {
|
|
54412
54412
|
type: "error",
|
|
54413
54413
|
metadata: { error: error.message },
|
|
54414
54414
|
});
|
|
@@ -54434,7 +54434,7 @@ async function getFilledOrders(client, params) {
|
|
|
54434
54434
|
client.getSDK();
|
|
54435
54435
|
const { startDate, endDate, symbols, side } = params;
|
|
54436
54436
|
try {
|
|
54437
|
-
log$
|
|
54437
|
+
log$h(`Fetching filled orders from ${startDate.toISOString()} to ${endDate.toISOString()}`, {
|
|
54438
54438
|
type: "debug",
|
|
54439
54439
|
metadata: {
|
|
54440
54440
|
startDate: startDate.toISOString(),
|
|
@@ -54459,14 +54459,14 @@ async function getFilledOrders(client, params) {
|
|
|
54459
54459
|
});
|
|
54460
54460
|
// Filter to only filled orders
|
|
54461
54461
|
const filledOrders = allOrders.filter((order) => FILLED_ORDER_STATUSES.includes(order.status));
|
|
54462
|
-
log$
|
|
54462
|
+
log$h(`Found ${filledOrders.length} filled orders in date range`, {
|
|
54463
54463
|
type: "debug",
|
|
54464
54464
|
metadata: { count: filledOrders.length },
|
|
54465
54465
|
});
|
|
54466
54466
|
return filledOrders;
|
|
54467
54467
|
}
|
|
54468
54468
|
catch (error) {
|
|
54469
|
-
log$
|
|
54469
|
+
log$h(`Error fetching filled orders: ${error.message}`, {
|
|
54470
54470
|
type: "error",
|
|
54471
54471
|
metadata: { error: error.message },
|
|
54472
54472
|
});
|
|
@@ -54503,7 +54503,7 @@ async function getOrderHistory(client, params = {}) {
|
|
|
54503
54503
|
const effectivePageSize = Math.min(pageSize, MAX_ORDERS_PER_REQUEST);
|
|
54504
54504
|
const sdk = client.getSDK();
|
|
54505
54505
|
try {
|
|
54506
|
-
log$
|
|
54506
|
+
log$h(`Fetching order history page ${page} (size: ${effectivePageSize})`, {
|
|
54507
54507
|
type: "debug",
|
|
54508
54508
|
metadata: { page, pageSize: effectivePageSize },
|
|
54509
54509
|
});
|
|
@@ -54576,7 +54576,7 @@ async function getOrderHistory(client, params = {}) {
|
|
|
54576
54576
|
};
|
|
54577
54577
|
}
|
|
54578
54578
|
catch (error) {
|
|
54579
|
-
log$
|
|
54579
|
+
log$h(`Error fetching order history: ${error.message}`, {
|
|
54580
54580
|
type: "error",
|
|
54581
54581
|
metadata: { error: error.message },
|
|
54582
54582
|
});
|
|
@@ -54616,7 +54616,7 @@ async function getAllOrders(client, params = {}) {
|
|
|
54616
54616
|
const orders = await sdk.getOrders(sdkParams);
|
|
54617
54617
|
return orders;
|
|
54618
54618
|
}
|
|
54619
|
-
log$
|
|
54619
|
+
log$h("Fetching all orders with pagination", {
|
|
54620
54620
|
type: "debug",
|
|
54621
54621
|
metadata: { params: queryParams },
|
|
54622
54622
|
});
|
|
@@ -54635,7 +54635,7 @@ async function getAllOrders(client, params = {}) {
|
|
|
54635
54635
|
const sdkParams = buildOrderQueryParams(batchParams);
|
|
54636
54636
|
const batch = (await sdk.getOrders(sdkParams));
|
|
54637
54637
|
pageCount++;
|
|
54638
|
-
log$
|
|
54638
|
+
log$h(`Fetched page ${pageCount}: ${batch.length} orders`, {
|
|
54639
54639
|
type: "debug",
|
|
54640
54640
|
metadata: { pageCount, batchSize: batch.length },
|
|
54641
54641
|
});
|
|
@@ -54660,14 +54660,14 @@ async function getAllOrders(client, params = {}) {
|
|
|
54660
54660
|
}
|
|
54661
54661
|
}
|
|
54662
54662
|
}
|
|
54663
|
-
log$
|
|
54663
|
+
log$h(`Fetched total of ${allOrders.length} orders across ${pageCount} pages`, {
|
|
54664
54664
|
type: "info",
|
|
54665
54665
|
metadata: { totalOrders: allOrders.length, pageCount },
|
|
54666
54666
|
});
|
|
54667
54667
|
return allOrders;
|
|
54668
54668
|
}
|
|
54669
54669
|
catch (error) {
|
|
54670
|
-
log$
|
|
54670
|
+
log$h(`Error fetching all orders: ${error.message}`, {
|
|
54671
54671
|
type: "error",
|
|
54672
54672
|
metadata: { error: error.message },
|
|
54673
54673
|
});
|
|
@@ -54702,7 +54702,7 @@ async function waitForOrderFill(client, params) {
|
|
|
54702
54702
|
const { orderId, timeoutMs = 60000, pollIntervalMs = 1000 } = params;
|
|
54703
54703
|
const sdk = client.getSDK();
|
|
54704
54704
|
const startTime = Date.now();
|
|
54705
|
-
log$
|
|
54705
|
+
log$h(`Waiting for order ${orderId} to fill (timeout: ${timeoutMs}ms)`, {
|
|
54706
54706
|
type: "debug",
|
|
54707
54707
|
metadata: { orderId, timeoutMs, pollIntervalMs },
|
|
54708
54708
|
});
|
|
@@ -54712,7 +54712,7 @@ async function waitForOrderFill(client, params) {
|
|
|
54712
54712
|
if (elapsed >= timeoutMs) {
|
|
54713
54713
|
// Fetch final state before returning
|
|
54714
54714
|
const order = (await sdk.getOrder(orderId));
|
|
54715
|
-
log$
|
|
54715
|
+
log$h(`Order ${orderId} timed out after ${elapsed}ms, status: ${order.status}`, {
|
|
54716
54716
|
type: "warn",
|
|
54717
54717
|
metadata: { orderId, elapsed, status: order.status },
|
|
54718
54718
|
});
|
|
@@ -54725,7 +54725,7 @@ async function waitForOrderFill(client, params) {
|
|
|
54725
54725
|
const order = (await sdk.getOrder(orderId));
|
|
54726
54726
|
// Check if filled
|
|
54727
54727
|
if (FILLED_ORDER_STATUSES.includes(order.status)) {
|
|
54728
|
-
log$
|
|
54728
|
+
log$h(`Order ${orderId} filled after ${elapsed}ms`, {
|
|
54729
54729
|
type: "info",
|
|
54730
54730
|
metadata: { orderId, elapsed, status: order.status },
|
|
54731
54731
|
});
|
|
@@ -54737,7 +54737,7 @@ async function waitForOrderFill(client, params) {
|
|
|
54737
54737
|
}
|
|
54738
54738
|
// Check if terminal but not filled
|
|
54739
54739
|
if (TERMINAL_ORDER_STATUSES.includes(order.status)) {
|
|
54740
|
-
log$
|
|
54740
|
+
log$h(`Order ${orderId} reached terminal state ${order.status} after ${elapsed}ms`, {
|
|
54741
54741
|
type: "info",
|
|
54742
54742
|
metadata: { orderId, elapsed, status: order.status },
|
|
54743
54743
|
});
|
|
@@ -54752,7 +54752,7 @@ async function waitForOrderFill(client, params) {
|
|
|
54752
54752
|
}
|
|
54753
54753
|
}
|
|
54754
54754
|
catch (error) {
|
|
54755
|
-
log$
|
|
54755
|
+
log$h(`Error waiting for order fill: ${error.message}`, {
|
|
54756
54756
|
type: "error",
|
|
54757
54757
|
metadata: { orderId, error: error.message },
|
|
54758
54758
|
});
|
|
@@ -55110,8 +55110,8 @@ const LOG_SOURCE$7 = "TrailingStops";
|
|
|
55110
55110
|
/**
|
|
55111
55111
|
* Internal logging helper with consistent source
|
|
55112
55112
|
*/
|
|
55113
|
-
const log$
|
|
55114
|
-
log$
|
|
55113
|
+
const log$g = (message, options = { type: "info" }) => {
|
|
55114
|
+
log$m(message, { ...options, source: LOG_SOURCE$7 });
|
|
55115
55115
|
};
|
|
55116
55116
|
/**
|
|
55117
55117
|
* Validation error for trailing stop parameters
|
|
@@ -55199,7 +55199,7 @@ async function createTrailingStop(client, params) {
|
|
|
55199
55199
|
const trailDescription = params.trailPercent
|
|
55200
55200
|
? `${params.trailPercent}%`
|
|
55201
55201
|
: `$${params.trailPrice?.toFixed(2)}`;
|
|
55202
|
-
log$
|
|
55202
|
+
log$g(`Creating trailing stop: ${params.side} ${params.qty} ${params.symbol} (trail: ${trailDescription})`, {
|
|
55203
55203
|
type: "info",
|
|
55204
55204
|
});
|
|
55205
55205
|
try {
|
|
@@ -55223,12 +55223,12 @@ async function createTrailingStop(client, params) {
|
|
|
55223
55223
|
orderParams.client_order_id = params.clientOrderId;
|
|
55224
55224
|
}
|
|
55225
55225
|
const order = await sdk.createOrder(orderParams);
|
|
55226
|
-
log$
|
|
55226
|
+
log$g(`Trailing stop created: orderId=${order.id}, HWM=${order.hwm || "pending"}, status=${order.status}`, { type: "info" });
|
|
55227
55227
|
return order;
|
|
55228
55228
|
}
|
|
55229
55229
|
catch (error) {
|
|
55230
55230
|
const err = error;
|
|
55231
|
-
log$
|
|
55231
|
+
log$g(`Trailing stop creation failed for ${params.symbol}: ${err.message}`, {
|
|
55232
55232
|
type: "error",
|
|
55233
55233
|
});
|
|
55234
55234
|
throw new Error(`Failed to create trailing stop for ${params.symbol}: ${err.message}`);
|
|
@@ -55274,7 +55274,7 @@ async function updateTrailingStop(client, orderId, updates) {
|
|
|
55274
55274
|
const updateDescription = updates.trailPercent
|
|
55275
55275
|
? `${updates.trailPercent}%`
|
|
55276
55276
|
: `$${updates.trailPrice?.toFixed(2)}`;
|
|
55277
|
-
log$
|
|
55277
|
+
log$g(`Updating trailing stop ${orderId} to trail: ${updateDescription}`, {
|
|
55278
55278
|
type: "info",
|
|
55279
55279
|
});
|
|
55280
55280
|
try {
|
|
@@ -55287,14 +55287,14 @@ async function updateTrailingStop(client, orderId, updates) {
|
|
|
55287
55287
|
replaceParams.trail = updates.trailPrice.toString();
|
|
55288
55288
|
}
|
|
55289
55289
|
const order = await sdk.replaceOrder(orderId, replaceParams);
|
|
55290
|
-
log$
|
|
55290
|
+
log$g(`Trailing stop updated: orderId=${order.id}, new replacement created`, {
|
|
55291
55291
|
type: "info",
|
|
55292
55292
|
});
|
|
55293
55293
|
return order;
|
|
55294
55294
|
}
|
|
55295
55295
|
catch (error) {
|
|
55296
55296
|
const err = error;
|
|
55297
|
-
log$
|
|
55297
|
+
log$g(`Trailing stop update failed for ${orderId}: ${err.message}`, {
|
|
55298
55298
|
type: "error",
|
|
55299
55299
|
});
|
|
55300
55300
|
throw new Error(`Failed to update trailing stop ${orderId}: ${err.message}`);
|
|
@@ -55324,18 +55324,18 @@ async function getTrailingStopHWM(client, orderId) {
|
|
|
55324
55324
|
const order = await sdk.getOrder(orderId);
|
|
55325
55325
|
// Validate this is actually a trailing stop order
|
|
55326
55326
|
if (order.type !== "trailing_stop") {
|
|
55327
|
-
log$
|
|
55327
|
+
log$g(`Order ${orderId} is not a trailing stop order (type: ${order.type})`, { type: "warn" });
|
|
55328
55328
|
}
|
|
55329
55329
|
const result = {
|
|
55330
55330
|
hwm: order.hwm ? parseFloat(order.hwm) : null,
|
|
55331
55331
|
currentStop: order.stop_price ? parseFloat(order.stop_price) : null,
|
|
55332
55332
|
};
|
|
55333
|
-
log$
|
|
55333
|
+
log$g(`Retrieved HWM for ${orderId}: HWM=${result.hwm ?? "N/A"}, currentStop=${result.currentStop ?? "N/A"}`, { type: "debug" });
|
|
55334
55334
|
return result;
|
|
55335
55335
|
}
|
|
55336
55336
|
catch (error) {
|
|
55337
55337
|
const err = error;
|
|
55338
|
-
log$
|
|
55338
|
+
log$g(`Failed to get trailing stop HWM for ${orderId}: ${err.message}`, {
|
|
55339
55339
|
type: "error",
|
|
55340
55340
|
});
|
|
55341
55341
|
throw new Error(`Failed to get trailing stop HWM for ${orderId}: ${err.message}`);
|
|
@@ -55355,21 +55355,21 @@ async function getTrailingStopHWM(client, orderId) {
|
|
|
55355
55355
|
*/
|
|
55356
55356
|
async function cancelTrailingStop(client, orderId) {
|
|
55357
55357
|
const sdk = client.getSDK();
|
|
55358
|
-
log$
|
|
55358
|
+
log$g(`Canceling trailing stop order: ${orderId}`, { type: "info" });
|
|
55359
55359
|
try {
|
|
55360
55360
|
await sdk.cancelOrder(orderId);
|
|
55361
|
-
log$
|
|
55361
|
+
log$g(`Trailing stop order canceled: ${orderId}`, { type: "info" });
|
|
55362
55362
|
}
|
|
55363
55363
|
catch (error) {
|
|
55364
55364
|
const err = error;
|
|
55365
55365
|
// Check if the order was already filled or canceled
|
|
55366
55366
|
if (err.message.includes("order is not cancelable")) {
|
|
55367
|
-
log$
|
|
55367
|
+
log$g(`Trailing stop ${orderId} is not cancelable (may already be filled or canceled)`, {
|
|
55368
55368
|
type: "warn",
|
|
55369
55369
|
});
|
|
55370
55370
|
throw new Error(`Trailing stop ${orderId} is not cancelable: order may already be filled or canceled`);
|
|
55371
55371
|
}
|
|
55372
|
-
log$
|
|
55372
|
+
log$g(`Failed to cancel trailing stop ${orderId}: ${err.message}`, {
|
|
55373
55373
|
type: "error",
|
|
55374
55374
|
});
|
|
55375
55375
|
throw new Error(`Failed to cancel trailing stop ${orderId}: ${err.message}`);
|
|
@@ -55410,28 +55410,28 @@ async function createPortfolioTrailingStops(client, params) {
|
|
|
55410
55410
|
const sdk = client.getSDK();
|
|
55411
55411
|
const results = new Map();
|
|
55412
55412
|
const excludeSet = new Set(params.excludeSymbols?.map((s) => s.toUpperCase()) || []);
|
|
55413
|
-
log$
|
|
55413
|
+
log$g(`Creating portfolio trailing stops at ${params.trailPercent}%`, {
|
|
55414
55414
|
type: "info",
|
|
55415
55415
|
});
|
|
55416
55416
|
try {
|
|
55417
55417
|
const positions = await sdk.getPositions();
|
|
55418
55418
|
if (positions.length === 0) {
|
|
55419
|
-
log$
|
|
55419
|
+
log$g("No positions found in portfolio", { type: "info" });
|
|
55420
55420
|
return results;
|
|
55421
55421
|
}
|
|
55422
|
-
log$
|
|
55422
|
+
log$g(`Found ${positions.length} positions, checking for eligible trailing stops`, { type: "debug" });
|
|
55423
55423
|
const errors = [];
|
|
55424
55424
|
for (const position of positions) {
|
|
55425
55425
|
const symbol = position.symbol.toUpperCase();
|
|
55426
55426
|
// Skip excluded symbols
|
|
55427
55427
|
if (excludeSet.has(symbol)) {
|
|
55428
|
-
log$
|
|
55428
|
+
log$g(`Skipping ${symbol} (excluded)`, { type: "debug" });
|
|
55429
55429
|
continue;
|
|
55430
55430
|
}
|
|
55431
55431
|
// Only create trailing stops for long positions
|
|
55432
55432
|
const qty = parseFloat(position.qty);
|
|
55433
55433
|
if (qty <= 0) {
|
|
55434
|
-
log$
|
|
55434
|
+
log$g(`Skipping ${symbol} (not a long position, qty: ${qty})`, {
|
|
55435
55435
|
type: "debug",
|
|
55436
55436
|
});
|
|
55437
55437
|
continue;
|
|
@@ -55449,7 +55449,7 @@ async function createPortfolioTrailingStops(client, params) {
|
|
|
55449
55449
|
catch (err) {
|
|
55450
55450
|
const errorMessage = err.message;
|
|
55451
55451
|
errors.push({ symbol, error: errorMessage });
|
|
55452
|
-
log$
|
|
55452
|
+
log$g(`Failed to create trailing stop for ${symbol}: ${errorMessage}`, {
|
|
55453
55453
|
type: "error",
|
|
55454
55454
|
});
|
|
55455
55455
|
}
|
|
@@ -55458,9 +55458,9 @@ async function createPortfolioTrailingStops(client, params) {
|
|
|
55458
55458
|
const successCount = results.size;
|
|
55459
55459
|
const failureCount = errors.length;
|
|
55460
55460
|
const skippedCount = positions.length - successCount - failureCount;
|
|
55461
|
-
log$
|
|
55461
|
+
log$g(`Portfolio trailing stops complete: ${successCount} created, ${failureCount} failed, ${skippedCount} skipped`, { type: "info" });
|
|
55462
55462
|
if (errors.length > 0) {
|
|
55463
|
-
log$
|
|
55463
|
+
log$g(`Failed symbols: ${errors.map((e) => `${e.symbol} (${e.error})`).join(", ")}`, {
|
|
55464
55464
|
type: "warn",
|
|
55465
55465
|
});
|
|
55466
55466
|
}
|
|
@@ -55468,7 +55468,7 @@ async function createPortfolioTrailingStops(client, params) {
|
|
|
55468
55468
|
}
|
|
55469
55469
|
catch (error) {
|
|
55470
55470
|
const err = error;
|
|
55471
|
-
log$
|
|
55471
|
+
log$g(`Failed to create portfolio trailing stops: ${err.message}`, {
|
|
55472
55472
|
type: "error",
|
|
55473
55473
|
});
|
|
55474
55474
|
throw new Error(`Failed to create portfolio trailing stops: ${err.message}`);
|
|
@@ -55503,14 +55503,14 @@ async function getOpenTrailingStops(client, symbol) {
|
|
|
55503
55503
|
const orders = (await sdk.getOrders(queryParams));
|
|
55504
55504
|
// Filter to only trailing stop orders
|
|
55505
55505
|
const trailingStops = orders.filter((order) => order.type === "trailing_stop");
|
|
55506
|
-
log$
|
|
55506
|
+
log$g(`Found ${trailingStops.length} open trailing stop orders${symbol ? ` for ${symbol}` : ""}`, {
|
|
55507
55507
|
type: "debug",
|
|
55508
55508
|
});
|
|
55509
55509
|
return trailingStops;
|
|
55510
55510
|
}
|
|
55511
55511
|
catch (error) {
|
|
55512
55512
|
const err = error;
|
|
55513
|
-
log$
|
|
55513
|
+
log$g(`Failed to get open trailing stops: ${err.message}`, { type: "error" });
|
|
55514
55514
|
throw new Error(`Failed to get open trailing stops: ${err.message}`);
|
|
55515
55515
|
}
|
|
55516
55516
|
}
|
|
@@ -55548,7 +55548,7 @@ async function hasActiveTrailingStop(client, symbol) {
|
|
|
55548
55548
|
async function cancelTrailingStopsForSymbol(client, symbol) {
|
|
55549
55549
|
const trailingStops = await getOpenTrailingStops(client, symbol);
|
|
55550
55550
|
if (trailingStops.length === 0) {
|
|
55551
|
-
log$
|
|
55551
|
+
log$g(`No trailing stops to cancel for ${symbol}`, { type: "debug" });
|
|
55552
55552
|
return 0;
|
|
55553
55553
|
}
|
|
55554
55554
|
let canceledCount = 0;
|
|
@@ -55563,9 +55563,9 @@ async function cancelTrailingStopsForSymbol(client, symbol) {
|
|
|
55563
55563
|
}
|
|
55564
55564
|
}
|
|
55565
55565
|
if (errors.length > 0) {
|
|
55566
|
-
log$
|
|
55566
|
+
log$g(`Some trailing stops failed to cancel for ${symbol}: ${errors.join(", ")}`, { type: "warn" });
|
|
55567
55567
|
}
|
|
55568
|
-
log$
|
|
55568
|
+
log$g(`Canceled ${canceledCount}/${trailingStops.length} trailing stops for ${symbol}`, { type: "info" });
|
|
55569
55569
|
return canceledCount;
|
|
55570
55570
|
}
|
|
55571
55571
|
/**
|
|
@@ -55608,8 +55608,8 @@ var trailingStops$1 = /*#__PURE__*/Object.freeze({
|
|
|
55608
55608
|
*
|
|
55609
55609
|
* @module oco-orders
|
|
55610
55610
|
*/
|
|
55611
|
-
const log$
|
|
55612
|
-
log$
|
|
55611
|
+
const log$f = (message, options = { type: "info" }) => {
|
|
55612
|
+
log$m(message, { ...options, source: "OCOOrders" });
|
|
55613
55613
|
};
|
|
55614
55614
|
/**
|
|
55615
55615
|
* Round a price to the nearest 2 decimal places for Alpaca,
|
|
@@ -55718,7 +55718,7 @@ async function createOCOOrder(client, params) {
|
|
|
55718
55718
|
// Validate parameters
|
|
55719
55719
|
validateOCOParams(params);
|
|
55720
55720
|
const { symbol, qty, side, takeProfit, stopLoss, timeInForce = "gtc", } = params;
|
|
55721
|
-
log$
|
|
55721
|
+
log$f(`Creating OCO order for ${symbol}: ${side} ${qty} shares | ` +
|
|
55722
55722
|
`Take profit at $${takeProfit.limitPrice.toFixed(2)} | ` +
|
|
55723
55723
|
`Stop loss at $${stopLoss.stopPrice.toFixed(2)}` +
|
|
55724
55724
|
(stopLoss.limitPrice
|
|
@@ -55743,7 +55743,7 @@ async function createOCOOrder(client, params) {
|
|
|
55743
55743
|
if (stopLoss.limitPrice !== undefined) {
|
|
55744
55744
|
orderRequest.stop_loss.limit_price = roundPriceForAlpaca$2(stopLoss.limitPrice).toString();
|
|
55745
55745
|
}
|
|
55746
|
-
log$
|
|
55746
|
+
log$f(`Submitting OCO order request: ${JSON.stringify(orderRequest)}`, {
|
|
55747
55747
|
symbol,
|
|
55748
55748
|
type: "debug",
|
|
55749
55749
|
});
|
|
@@ -55752,7 +55752,7 @@ async function createOCOOrder(client, params) {
|
|
|
55752
55752
|
// Extract leg orders from the response
|
|
55753
55753
|
const legs = order.legs || [];
|
|
55754
55754
|
if (legs.length < 2) {
|
|
55755
|
-
log$
|
|
55755
|
+
log$f(`OCO order created but legs not found in response. Order ID: ${order.id}`, { symbol, type: "warn" });
|
|
55756
55756
|
}
|
|
55757
55757
|
// Identify take profit and stop loss orders from legs
|
|
55758
55758
|
// Take profit is the limit order, stop loss is the stop/stop_limit order
|
|
@@ -55760,7 +55760,7 @@ async function createOCOOrder(client, params) {
|
|
|
55760
55760
|
const stopLossOrder = legs.find((leg) => leg.type === "stop" || leg.type === "stop_limit") ||
|
|
55761
55761
|
legs.find((leg) => leg !== takeProfitOrder) ||
|
|
55762
55762
|
order;
|
|
55763
|
-
log$
|
|
55763
|
+
log$f(`OCO order created successfully | Parent ID: ${order.id} | ` +
|
|
55764
55764
|
`Take profit ID: ${takeProfitOrder.id} | Stop loss ID: ${stopLossOrder.id}`, { symbol, type: "info" });
|
|
55765
55765
|
return {
|
|
55766
55766
|
takeProfitOrder,
|
|
@@ -55771,7 +55771,7 @@ async function createOCOOrder(client, params) {
|
|
|
55771
55771
|
}
|
|
55772
55772
|
catch (error) {
|
|
55773
55773
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
55774
|
-
log$
|
|
55774
|
+
log$f(`Failed to create OCO order for ${symbol}: ${errorMessage}`, {
|
|
55775
55775
|
symbol,
|
|
55776
55776
|
type: "error",
|
|
55777
55777
|
});
|
|
@@ -55791,17 +55791,17 @@ async function createOCOOrder(client, params) {
|
|
|
55791
55791
|
* await cancelOCOOrder(client, result.parentOrderId);
|
|
55792
55792
|
*/
|
|
55793
55793
|
async function cancelOCOOrder(client, parentOrderId) {
|
|
55794
|
-
log$
|
|
55794
|
+
log$f(`Canceling OCO order group: ${parentOrderId}`, { type: "info" });
|
|
55795
55795
|
const sdk = client.getSDK();
|
|
55796
55796
|
try {
|
|
55797
55797
|
await sdk.cancelOrder(parentOrderId);
|
|
55798
|
-
log$
|
|
55798
|
+
log$f(`OCO order group canceled successfully: ${parentOrderId}`, {
|
|
55799
55799
|
type: "info",
|
|
55800
55800
|
});
|
|
55801
55801
|
}
|
|
55802
55802
|
catch (error) {
|
|
55803
55803
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
55804
|
-
log$
|
|
55804
|
+
log$f(`Failed to cancel OCO order ${parentOrderId}: ${errorMessage}`, {
|
|
55805
55805
|
type: "error",
|
|
55806
55806
|
});
|
|
55807
55807
|
throw error;
|
|
@@ -55823,17 +55823,17 @@ async function cancelOCOOrder(client, parentOrderId) {
|
|
|
55823
55823
|
* });
|
|
55824
55824
|
*/
|
|
55825
55825
|
async function getOCOOrderStatus(client, parentOrderId) {
|
|
55826
|
-
log$
|
|
55826
|
+
log$f(`Getting OCO order status: ${parentOrderId}`, { type: "debug" });
|
|
55827
55827
|
const sdk = client.getSDK();
|
|
55828
55828
|
try {
|
|
55829
55829
|
const order = (await sdk.getOrder(parentOrderId));
|
|
55830
|
-
log$
|
|
55830
|
+
log$f(`OCO order ${parentOrderId} status: ${order.status} | ` +
|
|
55831
55831
|
`Legs: ${order.legs?.length || 0}`, { type: "debug" });
|
|
55832
55832
|
return order;
|
|
55833
55833
|
}
|
|
55834
55834
|
catch (error) {
|
|
55835
55835
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
55836
|
-
log$
|
|
55836
|
+
log$f(`Failed to get OCO order status ${parentOrderId}: ${errorMessage}`, {
|
|
55837
55837
|
type: "error",
|
|
55838
55838
|
});
|
|
55839
55839
|
throw error;
|
|
@@ -55939,8 +55939,8 @@ var ocoOrders$1 = /*#__PURE__*/Object.freeze({
|
|
|
55939
55939
|
*
|
|
55940
55940
|
* @module oto-orders
|
|
55941
55941
|
*/
|
|
55942
|
-
const log$
|
|
55943
|
-
log$
|
|
55942
|
+
const log$e = (message, options = { type: "info" }) => {
|
|
55943
|
+
log$m(message, { ...options, source: "OTOOrders" });
|
|
55944
55944
|
};
|
|
55945
55945
|
/**
|
|
55946
55946
|
* Round a price to the nearest 2 decimal places for Alpaca,
|
|
@@ -56010,7 +56010,7 @@ function validateOTOParams(params) {
|
|
|
56010
56010
|
// Validate logical order of sides for typical use cases
|
|
56011
56011
|
// Primary buy should typically trigger sell (exit), and vice versa
|
|
56012
56012
|
if (params.side === dependent.side) {
|
|
56013
|
-
log$
|
|
56013
|
+
log$e(`Warning: Primary and dependent orders have the same side (${params.side}). ` +
|
|
56014
56014
|
"This is unusual - typically entry and exit are opposite sides.", { symbol: params.symbol, type: "warn" });
|
|
56015
56015
|
}
|
|
56016
56016
|
}
|
|
@@ -56106,7 +56106,7 @@ async function createOTOOrder(client, params) {
|
|
|
56106
56106
|
dependentDescription += ` trail ${dependent.trailPercent}%`;
|
|
56107
56107
|
if (dependent.trailPrice)
|
|
56108
56108
|
dependentDescription += ` trail $${dependent.trailPrice.toFixed(2)}`;
|
|
56109
|
-
log$
|
|
56109
|
+
log$e(`Creating OTO order for ${symbol}: Primary [${primaryDescription}] -> Dependent [${dependentDescription}]`, { symbol, type: "info" });
|
|
56110
56110
|
const sdk = client.getSDK();
|
|
56111
56111
|
try {
|
|
56112
56112
|
// Build the OTO order request
|
|
@@ -56166,7 +56166,7 @@ async function createOTOOrder(client, params) {
|
|
|
56166
56166
|
orderRequest.stop_loss.trail_price = roundPriceForAlpaca$1(dependent.trailPrice).toString();
|
|
56167
56167
|
}
|
|
56168
56168
|
}
|
|
56169
|
-
log$
|
|
56169
|
+
log$e(`Submitting OTO order request: ${JSON.stringify(orderRequest)}`, {
|
|
56170
56170
|
symbol,
|
|
56171
56171
|
type: "debug",
|
|
56172
56172
|
});
|
|
@@ -56177,7 +56177,7 @@ async function createOTOOrder(client, params) {
|
|
|
56177
56177
|
// The primary order is the parent, dependent is in legs
|
|
56178
56178
|
const primaryOrder = order;
|
|
56179
56179
|
const dependentOrder = legs.length > 0 ? legs[0] : null;
|
|
56180
|
-
log$
|
|
56180
|
+
log$e(`OTO order created successfully | Parent ID: ${order.id} | Status: ${order.status}` +
|
|
56181
56181
|
(dependentOrder ? ` | Dependent ID: ${dependentOrder.id}` : ""), { symbol, type: "info" });
|
|
56182
56182
|
return {
|
|
56183
56183
|
primaryOrder,
|
|
@@ -56188,7 +56188,7 @@ async function createOTOOrder(client, params) {
|
|
|
56188
56188
|
}
|
|
56189
56189
|
catch (error) {
|
|
56190
56190
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
56191
|
-
log$
|
|
56191
|
+
log$e(`Failed to create OTO order for ${symbol}: ${errorMessage}`, {
|
|
56192
56192
|
symbol,
|
|
56193
56193
|
type: "error",
|
|
56194
56194
|
});
|
|
@@ -56208,17 +56208,17 @@ async function createOTOOrder(client, params) {
|
|
|
56208
56208
|
* await cancelOTOOrder(client, result.parentOrderId);
|
|
56209
56209
|
*/
|
|
56210
56210
|
async function cancelOTOOrder(client, parentOrderId) {
|
|
56211
|
-
log$
|
|
56211
|
+
log$e(`Canceling OTO order group: ${parentOrderId}`, { type: "info" });
|
|
56212
56212
|
const sdk = client.getSDK();
|
|
56213
56213
|
try {
|
|
56214
56214
|
await sdk.cancelOrder(parentOrderId);
|
|
56215
|
-
log$
|
|
56215
|
+
log$e(`OTO order group canceled successfully: ${parentOrderId}`, {
|
|
56216
56216
|
type: "info",
|
|
56217
56217
|
});
|
|
56218
56218
|
}
|
|
56219
56219
|
catch (error) {
|
|
56220
56220
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
56221
|
-
log$
|
|
56221
|
+
log$e(`Failed to cancel OTO order ${parentOrderId}: ${errorMessage}`, {
|
|
56222
56222
|
type: "error",
|
|
56223
56223
|
});
|
|
56224
56224
|
throw error;
|
|
@@ -56240,17 +56240,17 @@ async function cancelOTOOrder(client, parentOrderId) {
|
|
|
56240
56240
|
* }
|
|
56241
56241
|
*/
|
|
56242
56242
|
async function getOTOOrderStatus(client, parentOrderId) {
|
|
56243
|
-
log$
|
|
56243
|
+
log$e(`Getting OTO order status: ${parentOrderId}`, { type: "debug" });
|
|
56244
56244
|
const sdk = client.getSDK();
|
|
56245
56245
|
try {
|
|
56246
56246
|
const order = (await sdk.getOrder(parentOrderId));
|
|
56247
|
-
log$
|
|
56247
|
+
log$e(`OTO order ${parentOrderId} status: ${order.status} | ` +
|
|
56248
56248
|
`Legs: ${order.legs?.length || 0}`, { type: "debug" });
|
|
56249
56249
|
return order;
|
|
56250
56250
|
}
|
|
56251
56251
|
catch (error) {
|
|
56252
56252
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
56253
|
-
log$
|
|
56253
|
+
log$e(`Failed to get OTO order status ${parentOrderId}: ${errorMessage}`, {
|
|
56254
56254
|
type: "error",
|
|
56255
56255
|
});
|
|
56256
56256
|
throw error;
|
|
@@ -56437,8 +56437,119 @@ var otoOrders$1 = /*#__PURE__*/Object.freeze({
|
|
|
56437
56437
|
shortWithStopLoss: shortWithStopLoss
|
|
56438
56438
|
});
|
|
56439
56439
|
|
|
56440
|
+
const log$d = (message, options = { type: "info" }) => {
|
|
56441
|
+
log$m(message, { ...options, source: "AlpacaClock" });
|
|
56442
|
+
};
|
|
56443
|
+
/**
|
|
56444
|
+
* Formats a Date to a YYYY-MM-DD string suitable for Alpaca calendar API requests.
|
|
56445
|
+
*
|
|
56446
|
+
* @param date - The date to format
|
|
56447
|
+
* @returns Date string in YYYY-MM-DD format
|
|
56448
|
+
*/
|
|
56449
|
+
function formatCalendarDate(date) {
|
|
56450
|
+
const year = date.getFullYear();
|
|
56451
|
+
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
56452
|
+
const day = String(date.getDate()).padStart(2, "0");
|
|
56453
|
+
return `${year}-${month}-${day}`;
|
|
56454
|
+
}
|
|
56455
|
+
/**
|
|
56456
|
+
* Fetches the current market clock from Alpaca (GET /v2/clock).
|
|
56457
|
+
*
|
|
56458
|
+
* Returns the current server time, whether the market is open, and the next
|
|
56459
|
+
* open/close timestamps. Useful for determining whether trading is currently
|
|
56460
|
+
* possible before placing orders.
|
|
56461
|
+
*
|
|
56462
|
+
* @param client - An initialized AlpacaClient instance
|
|
56463
|
+
* @returns Promise resolving to the current market clock status
|
|
56464
|
+
*
|
|
56465
|
+
* @example
|
|
56466
|
+
* ```ts
|
|
56467
|
+
* const clock = await getAlpacaClock(client);
|
|
56468
|
+
* if (clock.is_open) {
|
|
56469
|
+
* console.log('Market is open, next close:', clock.next_close);
|
|
56470
|
+
* } else {
|
|
56471
|
+
* console.log('Market closed, next open:', clock.next_open);
|
|
56472
|
+
* }
|
|
56473
|
+
* ```
|
|
56474
|
+
*
|
|
56475
|
+
* @throws {Error} If the Alpaca API request fails
|
|
56476
|
+
*/
|
|
56477
|
+
async function getAlpacaClock(client) {
|
|
56478
|
+
log$d("Fetching market clock");
|
|
56479
|
+
try {
|
|
56480
|
+
const sdk = client.getSDK();
|
|
56481
|
+
const clock = await sdk.getClock();
|
|
56482
|
+
log$d(`Market clock fetched: is_open=${clock.is_open}, next_open=${clock.next_open}`);
|
|
56483
|
+
return clock;
|
|
56484
|
+
}
|
|
56485
|
+
catch (error) {
|
|
56486
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
56487
|
+
log$d(`Failed to fetch market clock: ${errorMessage}`, { type: "error" });
|
|
56488
|
+
throw error;
|
|
56489
|
+
}
|
|
56490
|
+
}
|
|
56491
|
+
/**
|
|
56492
|
+
* Fetches the market trading calendar from Alpaca (GET /v2/calendar).
|
|
56493
|
+
*
|
|
56494
|
+
* Returns the scheduled open and close times for each trading day within the
|
|
56495
|
+
* requested date range. The calendar accounts for market holidays and early
|
|
56496
|
+
* closures. Dates default to today when omitted.
|
|
56497
|
+
*
|
|
56498
|
+
* @param client - An initialized AlpacaClient instance
|
|
56499
|
+
* @param options - Optional start/end dates for the calendar range
|
|
56500
|
+
* @returns Promise resolving to an array of trading calendar days
|
|
56501
|
+
*
|
|
56502
|
+
* @example
|
|
56503
|
+
* ```ts
|
|
56504
|
+
* // Fetch the next 5 trading days
|
|
56505
|
+
* const today = new Date();
|
|
56506
|
+
* const nextWeek = new Date(today);
|
|
56507
|
+
* nextWeek.setDate(today.getDate() + 7);
|
|
56508
|
+
*
|
|
56509
|
+
* const calendar = await getAlpacaCalendar(client, {
|
|
56510
|
+
* start: today,
|
|
56511
|
+
* end: nextWeek,
|
|
56512
|
+
* });
|
|
56513
|
+
* console.log('Trading days this week:', calendar.length);
|
|
56514
|
+
* ```
|
|
56515
|
+
*
|
|
56516
|
+
* @throws {Error} If the Alpaca API request fails
|
|
56517
|
+
*/
|
|
56518
|
+
async function getAlpacaCalendar(client, options) {
|
|
56519
|
+
const startStr = options?.start
|
|
56520
|
+
? formatCalendarDate(options.start)
|
|
56521
|
+
: undefined;
|
|
56522
|
+
const endStr = options?.end ? formatCalendarDate(options.end) : undefined;
|
|
56523
|
+
log$d(`Fetching market calendar${startStr ? ` from ${startStr}` : ""}${endStr ? ` to ${endStr}` : ""}`);
|
|
56524
|
+
try {
|
|
56525
|
+
const sdk = client.getSDK();
|
|
56526
|
+
const calendar = await sdk.getCalendar({
|
|
56527
|
+
start: startStr,
|
|
56528
|
+
end: endStr,
|
|
56529
|
+
});
|
|
56530
|
+
log$d(`Market calendar fetched: ${calendar.length} trading days`);
|
|
56531
|
+
return calendar;
|
|
56532
|
+
}
|
|
56533
|
+
catch (error) {
|
|
56534
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
56535
|
+
log$d(`Failed to fetch market calendar: ${errorMessage}`, { type: "error" });
|
|
56536
|
+
throw error;
|
|
56537
|
+
}
|
|
56538
|
+
}
|
|
56539
|
+
var clock = {
|
|
56540
|
+
getAlpacaClock,
|
|
56541
|
+
getAlpacaCalendar,
|
|
56542
|
+
};
|
|
56543
|
+
|
|
56544
|
+
var clock$1 = /*#__PURE__*/Object.freeze({
|
|
56545
|
+
__proto__: null,
|
|
56546
|
+
default: clock,
|
|
56547
|
+
getAlpacaCalendar: getAlpacaCalendar,
|
|
56548
|
+
getAlpacaClock: getAlpacaClock
|
|
56549
|
+
});
|
|
56550
|
+
|
|
56440
56551
|
const log$c = (message, options = { type: "info" }) => {
|
|
56441
|
-
log$
|
|
56552
|
+
log$m(message, { ...options, source: "AlpacaQuotes" });
|
|
56442
56553
|
};
|
|
56443
56554
|
/**
|
|
56444
56555
|
* Error thrown when quote operations fail
|
|
@@ -56668,7 +56779,7 @@ var quotes$1 = /*#__PURE__*/Object.freeze({
|
|
|
56668
56779
|
});
|
|
56669
56780
|
|
|
56670
56781
|
const log$b = (message, options = { type: "info" }) => {
|
|
56671
|
-
log$
|
|
56782
|
+
log$m(message, { ...options, source: "AlpacaBars" });
|
|
56672
56783
|
};
|
|
56673
56784
|
/**
|
|
56674
56785
|
* Error thrown when bar operations fail
|
|
@@ -57034,7 +57145,7 @@ var bars$1 = /*#__PURE__*/Object.freeze({
|
|
|
57034
57145
|
});
|
|
57035
57146
|
|
|
57036
57147
|
const log$a = (message, options = { type: "info" }) => {
|
|
57037
|
-
log$
|
|
57148
|
+
log$m(message, { ...options, source: "AlpacaTrades" });
|
|
57038
57149
|
};
|
|
57039
57150
|
/**
|
|
57040
57151
|
* Error thrown when trade operations fail
|
|
@@ -57411,7 +57522,7 @@ var trades$1 = /*#__PURE__*/Object.freeze({
|
|
|
57411
57522
|
});
|
|
57412
57523
|
|
|
57413
57524
|
const log$9 = (message, options = { type: "info" }) => {
|
|
57414
|
-
log$
|
|
57525
|
+
log$m(message, { ...options, source: "AlpacaNews" });
|
|
57415
57526
|
};
|
|
57416
57527
|
/**
|
|
57417
57528
|
* Error thrown when news operations fail
|
|
@@ -57884,7 +57995,7 @@ const LOG_SOURCE$6 = "OptionsContracts";
|
|
|
57884
57995
|
* Internal logging helper with consistent source
|
|
57885
57996
|
*/
|
|
57886
57997
|
const log$8 = (message, options = { type: "info" }) => {
|
|
57887
|
-
log$
|
|
57998
|
+
log$m(message, { ...options, source: LOG_SOURCE$6 });
|
|
57888
57999
|
};
|
|
57889
58000
|
// ============================================================================
|
|
57890
58001
|
// API Functions
|
|
@@ -58593,7 +58704,7 @@ const LOG_SOURCE$5 = "OptionsOrders";
|
|
|
58593
58704
|
* Internal logging helper with consistent source
|
|
58594
58705
|
*/
|
|
58595
58706
|
const log$7 = (message, options = { type: "info" }) => {
|
|
58596
|
-
log$
|
|
58707
|
+
log$m(message, { ...options, source: LOG_SOURCE$5 });
|
|
58597
58708
|
};
|
|
58598
58709
|
// ============================================================================
|
|
58599
58710
|
// Single-Leg Option Orders
|
|
@@ -59448,7 +59559,7 @@ const LOG_SOURCE$4 = "AlpacaOrders";
|
|
|
59448
59559
|
* Internal logging helper with consistent source
|
|
59449
59560
|
*/
|
|
59450
59561
|
const log$6 = (message, options = { type: "info" }) => {
|
|
59451
|
-
log$
|
|
59562
|
+
log$m(message, { ...options, source: LOG_SOURCE$4 });
|
|
59452
59563
|
};
|
|
59453
59564
|
/**
|
|
59454
59565
|
* Creates a new order using the Alpaca SDK.
|
|
@@ -59861,7 +59972,7 @@ const LOG_SOURCE$3 = "OptionsStrategies";
|
|
|
59861
59972
|
* Internal logging helper with consistent source
|
|
59862
59973
|
*/
|
|
59863
59974
|
const log$5 = (message, options = { type: "info" }) => {
|
|
59864
|
-
log$
|
|
59975
|
+
log$m(message, { ...options, source: LOG_SOURCE$3 });
|
|
59865
59976
|
};
|
|
59866
59977
|
/**
|
|
59867
59978
|
* Error class for option strategy operations
|
|
@@ -60463,7 +60574,7 @@ const LOG_SOURCE$2 = "OptionsData";
|
|
|
60463
60574
|
* Internal logging helper with consistent source
|
|
60464
60575
|
*/
|
|
60465
60576
|
const log$4 = (message, options = { type: "info" }) => {
|
|
60466
|
-
log$
|
|
60577
|
+
log$m(message, { ...options, source: LOG_SOURCE$2 });
|
|
60467
60578
|
};
|
|
60468
60579
|
/**
|
|
60469
60580
|
* Error class for options data operations
|
|
@@ -60969,7 +61080,7 @@ const LOG_SOURCE$1 = "CryptoOrders";
|
|
|
60969
61080
|
* Internal logging helper with consistent source
|
|
60970
61081
|
*/
|
|
60971
61082
|
const log$3 = (message, options = { type: "info" }) => {
|
|
60972
|
-
log$
|
|
61083
|
+
log$m(message, { ...options, source: LOG_SOURCE$1 });
|
|
60973
61084
|
};
|
|
60974
61085
|
/**
|
|
60975
61086
|
* Error thrown when crypto order operations fail
|
|
@@ -61461,7 +61572,7 @@ const LOG_SOURCE = "CryptoData";
|
|
|
61461
61572
|
* Internal logging helper with consistent source
|
|
61462
61573
|
*/
|
|
61463
61574
|
const log$2 = (message, options = { type: "info" }) => {
|
|
61464
|
-
log$
|
|
61575
|
+
log$m(message, { ...options, source: LOG_SOURCE });
|
|
61465
61576
|
};
|
|
61466
61577
|
/**
|
|
61467
61578
|
* Error thrown when crypto data operations fail
|
|
@@ -62280,7 +62391,7 @@ var streams$1 = /*#__PURE__*/Object.freeze({
|
|
|
62280
62391
|
});
|
|
62281
62392
|
|
|
62282
62393
|
const log$1 = (message, options = { type: "info" }) => {
|
|
62283
|
-
log$
|
|
62394
|
+
log$m(message, { ...options, source: "SmartOrders" });
|
|
62284
62395
|
};
|
|
62285
62396
|
/**
|
|
62286
62397
|
* Analyze parameters and determine the best order type
|
|
@@ -62718,7 +62829,7 @@ var smartOrders$1 = /*#__PURE__*/Object.freeze({
|
|
|
62718
62829
|
const log = (message, options = {
|
|
62719
62830
|
type: "info",
|
|
62720
62831
|
}) => {
|
|
62721
|
-
log$
|
|
62832
|
+
log$m(message, { ...options, source: "Positions" });
|
|
62722
62833
|
};
|
|
62723
62834
|
// ============================================================================
|
|
62724
62835
|
// Helper Functions
|
|
@@ -63498,6 +63609,8 @@ const alpaca = {
|
|
|
63498
63609
|
positions: positions$1,
|
|
63499
63610
|
// Trading - Account
|
|
63500
63611
|
account: account$1,
|
|
63612
|
+
// Trading - Clock & Calendar
|
|
63613
|
+
clock: clock$1,
|
|
63501
63614
|
// Market Data
|
|
63502
63615
|
quotes: quotes$1,
|
|
63503
63616
|
bars: bars$1,
|
|
@@ -71393,6 +71506,8 @@ const adaptic = {
|
|
|
71393
71506
|
sdkPositions: alpaca.positions,
|
|
71394
71507
|
/** @description Account information and configuration - SDK-based (requires AlpacaClient) */
|
|
71395
71508
|
sdkAccount: alpaca.account,
|
|
71509
|
+
/** @description Market clock and trading calendar - SDK-based (requires AlpacaClient) */
|
|
71510
|
+
sdkClock: alpaca.clock,
|
|
71396
71511
|
// Legacy API (with original signatures for backward compatibility)
|
|
71397
71512
|
/** @description Standard order operations - Legacy API (uses AlpacaAuth) */
|
|
71398
71513
|
orders: {
|
|
@@ -71558,5 +71673,5 @@ const adaptic = {
|
|
|
71558
71673
|
};
|
|
71559
71674
|
const adptc = adaptic;
|
|
71560
71675
|
|
|
71561
|
-
export { API_RETRY_CONFIGS, AVNewsArticleSchema, AVNewsResponseSchema, AdapticUtilsError, AlpacaAccountDetailsSchema, AlpacaApiError, AlpacaBarSchema, AlpacaClient, AlpacaCryptoBarsResponseSchema, AlpacaHistoricalBarsResponseSchema, AlpacaLatestBarsResponseSchema, AlpacaLatestQuotesResponseSchema, AlpacaLatestTradesResponseSchema, AlpacaMarketDataAPI, AlpacaNewsArticleSchema, AlpacaNewsResponseSchema, AlpacaOrderSchema, AlpacaOrdersArraySchema, AlpacaPortfolioHistoryResponseSchema, AlpacaPositionSchema, AlpacaPositionsArraySchema, AlpacaQuoteSchema, AlpacaTradeSchema, AlpacaTradingAPI, AlphaVantageError, AlphaVantageQuoteResponseSchema, AssetAllocationEngine, AuthenticationError, BTC_PAIRS, BarError, CryptoDataError, CryptoOrderError, DEFAULT_CACHE_OPTIONS, DEFAULT_TIMEOUTS, DataFormatError, HttpClientError, HttpServerError, KEEP_ALIVE_DEFAULTS, MARKET_DATA_API, NetworkError, NewsError, OptionStrategyError, OptionsDataError, PolygonAggregatesResponseSchema, PolygonApiError, PolygonDailyOpenCloseSchema, PolygonErrorResponseSchema, PolygonGroupedDailyResponseSchema, PolygonLastTradeResponseSchema, PolygonTickerDetailsResponseSchema, PolygonTickerInfoSchema, PolygonTradeSchema as PolygonTradeZodSchema, PolygonTradesResponseSchema, QuoteError, RateLimitError, RawPolygonPriceDataSchema, StampedeProtectedCache, TRADING_API, TimeoutError, TokenBucketRateLimiter, TradeError, TrailingStopValidationError, USDC_PAIRS, USDT_PAIRS, USD_PAIRS, ValidationError, ValidationResponseError, WEBSOCKET_STREAMS, WebSocketError, account, adaptic, adptc, alpaca, analyzeBars, approximateImpliedVolatility, bracketOrders, buildOCCSymbol, buildOptionSymbol, buyCryptoNotional, buyToClose, buyToOpen, buyWithStopLoss, buyWithTrailingStop, calculateMoneyness, calculateOrderValue, calculatePeriodPerformance, calculatePutCallRatio, calculateTotalFilledValue, cancelAllCryptoOrders, cancelOCOOrder, cancelOTOOrder, cancelTrailingStop, cancelTrailingStopsForSymbol, checkTradingEligibility, clearClientCache, closeAllOptionPositions, closeOptionPosition, createAlpacaClient, createAlpacaMarketDataAPI, createAlpacaTradingAPI, createBracketOrder, createButterflySpread, createClientFromEnv, createCoveredCall, createCryptoLimitOrder, createCryptoMarketOrder, createCryptoOrder, createCryptoStopLimitOrder, createCryptoStopOrder, createExecutorFromTradingAPI, createIronCondor$1 as createIronCondor, createIronCondor as createIronCondorAdvanced, createMultiLegOptionOrder, createOCOOrder, createOTOOrder, createOptionOrder, createPortfolioTrailingStops, createProtectiveBracket, createStampedeProtectedCache, createStraddle$1 as createStraddle, createStraddle as createStraddleAdvanced, createStrangle$1 as createStrangle, createStrangle as createStrangleAdvanced, createStreamManager, createTimeoutSignal, createTrailingStop, createVerticalSpread$1 as createVerticalSpread, createVerticalSpread as createVerticalSpreadAdvanced, entryWithPercentStopLoss, exerciseOption, extractGreeks, filterByExpiration, filterByStrike, filterByType, filterOrdersByDateRange, findATMOptions, findATMStrikes, findNearestExpiration, findOptionsByDelta, formatOrderForLog, formatOrderSummary, generateOptimalAllocation, getAccountConfiguration, getAccountDetails, getAccountSummary, getAgentPoolStatus, getAllOrders, getAverageDailyVolume, getBars, getBuyingPower, getCrypto24HourChange, getCryptoBars, getCryptoDailyPrices, getCryptoPairsByQuote, getCryptoPrice, getCryptoSnapshots, getCryptoSpread, getCryptoStreamUrl, getCryptoTrades, getCurrentPrice, getCurrentPrices, getDailyPrices, getDailyReturns, getDaysToExpiration, getDefaultRiskProfile, getEquityCurve, getExpirationDates, getFilledOrders, getGroupedOptionChain, getHistoricalOptionsBars, getHistoricalTrades, getIntradayPrices, getLatestBars, getLatestCryptoQuotes, getLatestCryptoTrades, getLatestNews, getLatestOptionsQuotes, getLatestOptionsTrades, getLatestQuote, getLatestQuotes, getLatestTrade, getLatestTrades, getLogger, getMarginInfo, getNews, getNewsForSymbols, getOCOOrderStatus, getOTOOrderStatus, getOpenCryptoOrders, getOpenOrders$1 as getOpenOrdersQuery, getOpenTrailingStops, getOptionChain, getOptionContract, getOptionContracts, getOptionSpread, getOptionsChain, getOptionsSnapshots, getOptionsStreamUrl, getOptionsTradingLevel, getOrderHistory, getOrdersBySymbol, getPDTStatus, getPopularCryptoPairs, getPortfolioHistory, getPreviousClose, getPriceRange, getSpread, getSpreads, getStockStreamUrl, getStrikePrices, getSupportedCryptoPairs, getSymbolSentiment, getTimeout, getTradeVolume, getTradingApiUrl, getTradingWebSocketUrl, getTrailingStopHWM, groupOrdersByStatus, groupOrdersBySymbol, hasActiveTrailingStop, hasGoodLiquidity as hasOptionLiquidity, hasGoodLiquidity$1 as hasStockLiquidity, hasSufficientVolume, httpAgent, httpsAgent, isContractTradable, isCryptoPair, isExpiringWithin, isMarginAccount, isOptionOrderCancelable, isOptionOrderTerminal, isOrderFillable, isOrderFilled, isOrderOpen, isOrderTerminal$1 as isOrderTerminalStatus, isSupportedCryptoPair, index as legacyApi, limitBuyWithTakeProfit, ocoOrders, orderUtils, otoOrders, paginate, paginateAll, parseOCCSymbol, protectLongPosition, protectShortPosition, rateLimiters, resetLogger, rollOptionPosition, roundPriceForAlpaca$3 as roundPriceForAlpaca, roundPriceForAlpacaNumber, safeValidateResponse, searchNews, sellAllCrypto, sellCryptoNotional, sellToClose, sellToOpen, setLogger, shortWithStopLoss, sortOrdersByDate, trailingStops, updateAccountConfiguration, updateTrailingStop, validateAlpacaCredentials, validateAlphaVantageApiKey, validateMultiLegOrder, validatePolygonApiKey$1 as validatePolygonApiKey, validateResponse, verifyFetchKeepAlive, waitForOrderFill, withRetry, withTimeout };
|
|
71676
|
+
export { API_RETRY_CONFIGS, AVNewsArticleSchema, AVNewsResponseSchema, AdapticUtilsError, AlpacaAccountDetailsSchema, AlpacaApiError, AlpacaBarSchema, AlpacaClient, AlpacaCryptoBarsResponseSchema, AlpacaHistoricalBarsResponseSchema, AlpacaLatestBarsResponseSchema, AlpacaLatestQuotesResponseSchema, AlpacaLatestTradesResponseSchema, AlpacaMarketDataAPI, AlpacaNewsArticleSchema, AlpacaNewsResponseSchema, AlpacaOrderSchema, AlpacaOrdersArraySchema, AlpacaPortfolioHistoryResponseSchema, AlpacaPositionSchema, AlpacaPositionsArraySchema, AlpacaQuoteSchema, AlpacaTradeSchema, AlpacaTradingAPI, AlphaVantageError, AlphaVantageQuoteResponseSchema, AssetAllocationEngine, AuthenticationError, BTC_PAIRS, BarError, CryptoDataError, CryptoOrderError, DEFAULT_CACHE_OPTIONS, DEFAULT_TIMEOUTS, DataFormatError, HttpClientError, HttpServerError, KEEP_ALIVE_DEFAULTS, MARKET_DATA_API, NetworkError, NewsError, OptionStrategyError, OptionsDataError, PolygonAggregatesResponseSchema, PolygonApiError, PolygonDailyOpenCloseSchema, PolygonErrorResponseSchema, PolygonGroupedDailyResponseSchema, PolygonLastTradeResponseSchema, PolygonTickerDetailsResponseSchema, PolygonTickerInfoSchema, PolygonTradeSchema as PolygonTradeZodSchema, PolygonTradesResponseSchema, QuoteError, RateLimitError, RawPolygonPriceDataSchema, StampedeProtectedCache, TRADING_API, TimeoutError, TokenBucketRateLimiter, TradeError, TrailingStopValidationError, USDC_PAIRS, USDT_PAIRS, USD_PAIRS, ValidationError, ValidationResponseError, WEBSOCKET_STREAMS, WebSocketError, account, adaptic, adptc, alpaca, analyzeBars, approximateImpliedVolatility, bracketOrders, buildOCCSymbol, buildOptionSymbol, buyCryptoNotional, buyToClose, buyToOpen, buyWithStopLoss, buyWithTrailingStop, calculateMoneyness, calculateOrderValue, calculatePeriodPerformance, calculatePutCallRatio, calculateTotalFilledValue, cancelAllCryptoOrders, cancelOCOOrder, cancelOTOOrder, cancelTrailingStop, cancelTrailingStopsForSymbol, checkTradingEligibility, clearClientCache, clock, closeAllOptionPositions, closeOptionPosition, createAlpacaClient, createAlpacaMarketDataAPI, createAlpacaTradingAPI, createBracketOrder, createButterflySpread, createClientFromEnv, createCoveredCall, createCryptoLimitOrder, createCryptoMarketOrder, createCryptoOrder, createCryptoStopLimitOrder, createCryptoStopOrder, createExecutorFromTradingAPI, createIronCondor$1 as createIronCondor, createIronCondor as createIronCondorAdvanced, createMultiLegOptionOrder, createOCOOrder, createOTOOrder, createOptionOrder, createPortfolioTrailingStops, createProtectiveBracket, createStampedeProtectedCache, createStraddle$1 as createStraddle, createStraddle as createStraddleAdvanced, createStrangle$1 as createStrangle, createStrangle as createStrangleAdvanced, createStreamManager, createTimeoutSignal, createTrailingStop, createVerticalSpread$1 as createVerticalSpread, createVerticalSpread as createVerticalSpreadAdvanced, entryWithPercentStopLoss, exerciseOption, extractGreeks, filterByExpiration, filterByStrike, filterByType, filterOrdersByDateRange, findATMOptions, findATMStrikes, findNearestExpiration, findOptionsByDelta, formatOrderForLog, formatOrderSummary, generateOptimalAllocation, getAccountConfiguration, getAccountDetails, getAccountSummary, getAgentPoolStatus, getAllOrders, getAlpacaCalendar, getAlpacaClock, getAverageDailyVolume, getBars, getBuyingPower, getCrypto24HourChange, getCryptoBars, getCryptoDailyPrices, getCryptoPairsByQuote, getCryptoPrice, getCryptoSnapshots, getCryptoSpread, getCryptoStreamUrl, getCryptoTrades, getCurrentPrice, getCurrentPrices, getDailyPrices, getDailyReturns, getDaysToExpiration, getDefaultRiskProfile, getEquityCurve, getExpirationDates, getFilledOrders, getGroupedOptionChain, getHistoricalOptionsBars, getHistoricalTrades, getIntradayPrices, getLatestBars, getLatestCryptoQuotes, getLatestCryptoTrades, getLatestNews, getLatestOptionsQuotes, getLatestOptionsTrades, getLatestQuote, getLatestQuotes, getLatestTrade, getLatestTrades, getLogger, getMarginInfo, getNews, getNewsForSymbols, getOCOOrderStatus, getOTOOrderStatus, getOpenCryptoOrders, getOpenOrders$1 as getOpenOrdersQuery, getOpenTrailingStops, getOptionChain, getOptionContract, getOptionContracts, getOptionSpread, getOptionsChain, getOptionsSnapshots, getOptionsStreamUrl, getOptionsTradingLevel, getOrderHistory, getOrdersBySymbol, getPDTStatus, getPopularCryptoPairs, getPortfolioHistory, getPreviousClose, getPriceRange, getSpread, getSpreads, getStockStreamUrl, getStrikePrices, getSupportedCryptoPairs, getSymbolSentiment, getTimeout, getTradeVolume, getTradingApiUrl, getTradingWebSocketUrl, getTrailingStopHWM, groupOrdersByStatus, groupOrdersBySymbol, hasActiveTrailingStop, hasGoodLiquidity as hasOptionLiquidity, hasGoodLiquidity$1 as hasStockLiquidity, hasSufficientVolume, httpAgent, httpsAgent, isContractTradable, isCryptoPair, isExpiringWithin, isMarginAccount, isOptionOrderCancelable, isOptionOrderTerminal, isOrderFillable, isOrderFilled, isOrderOpen, isOrderTerminal$1 as isOrderTerminalStatus, isSupportedCryptoPair, index as legacyApi, limitBuyWithTakeProfit, ocoOrders, orderUtils, otoOrders, paginate, paginateAll, parseOCCSymbol, protectLongPosition, protectShortPosition, rateLimiters, resetLogger, rollOptionPosition, roundPriceForAlpaca$3 as roundPriceForAlpaca, roundPriceForAlpacaNumber, safeValidateResponse, searchNews, sellAllCrypto, sellCryptoNotional, sellToClose, sellToOpen, setLogger, shortWithStopLoss, sortOrdersByDate, trailingStops, updateAccountConfiguration, updateTrailingStop, validateAlpacaCredentials, validateAlphaVantageApiKey, validateMultiLegOrder, validatePolygonApiKey$1 as validatePolygonApiKey, validateResponse, verifyFetchKeepAlive, waitForOrderFill, withRetry, withTimeout };
|
|
71562
71677
|
//# sourceMappingURL=index.mjs.map
|