nexustrade 5.2.2 → 5.4.0

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/README.md CHANGED
@@ -140,6 +140,27 @@ A cached single-name spec that omitted the baseline therefore runs once more
140
140
  after upgrading, because its benchmark is now part of the run's identity. The
141
141
  portfolio handle accepts the same typed benchmark: `PortfolioHandle.backtest({ baselineAsset })`.
142
142
 
143
+ ### Equity curve and fills
144
+
145
+ The terminal `result.statistics` carries the aggregates (`percentChange`,
146
+ `sharpeRatio`, `maxDrawdown`, `winRate`, `closedTradeCount`, `totalFees`).
147
+ The curve and the individual fills are separate reads:
148
+
149
+ ```typescript
150
+ const curve = await client.getBacktestHistory(backtestId, { pageSize: 5000 });
151
+ // curve.points: time, value, cash, positionValue, comparisonValue, reservedCollateral
152
+ // follow curve.nextPage until null
153
+
154
+ const fills = await client.listBacktestEvents(backtestId, {
155
+ eventTypes: ["Order"],
156
+ orderStatuses: ["Filled"],
157
+ });
158
+ ```
159
+
160
+ History is retained for 30 days. Events exist only for a run submitted with
161
+ `generateEvents: true` and are retained for 3 days; otherwise the call raises
162
+ `events_unavailable`.
163
+
143
164
  ### Collateral at risk
144
165
 
145
166
  A terminal operation's `result.statistics` answers how much capital the run had
@@ -771,6 +792,120 @@ Branch on `result.outcome`, not on status alone:
771
792
 
772
793
  This method spends LLM credits.
773
794
 
795
+ ## Congressional trades
796
+
797
+ House and Senate stock disclosures (STOCK Act periodic transaction reports) are
798
+ readable as data, separately from the `PoliticalTrades` strategy indicators.
799
+ The client calls NexusTrade's REST API at `/api/political-disclosures`, on the
800
+ same host as the SDK routes.
801
+
802
+ Seven reads work with no API key and no workspace, so a bare client is enough:
803
+
804
+ ```ts
805
+ import { NexusTradeClient } from "nexustrade";
806
+
807
+ const client = new NexusTradeClient(); // no API key needed for these reads
808
+
809
+ const page = await client.listCongressionalTrades({
810
+ ticker: "NVDA",
811
+ fromDate: "2026-01-01",
812
+ limit: 5,
813
+ });
814
+ for (const trade of page.data.trades) {
815
+ console.log(
816
+ trade.availableAt, // public from here: the date to trade from
817
+ trade.filerName,
818
+ trade.action,
819
+ trade.ticker,
820
+ trade.amountBracket
821
+ );
822
+ }
823
+
824
+ // Next page: the same filters plus the cursor.
825
+ if (page.data.nextCursor) {
826
+ await client.listCongressionalTrades({
827
+ ticker: "NVDA",
828
+ fromDate: "2026-01-01",
829
+ limit: 5,
830
+ cursor: page.data.nextCursor,
831
+ });
832
+ }
833
+
834
+ const pelosi = await client.getPolitician("nancy-pelosi");
835
+ console.log(pelosi.data.politician.displayName, pelosi.data.profile.summary);
836
+
837
+ const board = await client.getCongressionalLeaderboard({ limit: 5 });
838
+ console.log(board.best.map((row) => [row.displayName, row.excessReturn]));
839
+
840
+ const slowest = await client.listCongressionalFilingLatency({ limit: 5 });
841
+ console.log(slowest.data.map((row) => [row.displayName, row.medianDaysToPublic]));
842
+ ```
843
+
844
+ **Trade from `availableAt`.** Each trade carries `transactionDate` (when the
845
+ member traded) and `availableAt` (when the disclosure became public). The gap is
846
+ usually weeks. A backtest or signal that acts on `transactionDate` uses
847
+ information nobody outside Congress had, so every date filter here
848
+ (`fromDate`, `toDate`, `asOf`) is compared against a public date, never the trade
849
+ date. `fromDate`, `toDate` and `sort` use `firstAvailableAt`, the day the first
850
+ version of a disclosure became public. It equals `availableAt` unless the
851
+ disclosure was later amended.
852
+
853
+ Filters, all optional: `q` (free text; a phrase naming exactly one member
854
+ resolves to that member), `filerKey` (Bioguide ID such as `P000197`), `ticker`,
855
+ `chamber` (`house`, `senate`, `all`), `action` (`purchase`, `sale`, `exchange`,
856
+ `unmarked`, `all`), `instrument` (`equity`, `option`, `fund`, `bond`, `other`,
857
+ `all`), `sort` (`newest`, `oldest`), `fromDate` / `toDate` (`YYYY-MM-DD`), `asOf` (ISO
858
+ timestamp; reads the record as it was publicly known then), `cursor` and
859
+ `limit` (1 to 100, default 25). `toDate` defaults to the day of `asOf`, which
860
+ defaults to the dataset's last update (`dataUpdatedAt`), and `fromDate` defaults
861
+ to 29 days before `toDate`, so with no dates the feed covers the 30 days ending
862
+ on the last update day. `instrument` defaults to `equity`. Amounts are the disclosed brackets (`amountLow`,
863
+ `amountHigh`), never exact figures.
864
+
865
+ Each method takes the filters its route reads. The summary takes no `sort`,
866
+ `cursor` or `limit`. The filer, filing latency and volume lists take `limit`
867
+ but no `sort` or `cursor`. The member records (`getPolitician`,
868
+ `getCongressionalFiler`) take `ticker`, `action`, `instrument`, `sort`, the
869
+ dates, `cursor` and `limit`; with neither date they cover the whole record,
870
+ 2012-01-01 to today, and `instrument` defaults to `all`.
871
+
872
+ Every read except the leaderboard and the copy bot returns an envelope:
873
+ `data`, plus `snapshotId`, `asOf`, `dataUpdatedAt`, `stale`, `cache`,
874
+ `coverage` and the applied `filters`.
875
+
876
+ The detail and coverage reads need an API key with the `read` scope. Without
877
+ one they raise `NexusTradeApiError` with status 401. The client sends its key
878
+ on every read when it holds one, so a key that is supplied must be valid and
879
+ have the `read` scope even on the calls that need no key.
880
+
881
+ ```ts
882
+ const authed = new NexusTradeClient({ apiKey: process.env.NEXUSTRADE_API_KEY });
883
+
884
+ const detail = await authed.getCongressionalTrade("house:20035831:0");
885
+ console.log(detail.data.current, detail.data.history.length);
886
+
887
+ const coverage = await authed.getCongressionalCoverage();
888
+ console.log(coverage.data.events, coverage.data.latestAvailableAt);
889
+ ```
890
+
891
+ | Method | Endpoint | API key |
892
+ | --- | --- | --- |
893
+ | `listCongressionalTrades` | `GET /trades` | No |
894
+ | `getCongressionalTradeSummary` | `GET /summary` | No |
895
+ | `getCongressionalLeaderboard` | `GET /leaderboard` | No |
896
+ | `listCongressionalFilingLatency` | `GET /filer-latency` | No |
897
+ | `listCongressionalTradeVolume` | `GET /filer-volume` | No |
898
+ | `getPolitician` | `GET /politicians/:id` | No |
899
+ | `getPoliticianBot` | `GET /politicians/:id/bot` | No |
900
+ | `listCongressionalFilers` | `GET /filers` | Yes |
901
+ | `getCongressionalFiler` | `GET /filers/:filerKey` | Yes |
902
+ | `getCongressionalTrade` | `GET /trades/:eventId` | Yes |
903
+ | `getCongressionalFiling` | `GET /filings/:chamber/:docId` | Yes |
904
+ | `getCongressionalCoverage` | `GET /coverage` | Yes |
905
+
906
+ `getPoliticianBot` returns a `sharedPortfolioId` you can pass to
907
+ `forkPublicPortfolio` to copy that member's bot into your workspace.
908
+
774
909
  ## Managed watchlist universes
775
910
 
776
911
  `nt.updateWatchlist({watchlistKey, memberId, instrument, amountBasis, chamber, output})`
@@ -864,6 +999,8 @@ is missing here, so this list cannot drift from the code.
864
999
  | `getBacktest(backtestId)` | Read the operation |
865
1000
  | `waitForBacktest(backtestId, options)` | Block until terminal |
866
1001
  | `waitForBacktests(operations, options)` | Block on a whole batch |
1002
+ | `getBacktestHistory(backtestId, options)` | Equity curve, one page |
1003
+ | `listBacktestEvents(backtestId, options)` | Orders, fills and signals |
867
1004
 
868
1005
  **Optimization and walk-forward**
869
1006
 
@@ -923,6 +1060,23 @@ is missing here, so this list cannot drift from the code.
923
1060
  | `exportWorkspaceSession()` | Export an anonymous workspace for later use |
924
1061
  | `importWorkspaceSession(token)` | Resume an existing anonymous workspace |
925
1062
 
1063
+ **Congressional trades**
1064
+
1065
+ | Method | Purpose |
1066
+ | --- | --- |
1067
+ | `listCongressionalTrades({ ticker, fromDate, cursor, … })` | Disclosed trades, newest first (no API key) |
1068
+ | `getCongressionalTradeSummary({ … })` | Purchase and sale totals over the same filters (no API key) |
1069
+ | `getCongressionalLeaderboard({ limit })` | Members ranked by their copy bot against SPY (no API key) |
1070
+ | `listCongressionalFilingLatency({ … })` | Days from trade to public disclosure per member (no API key) |
1071
+ | `listCongressionalTradeVolume({ … })` | Disclosed dollar volume per member (no API key) |
1072
+ | `getPolitician(id, { … })` | One member's profile and trading record (no API key) |
1073
+ | `getPoliticianBot(id)` | A member's copy bot and cached backtest (no API key) |
1074
+ | `listCongressionalFilers({ … })` | Members with matching disclosures (API key) |
1075
+ | `getCongressionalFiler(filerKey, { … })` | One member's record by Bioguide ID (API key) |
1076
+ | `getCongressionalTrade(eventId, { asOf })` | One disclosure with its amendment history (API key) |
1077
+ | `getCongressionalFiling(chamber, docId)` | One source filing and its trades (API key) |
1078
+ | `getCongressionalCoverage()` | How much of the public record the dataset holds (API key) |
1079
+
926
1080
  **PortfolioHandle** — returned by the `portfolio(...)` builder and by
927
1081
  `getPortfolio` / `listPortfolios`.
928
1082
 
@@ -1063,7 +1217,9 @@ configures its own timeout, so passing both throws.
1063
1217
 
1064
1218
  Portfolio drafting, backtesting, optimization, walk-forward studies, and the
1065
1219
  natural-language screener, versioned under `/api/v1/nexustrade`. Market data is
1066
- available only through the natural-language screener.
1220
+ available only through the natural-language screener. Congressional trade
1221
+ disclosures are the exception: they are read from `/api/political-disclosures`
1222
+ (see [Congressional trades](#congressional-trades)).
1067
1223
  The full surface requires a registered API key; anonymous workspaces are limited
1068
1224
  to portfolio authoring/forking, backtests, and programmatic agent/chat calls.
1069
1225
  Creating a live deployment remains outside this surface.
@@ -12,6 +12,7 @@ exports.clientTransport = clientTransport;
12
12
  exports.createCustomIndicator = createCustomIndicator;
13
13
  exports.createPortfolio = createPortfolio;
14
14
  const agent_ts_1 = require("./agent.js");
15
+ const congress_ts_1 = require("./congress.js");
15
16
  const env_ts_1 = require("./env.js");
16
17
  const portfolio_ts_1 = require("./portfolio.js");
17
18
  /** Boundary adapter: builder output is JSON by construction. */
@@ -162,6 +163,15 @@ function sameOrigin(left, right) {
162
163
  function supportsUpload(transport) {
163
164
  return typeof transport.putBytes === "function";
164
165
  }
166
+ function supportsPublicApi(transport) {
167
+ return typeof transport.getPublicApi === "function";
168
+ }
169
+ async function readPublicApi(transport, path) {
170
+ if (!supportsPublicApi(transport)) {
171
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsupported_transport", "Congressional trade reads require HttpTransport.getPublicApi.");
172
+ }
173
+ return (await transport.getPublicApi(path));
174
+ }
165
175
  function assertValidApiKey(apiKey) {
166
176
  const invalid = typeof apiKey !== "string" ||
167
177
  apiKey.length === 0 ||
@@ -274,6 +284,10 @@ async function apiErrorFromResponse(response) {
274
284
  if (body.message)
275
285
  message = String(body.message);
276
286
  }
287
+ else if (typeof decoded.message === "string" && decoded.message) {
288
+ // Public REST routes answer `{ message }` with no error envelope.
289
+ message = decoded.message;
290
+ }
277
291
  }
278
292
  catch {
279
293
  // Non-JSON error bodies keep the transport-level code/message.
@@ -290,6 +304,9 @@ function workspaceSessionUrl(baseUrl) {
290
304
  parsed.hash = "";
291
305
  return parsed.toString();
292
306
  }
307
+ function publicApiUrl(baseUrl, path) {
308
+ return `${new URL(baseUrl).origin}/api/${path.replace(/^\/+/, "")}`;
309
+ }
293
310
  function supportsWorkspaceSession(transport) {
294
311
  const candidate = transport;
295
312
  return (typeof candidate.exportWorkspaceSession === "function" &&
@@ -450,6 +467,16 @@ class HttpTransport {
450
467
  if (options.idempotencyKey !== undefined) {
451
468
  headers["Idempotency-Key"] = options.idempotencyKey;
452
469
  }
470
+ return this.#send(method, url, headers, payload);
471
+ }
472
+ async getPublicApi(path) {
473
+ const headers = { Accept: "application/json" };
474
+ if (this.#apiKey !== undefined) {
475
+ headers.Authorization = `Bearer ${this.#apiKey}`;
476
+ }
477
+ return this.#send("GET", publicApiUrl(this.#baseUrl, path), headers);
478
+ }
479
+ async #send(method, url, headers, payload) {
453
480
  const controller = new AbortController();
454
481
  const timer = setTimeout(() => controller.abort(), this.#timeoutSeconds * 1000);
455
482
  try {
@@ -1389,6 +1416,29 @@ class NexusTradeClient {
1389
1416
  const response = await this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}`);
1390
1417
  return operationOf(response);
1391
1418
  }
1419
+ /** One page of a completed backtest's equity curve; follow `nextPage` until null. */
1420
+ async getBacktestHistory(backtestId, options = {}) {
1421
+ const query = encodeQuery({
1422
+ page: options.page === undefined ? undefined : String(options.page),
1423
+ page_size: options.pageSize === undefined ? undefined : String(options.pageSize),
1424
+ start_date: options.startDate,
1425
+ end_date: options.endDate,
1426
+ });
1427
+ return this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}/history${query}`);
1428
+ }
1429
+ /** One page of a backtest's event tape. The run needs `generateEvents: true`; traces last 3 days. */
1430
+ async listBacktestEvents(backtestId, options = {}) {
1431
+ const query = encodeQuery({
1432
+ event_types: options.eventTypes?.join(","),
1433
+ order_statuses: options.orderStatuses?.join(","),
1434
+ ticker: options.ticker,
1435
+ start_date: options.startDate,
1436
+ end_date: options.endDate,
1437
+ page: options.page === undefined ? undefined : String(options.page),
1438
+ page_size: options.pageSize === undefined ? undefined : String(options.pageSize),
1439
+ });
1440
+ return this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}/events${query}`);
1441
+ }
1392
1442
  /** Requires a registered API key; anonymous workspaces cannot optimize. */
1393
1443
  async createOptimization(handle, options) {
1394
1444
  return this.createPortfolioJob("optimizations", handle, options.idempotencyKey);
@@ -1431,6 +1481,76 @@ class NexusTradeClient {
1431
1481
  async waitForNlScreen(screenId, options = {}) {
1432
1482
  return waitForOperation((id) => this.getNlScreen(id), screenId, options);
1433
1483
  }
1484
+ /**
1485
+ * Congressional trade disclosures, newest first. No API key required.
1486
+ *
1487
+ * Defaults to equities first made public in the 30 days ending on the
1488
+ * dataset's last update day. `fromDate` and `toDate` filter on
1489
+ * `firstAvailableAt`. Trade from `availableAt`, when the disclosure became
1490
+ * public, never `transactionDate`.
1491
+ */
1492
+ async listCongressionalTrades(options = {}) {
1493
+ return readPublicApi(this.transport, `political-disclosures/trades${encodeQuery((0, congress_ts_1.congressionalQueryParams)(options))}`);
1494
+ }
1495
+ /** Purchase and sale totals over the same filters as the feed. No API key required. */
1496
+ async getCongressionalTradeSummary(filters = {}) {
1497
+ return readPublicApi(this.transport, `political-disclosures/summary${encodeQuery((0, congress_ts_1.congressionalQueryParams)(filters))}`);
1498
+ }
1499
+ /** Members ranked by their copy bot's cached backtest against SPY. No API key required. */
1500
+ async getCongressionalLeaderboard(options = {}) {
1501
+ return readPublicApi(this.transport, `political-disclosures/leaderboard${encodeQuery({
1502
+ limit: options.limit === undefined ? undefined : String(options.limit),
1503
+ })}`);
1504
+ }
1505
+ /** Days from trade to public disclosure per member, slowest first. No API key required. */
1506
+ async listCongressionalFilingLatency(filters = {}) {
1507
+ return readPublicApi(this.transport, `political-disclosures/filer-latency${encodeQuery((0, congress_ts_1.congressionalQueryParams)(filters))}`);
1508
+ }
1509
+ /** Disclosed dollar volume per member, largest first. No API key required. */
1510
+ async listCongressionalTradeVolume(filters = {}) {
1511
+ return readPublicApi(this.transport, `political-disclosures/filer-volume${encodeQuery((0, congress_ts_1.congressionalQueryParams)(filters))}`);
1512
+ }
1513
+ /**
1514
+ * One member's profile and whole trading record. No API key required.
1515
+ *
1516
+ * `id` is a Bioguide ID (`"P000197"`) or a page slug (`"nancy-pelosi"`).
1517
+ * With neither date the record runs from 2012-01-01 to today, and
1518
+ * `instrument` defaults to `"all"`.
1519
+ */
1520
+ async getPolitician(id, options = {}) {
1521
+ return readPublicApi(this.transport, `political-disclosures/politicians/${encodePathSegment(id)}${encodeQuery((0, congress_ts_1.congressionalQueryParams)(options))}`);
1522
+ }
1523
+ /** A member's copy bot and its cached backtest. No API key required. */
1524
+ async getPoliticianBot(id) {
1525
+ return readPublicApi(this.transport, `political-disclosures/politicians/${encodePathSegment(id)}/bot`);
1526
+ }
1527
+ /** Members with disclosures matching the filters. Requires an API key. */
1528
+ async listCongressionalFilers(filters = {}) {
1529
+ return readPublicApi(this.transport, `political-disclosures/filers${encodeQuery((0, congress_ts_1.congressionalQueryParams)(filters))}`);
1530
+ }
1531
+ /**
1532
+ * One member's summary, activity and trades by Bioguide ID. Requires an API key.
1533
+ *
1534
+ * With neither date the record runs from 2012-01-01 to today, and
1535
+ * `instrument` defaults to `"all"`.
1536
+ */
1537
+ async getCongressionalFiler(filerKey, options = {}) {
1538
+ return readPublicApi(this.transport, `political-disclosures/filers/${encodePathSegment(filerKey)}${encodeQuery((0, congress_ts_1.congressionalQueryParams)(options))}`);
1539
+ }
1540
+ /** One disclosure with its amendment history. Requires an API key. */
1541
+ async getCongressionalTrade(eventId, options = {}) {
1542
+ return readPublicApi(this.transport, `political-disclosures/trades/${encodePathSegment(eventId)}${encodeQuery({
1543
+ asOf: options.asOf,
1544
+ })}`);
1545
+ }
1546
+ /** One source filing and every trade it disclosed. Requires an API key. */
1547
+ async getCongressionalFiling(chamber, docId) {
1548
+ return readPublicApi(this.transport, `political-disclosures/filings/${encodePathSegment(chamber)}/${encodePathSegment(docId)}`);
1549
+ }
1550
+ /** How much of the public record the dataset holds. Requires an API key. */
1551
+ async getCongressionalCoverage() {
1552
+ return readPublicApi(this.transport, "political-disclosures/coverage");
1553
+ }
1434
1554
  /** Resolve once a backtest is terminal. See `waitForOperation`. */
1435
1555
  async waitForBacktest(backtestId, options = {}) {
1436
1556
  return waitForOperation((id) => this.getBacktest(id), backtestId, options);
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ /**
3
+ * Congressional (STOCK Act) disclosure types for the public REST API at
4
+ * `/api/political-disclosures`.
5
+ *
6
+ * `availableAt` is when a disclosure became public. It is the only date a
7
+ * strategy may act on: `transactionDate` is when the member traded, typically
8
+ * weeks before anyone outside Congress could know. Date filters and `sort` use
9
+ * `firstAvailableAt`, when the first version of a disclosure became public.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.congressionalQueryParams = congressionalQueryParams;
13
+ /** Query pairs in one fixed order, so both SDKs put the same bytes on the wire. */
14
+ function congressionalQueryParams(options) {
15
+ return {
16
+ q: options.q,
17
+ filerKey: options.filerKey,
18
+ ticker: options.ticker,
19
+ chamber: options.chamber,
20
+ action: options.action,
21
+ instrument: options.instrument,
22
+ sort: options.sort,
23
+ from: options.fromDate,
24
+ to: options.toDate,
25
+ asOf: options.asOf,
26
+ cursor: options.cursor,
27
+ limit: options.limit === undefined ? undefined : String(options.limit),
28
+ };
29
+ }
@@ -428,7 +428,7 @@ const updateInsiderWatchlist = (config) => ({
428
428
  type: "UpdateWatchlist", watchlistKey: config.watchlistKey,
429
429
  ...(config.output ? { output: config.output } : {}),
430
430
  source: compact({ type: "InsiderPurchases", windowDays: config.windowDays, role: config.role,
431
- ownerCik: config.ownerCik, issuerCik: config.issuerCik }),
431
+ ownerCik: config.ownerCik, issuerCik: config.issuerCik, includeAwards: config.includeAwards }),
432
432
  });
433
433
  exports.updateInsiderWatchlist = updateInsiderWatchlist;
434
434
  /** Scalar PIT screen: facts are sampled only when due. Volume uses certified completed historical OHLC at the replay interval; live quote/trade volume stays unknown. */
@@ -1256,7 +1256,7 @@ function InitialValue() {
1256
1256
  * @param asset Pass CANDIDATE in a dynamic rebalance pipeline.
1257
1257
  * @param ownerCik Exact nonzero SEC reporting owner CIK, up to 10 digits. Omit for a whole company (with issuerCik) or aggregate activity.
1258
1258
  * @param issuerCik Company CIK. With ownerCik, restricts that owner to this company. Alone, every reporting owner's events at this company, a joint filing counted once.
1259
- * @param instrument Disclosed instrument; defaults to Equity. Call/Put, award and acquisition metrics, and budget shares require ownerCik or issuerCik. AwardCount is SEC code A issuer acquisitions, not cash purchases or vested-share proof. Its default Equity bucket includes unresolved restricted units. AcquisitionCount and AcquisitionSharePercent combine public code P purchases with code A issuer acquisitions. Shares use qualifying signal counts across all the owner's tickers, or all the company's tickers under issuerCik alone.
1259
+ * @param instrument Disclosed instrument; defaults to Equity. Call/Put, award and acquisition metrics, and budget shares require ownerCik or issuerCik. AwardCount is SEC code A issuer acquisitions, not cash purchases or vested-share proof. AcquisitionValue is disclosed purchase dollars plus award shares at the target's current price. Its default Equity bucket includes unresolved restricted units. AcquisitionCount and AcquisitionSharePercent combine public code P purchases with code A issuer acquisitions. Shares use qualifying signal counts across all the owner's tickers, or all the company's tickers under issuerCik alone.
1260
1260
  */
1261
1261
  function InsiderTrades(asset, metric, role, windowDays, ownerCik, issuerCik, instrument) {
1262
1262
  const d = { type: "InsiderTrades" };
@@ -2448,18 +2448,18 @@ const geneEntryCooldownDays = (strategyIndex, values) => ({
2448
2448
  });
2449
2449
  exports.geneEntryCooldownDays = geneEntryCooldownDays;
2450
2450
  /** Sweep ConditionWindowLength (Strategy scope) over a value set. */
2451
- const geneConditionWindowLength = (strategyIndex, path, slot, values) => ({
2451
+ const geneConditionWindowLength = (strategyIndex, path, slot, values, indicatorPath) => ({
2452
2452
  field: "ConditionWindowLength",
2453
2453
  scope: "Strategy",
2454
- target: { scope: "Strategy", field: "ConditionWindowLength", strategyIndex, path, slot },
2454
+ target: { scope: "Strategy", field: "ConditionWindowLength", strategyIndex, path, slot, ...(indicatorPath === undefined ? {} : { indicatorPath }) },
2455
2455
  values: values,
2456
2456
  });
2457
2457
  exports.geneConditionWindowLength = geneConditionWindowLength;
2458
2458
  /** Sweep ConditionThreshold (Strategy scope) over a value set. */
2459
- const geneConditionThreshold = (strategyIndex, path, slot, values) => ({
2459
+ const geneConditionThreshold = (strategyIndex, path, slot, values, indicatorPath, parameter) => ({
2460
2460
  field: "ConditionThreshold",
2461
2461
  scope: "Strategy",
2462
- target: { scope: "Strategy", field: "ConditionThreshold", strategyIndex, path, slot },
2462
+ target: { scope: "Strategy", field: "ConditionThreshold", strategyIndex, path, slot, ...(indicatorPath === undefined ? {} : { indicatorPath }), ...(parameter === undefined ? {} : { parameter }) },
2463
2463
  values: values,
2464
2464
  });
2465
2465
  exports.geneConditionThreshold = geneConditionThreshold;
@@ -5,6 +5,7 @@
5
5
  * pass an API key/base URL, or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
6
6
  */
7
7
  import { AgentRun } from "./agent.ts";
8
+ import { type CongressChamber, type CongressionalCoverage, type CongressionalEnvelope, type CongressionalFiler, type CongressionalFilerDetail, type CongressionalFilerListOptions, type CongressionalFilerVolume, type CongressionalFiling, type CongressionalFilingLatency, type CongressionalLeaderboard, type CongressionalMemberRecordOptions, type CongressionalTradeDetail, type CongressionalTradeFilters, type CongressionalTradePage, type CongressionalTradeSummary, type ListCongressionalTradesOptions, type PoliticianBot, type PoliticianProfile } from "./congress.ts";
8
9
  import type { JobRequest, OrderStatus, Portfolio, Strategy } from "./generated/ntSdk.generated.js";
9
10
  import { PortfolioHandle, type DeployResult, type PortfolioListResult } from "./portfolio.ts";
10
11
  export type JsonValue = string | number | boolean | null | JsonValue[] | {
@@ -88,6 +89,24 @@ export interface ListOrdersOptions {
88
89
  limit?: number;
89
90
  includeRebalanceOrders?: boolean;
90
91
  }
92
+ export interface BacktestHistoryOptions {
93
+ page?: number;
94
+ /** Rows per page, at most 5000 (server default 500). */
95
+ pageSize?: number;
96
+ startDate?: string;
97
+ endDate?: string;
98
+ }
99
+ export interface ListBacktestEventsOptions {
100
+ /** e.g. ["Order"]. Omit for every actionable event. */
101
+ eventTypes?: ReadonlyArray<string>;
102
+ /** Order events only, e.g. ["Filled"]. */
103
+ orderStatuses?: ReadonlyArray<string>;
104
+ ticker?: string;
105
+ startDate?: string;
106
+ endDate?: string;
107
+ page?: number;
108
+ pageSize?: number;
109
+ }
91
110
  export interface ListPortfoliosOptions {
92
111
  portfolioIds?: string[];
93
112
  includeInactive?: boolean;
@@ -149,6 +168,17 @@ export interface UploadTransport extends Transport {
149
168
  contentType: string;
150
169
  }): Promise<void>;
151
170
  }
171
+ /**
172
+ * Transports that can read NexusTrade's public REST API.
173
+ *
174
+ * Those routes are served at `/api/<path>` on the API origin, beside the
175
+ * versioned SDK routes rather than under them. `path` is relative to `/api/`.
176
+ * An API key is sent when the transport holds one; an anonymous workspace
177
+ * session is never sent, because these routes do not read it.
178
+ */
179
+ export interface PublicApiTransport extends Transport {
180
+ getPublicApi(path: string): Promise<JsonObject>;
181
+ }
152
182
  export interface HttpTransportOptions {
153
183
  apiKey?: string;
154
184
  baseUrl: string;
@@ -159,7 +189,7 @@ export interface WorkspaceSessionTransport extends Transport {
159
189
  exportWorkspaceSession(): string | undefined;
160
190
  importWorkspaceSession(workspaceSession: string): void;
161
191
  }
162
- export declare class HttpTransport implements Transport, UploadTransport, WorkspaceSessionTransport {
192
+ export declare class HttpTransport implements Transport, UploadTransport, WorkspaceSessionTransport, PublicApiTransport {
163
193
  #private;
164
194
  constructor(options: HttpTransportOptions);
165
195
  get baseUrl(): string;
@@ -170,6 +200,7 @@ export declare class HttpTransport implements Transport, UploadTransport, Worksp
170
200
  contentType: string;
171
201
  }): Promise<void>;
172
202
  request(method: string, path: string, options?: RequestOptions): Promise<JsonObject>;
203
+ getPublicApi(path: string): Promise<JsonObject>;
173
204
  }
174
205
  export interface NexusTradeClientOptions {
175
206
  apiKey?: string;
@@ -453,6 +484,10 @@ export declare class NexusTradeClient {
453
484
  }): Promise<AgentRun>;
454
485
  getAgent(agentId: string): Promise<JsonObject>;
455
486
  getBacktest(backtestId: string): Promise<JsonObject>;
487
+ /** One page of a completed backtest's equity curve; follow `nextPage` until null. */
488
+ getBacktestHistory(backtestId: string, options?: BacktestHistoryOptions): Promise<JsonObject>;
489
+ /** One page of a backtest's event tape. The run needs `generateEvents: true`; traces last 3 days. */
490
+ listBacktestEvents(backtestId: string, options?: ListBacktestEventsOptions): Promise<JsonObject>;
456
491
  /** Requires a registered API key; anonymous workspaces cannot optimize. */
457
492
  createOptimization(handle: JobInput, options: {
458
493
  idempotencyKey: string;
@@ -476,6 +511,52 @@ export declare class NexusTradeClient {
476
511
  cancelNlScreen(screenId: string): Promise<JsonObject>;
477
512
  /** Block until a screen is terminal. See `waitForOperation`. */
478
513
  waitForNlScreen(screenId: string, options?: WaitOptions): Promise<JsonObject>;
514
+ /**
515
+ * Congressional trade disclosures, newest first. No API key required.
516
+ *
517
+ * Defaults to equities first made public in the 30 days ending on the
518
+ * dataset's last update day. `fromDate` and `toDate` filter on
519
+ * `firstAvailableAt`. Trade from `availableAt`, when the disclosure became
520
+ * public, never `transactionDate`.
521
+ */
522
+ listCongressionalTrades(options?: ListCongressionalTradesOptions): Promise<CongressionalEnvelope<CongressionalTradePage>>;
523
+ /** Purchase and sale totals over the same filters as the feed. No API key required. */
524
+ getCongressionalTradeSummary(filters?: CongressionalTradeFilters): Promise<CongressionalEnvelope<CongressionalTradeSummary>>;
525
+ /** Members ranked by their copy bot's cached backtest against SPY. No API key required. */
526
+ getCongressionalLeaderboard(options?: {
527
+ limit?: number;
528
+ }): Promise<CongressionalLeaderboard>;
529
+ /** Days from trade to public disclosure per member, slowest first. No API key required. */
530
+ listCongressionalFilingLatency(filters?: CongressionalFilerListOptions): Promise<CongressionalEnvelope<CongressionalFilingLatency[]>>;
531
+ /** Disclosed dollar volume per member, largest first. No API key required. */
532
+ listCongressionalTradeVolume(filters?: CongressionalFilerListOptions): Promise<CongressionalEnvelope<CongressionalFilerVolume[]>>;
533
+ /**
534
+ * One member's profile and whole trading record. No API key required.
535
+ *
536
+ * `id` is a Bioguide ID (`"P000197"`) or a page slug (`"nancy-pelosi"`).
537
+ * With neither date the record runs from 2012-01-01 to today, and
538
+ * `instrument` defaults to `"all"`.
539
+ */
540
+ getPolitician(id: string, options?: CongressionalMemberRecordOptions): Promise<CongressionalEnvelope<PoliticianProfile>>;
541
+ /** A member's copy bot and its cached backtest. No API key required. */
542
+ getPoliticianBot(id: string): Promise<PoliticianBot>;
543
+ /** Members with disclosures matching the filters. Requires an API key. */
544
+ listCongressionalFilers(filters?: CongressionalFilerListOptions): Promise<CongressionalEnvelope<CongressionalFiler[]>>;
545
+ /**
546
+ * One member's summary, activity and trades by Bioguide ID. Requires an API key.
547
+ *
548
+ * With neither date the record runs from 2012-01-01 to today, and
549
+ * `instrument` defaults to `"all"`.
550
+ */
551
+ getCongressionalFiler(filerKey: string, options?: CongressionalMemberRecordOptions): Promise<CongressionalEnvelope<CongressionalFilerDetail>>;
552
+ /** One disclosure with its amendment history. Requires an API key. */
553
+ getCongressionalTrade(eventId: string, options?: {
554
+ asOf?: string;
555
+ }): Promise<CongressionalEnvelope<CongressionalTradeDetail>>;
556
+ /** One source filing and every trade it disclosed. Requires an API key. */
557
+ getCongressionalFiling(chamber: CongressChamber, docId: string): Promise<CongressionalEnvelope<CongressionalFiling>>;
558
+ /** How much of the public record the dataset holds. Requires an API key. */
559
+ getCongressionalCoverage(): Promise<CongressionalEnvelope<CongressionalCoverage>>;
479
560
  /** Resolve once a backtest is terminal. See `waitForOperation`. */
480
561
  waitForBacktest(backtestId: string, options?: WaitOptions): Promise<JsonObject>;
481
562
  /** Resolve once an optimization is terminal. See `waitForOperation`. */
@@ -5,6 +5,7 @@
5
5
  * pass an API key/base URL, or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
6
6
  */
7
7
  import { AgentRun } from "./agent.js";
8
+ import { congressionalQueryParams, } from "./congress.js";
8
9
  import { LazyDotenv, environmentValue } from "./env.js";
9
10
  import { portfolioHandleFromWire, } from "./portfolio.js";
10
11
  /** Boundary adapter: builder output is JSON by construction. */
@@ -153,6 +154,15 @@ function sameOrigin(left, right) {
153
154
  function supportsUpload(transport) {
154
155
  return typeof transport.putBytes === "function";
155
156
  }
157
+ function supportsPublicApi(transport) {
158
+ return typeof transport.getPublicApi === "function";
159
+ }
160
+ async function readPublicApi(transport, path) {
161
+ if (!supportsPublicApi(transport)) {
162
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "unsupported_transport", "Congressional trade reads require HttpTransport.getPublicApi.");
163
+ }
164
+ return (await transport.getPublicApi(path));
165
+ }
156
166
  function assertValidApiKey(apiKey) {
157
167
  const invalid = typeof apiKey !== "string" ||
158
168
  apiKey.length === 0 ||
@@ -265,6 +275,10 @@ async function apiErrorFromResponse(response) {
265
275
  if (body.message)
266
276
  message = String(body.message);
267
277
  }
278
+ else if (typeof decoded.message === "string" && decoded.message) {
279
+ // Public REST routes answer `{ message }` with no error envelope.
280
+ message = decoded.message;
281
+ }
268
282
  }
269
283
  catch {
270
284
  // Non-JSON error bodies keep the transport-level code/message.
@@ -281,6 +295,9 @@ function workspaceSessionUrl(baseUrl) {
281
295
  parsed.hash = "";
282
296
  return parsed.toString();
283
297
  }
298
+ function publicApiUrl(baseUrl, path) {
299
+ return `${new URL(baseUrl).origin}/api/${path.replace(/^\/+/, "")}`;
300
+ }
284
301
  function supportsWorkspaceSession(transport) {
285
302
  const candidate = transport;
286
303
  return (typeof candidate.exportWorkspaceSession === "function" &&
@@ -441,6 +458,16 @@ export class HttpTransport {
441
458
  if (options.idempotencyKey !== undefined) {
442
459
  headers["Idempotency-Key"] = options.idempotencyKey;
443
460
  }
461
+ return this.#send(method, url, headers, payload);
462
+ }
463
+ async getPublicApi(path) {
464
+ const headers = { Accept: "application/json" };
465
+ if (this.#apiKey !== undefined) {
466
+ headers.Authorization = `Bearer ${this.#apiKey}`;
467
+ }
468
+ return this.#send("GET", publicApiUrl(this.#baseUrl, path), headers);
469
+ }
470
+ async #send(method, url, headers, payload) {
444
471
  const controller = new AbortController();
445
472
  const timer = setTimeout(() => controller.abort(), this.#timeoutSeconds * 1000);
446
473
  try {
@@ -1379,6 +1406,29 @@ export class NexusTradeClient {
1379
1406
  const response = await this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}`);
1380
1407
  return operationOf(response);
1381
1408
  }
1409
+ /** One page of a completed backtest's equity curve; follow `nextPage` until null. */
1410
+ async getBacktestHistory(backtestId, options = {}) {
1411
+ const query = encodeQuery({
1412
+ page: options.page === undefined ? undefined : String(options.page),
1413
+ page_size: options.pageSize === undefined ? undefined : String(options.pageSize),
1414
+ start_date: options.startDate,
1415
+ end_date: options.endDate,
1416
+ });
1417
+ return this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}/history${query}`);
1418
+ }
1419
+ /** One page of a backtest's event tape. The run needs `generateEvents: true`; traces last 3 days. */
1420
+ async listBacktestEvents(backtestId, options = {}) {
1421
+ const query = encodeQuery({
1422
+ event_types: options.eventTypes?.join(","),
1423
+ order_statuses: options.orderStatuses?.join(","),
1424
+ ticker: options.ticker,
1425
+ start_date: options.startDate,
1426
+ end_date: options.endDate,
1427
+ page: options.page === undefined ? undefined : String(options.page),
1428
+ page_size: options.pageSize === undefined ? undefined : String(options.pageSize),
1429
+ });
1430
+ return this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}/events${query}`);
1431
+ }
1382
1432
  /** Requires a registered API key; anonymous workspaces cannot optimize. */
1383
1433
  async createOptimization(handle, options) {
1384
1434
  return this.createPortfolioJob("optimizations", handle, options.idempotencyKey);
@@ -1421,6 +1471,76 @@ export class NexusTradeClient {
1421
1471
  async waitForNlScreen(screenId, options = {}) {
1422
1472
  return waitForOperation((id) => this.getNlScreen(id), screenId, options);
1423
1473
  }
1474
+ /**
1475
+ * Congressional trade disclosures, newest first. No API key required.
1476
+ *
1477
+ * Defaults to equities first made public in the 30 days ending on the
1478
+ * dataset's last update day. `fromDate` and `toDate` filter on
1479
+ * `firstAvailableAt`. Trade from `availableAt`, when the disclosure became
1480
+ * public, never `transactionDate`.
1481
+ */
1482
+ async listCongressionalTrades(options = {}) {
1483
+ return readPublicApi(this.transport, `political-disclosures/trades${encodeQuery(congressionalQueryParams(options))}`);
1484
+ }
1485
+ /** Purchase and sale totals over the same filters as the feed. No API key required. */
1486
+ async getCongressionalTradeSummary(filters = {}) {
1487
+ return readPublicApi(this.transport, `political-disclosures/summary${encodeQuery(congressionalQueryParams(filters))}`);
1488
+ }
1489
+ /** Members ranked by their copy bot's cached backtest against SPY. No API key required. */
1490
+ async getCongressionalLeaderboard(options = {}) {
1491
+ return readPublicApi(this.transport, `political-disclosures/leaderboard${encodeQuery({
1492
+ limit: options.limit === undefined ? undefined : String(options.limit),
1493
+ })}`);
1494
+ }
1495
+ /** Days from trade to public disclosure per member, slowest first. No API key required. */
1496
+ async listCongressionalFilingLatency(filters = {}) {
1497
+ return readPublicApi(this.transport, `political-disclosures/filer-latency${encodeQuery(congressionalQueryParams(filters))}`);
1498
+ }
1499
+ /** Disclosed dollar volume per member, largest first. No API key required. */
1500
+ async listCongressionalTradeVolume(filters = {}) {
1501
+ return readPublicApi(this.transport, `political-disclosures/filer-volume${encodeQuery(congressionalQueryParams(filters))}`);
1502
+ }
1503
+ /**
1504
+ * One member's profile and whole trading record. No API key required.
1505
+ *
1506
+ * `id` is a Bioguide ID (`"P000197"`) or a page slug (`"nancy-pelosi"`).
1507
+ * With neither date the record runs from 2012-01-01 to today, and
1508
+ * `instrument` defaults to `"all"`.
1509
+ */
1510
+ async getPolitician(id, options = {}) {
1511
+ return readPublicApi(this.transport, `political-disclosures/politicians/${encodePathSegment(id)}${encodeQuery(congressionalQueryParams(options))}`);
1512
+ }
1513
+ /** A member's copy bot and its cached backtest. No API key required. */
1514
+ async getPoliticianBot(id) {
1515
+ return readPublicApi(this.transport, `political-disclosures/politicians/${encodePathSegment(id)}/bot`);
1516
+ }
1517
+ /** Members with disclosures matching the filters. Requires an API key. */
1518
+ async listCongressionalFilers(filters = {}) {
1519
+ return readPublicApi(this.transport, `political-disclosures/filers${encodeQuery(congressionalQueryParams(filters))}`);
1520
+ }
1521
+ /**
1522
+ * One member's summary, activity and trades by Bioguide ID. Requires an API key.
1523
+ *
1524
+ * With neither date the record runs from 2012-01-01 to today, and
1525
+ * `instrument` defaults to `"all"`.
1526
+ */
1527
+ async getCongressionalFiler(filerKey, options = {}) {
1528
+ return readPublicApi(this.transport, `political-disclosures/filers/${encodePathSegment(filerKey)}${encodeQuery(congressionalQueryParams(options))}`);
1529
+ }
1530
+ /** One disclosure with its amendment history. Requires an API key. */
1531
+ async getCongressionalTrade(eventId, options = {}) {
1532
+ return readPublicApi(this.transport, `political-disclosures/trades/${encodePathSegment(eventId)}${encodeQuery({
1533
+ asOf: options.asOf,
1534
+ })}`);
1535
+ }
1536
+ /** One source filing and every trade it disclosed. Requires an API key. */
1537
+ async getCongressionalFiling(chamber, docId) {
1538
+ return readPublicApi(this.transport, `political-disclosures/filings/${encodePathSegment(chamber)}/${encodePathSegment(docId)}`);
1539
+ }
1540
+ /** How much of the public record the dataset holds. Requires an API key. */
1541
+ async getCongressionalCoverage() {
1542
+ return readPublicApi(this.transport, "political-disclosures/coverage");
1543
+ }
1424
1544
  /** Resolve once a backtest is terminal. See `waitForOperation`. */
1425
1545
  async waitForBacktest(backtestId, options = {}) {
1426
1546
  return waitForOperation((id) => this.getBacktest(id), backtestId, options);
@@ -0,0 +1,390 @@
1
+ /**
2
+ * Congressional (STOCK Act) disclosure types for the public REST API at
3
+ * `/api/political-disclosures`.
4
+ *
5
+ * `availableAt` is when a disclosure became public. It is the only date a
6
+ * strategy may act on: `transactionDate` is when the member traded, typically
7
+ * weeks before anyone outside Congress could know. Date filters and `sort` use
8
+ * `firstAvailableAt`, when the first version of a disclosure became public.
9
+ */
10
+ export type CongressChamber = "house" | "senate";
11
+ export type CongressAction = "purchase" | "sale" | "exchange" | "unmarked";
12
+ export type CongressInstrument = "equity" | "option" | "fund" | "bond" | "other";
13
+ export type CongressOwner = "self" | "spouse" | "dependent_child" | "joint" | "not_indicated";
14
+ export type CongressParty = "Democrat" | "Republican" | "Independent" | "Other";
15
+ export type CongressParseMethod = "text" | "scan" | "html" | "paper";
16
+ export type CongressSort = "newest" | "oldest";
17
+ /**
18
+ * Filters shared by the trade feed and its aggregates.
19
+ *
20
+ * `toDate` defaults to the day of `asOf`, which defaults to the dataset's last
21
+ * update. With no `fromDate` the window is the 30 days ending at `toDate`.
22
+ * `instrument` defaults to `"equity"`; pass `"all"` to include options, funds
23
+ * and bonds.
24
+ */
25
+ export interface CongressionalTradeFilters {
26
+ /** Free-text search. A phrase naming exactly one member resolves to that member. */
27
+ q?: string;
28
+ /** Bioguide ID, for example `"P000197"`. */
29
+ filerKey?: string;
30
+ ticker?: string;
31
+ chamber?: CongressChamber | "all";
32
+ action?: CongressAction | "all";
33
+ instrument?: CongressInstrument | "all";
34
+ /** `YYYY-MM-DD`, compared against the day of `firstAvailableAt`. Sent as `from`. */
35
+ fromDate?: string;
36
+ /** `YYYY-MM-DD`, compared against the day of `firstAvailableAt`. Sent as `to`. */
37
+ toDate?: string;
38
+ /** ISO timestamp. Reads the record as it was publicly known at that instant. */
39
+ asOf?: string;
40
+ }
41
+ /** The trade feed: the shared filters plus ordering and paging. */
42
+ export interface ListCongressionalTradesOptions extends CongressionalTradeFilters {
43
+ /** Orders by `firstAvailableAt`. Default `"newest"`. */
44
+ sort?: CongressSort;
45
+ /** `nextCursor` from the previous page, sent with the same filters. */
46
+ cursor?: string;
47
+ /** 1 to 100. Default 25. */
48
+ limit?: number;
49
+ }
50
+ /** The per-member lists (filers, filing latency, volume). Each has a fixed order. */
51
+ export interface CongressionalFilerListOptions extends CongressionalTradeFilters {
52
+ /** 1 to 100. Default 25. */
53
+ limit?: number;
54
+ }
55
+ /**
56
+ * One member's record, for `getPolitician` and `getCongressionalFiler`.
57
+ *
58
+ * With neither date the record runs from 2012-01-01 to today. With only one,
59
+ * the other takes the feed default. `instrument` defaults to `"all"`.
60
+ */
61
+ export interface CongressionalMemberRecordOptions {
62
+ ticker?: string;
63
+ action?: CongressAction | "all";
64
+ instrument?: CongressInstrument | "all";
65
+ /** Orders the trades by `firstAvailableAt`. Default `"newest"`. */
66
+ sort?: CongressSort;
67
+ /** `YYYY-MM-DD`, compared against the day of `firstAvailableAt`. Sent as `from`. */
68
+ fromDate?: string;
69
+ /** `YYYY-MM-DD`, compared against the day of `firstAvailableAt`. Sent as `to`. */
70
+ toDate?: string;
71
+ /** ISO timestamp. Reads the record as it was publicly known at that instant. */
72
+ asOf?: string;
73
+ /** `recentTradesNextCursor` from the previous page, sent with the same filters. */
74
+ cursor?: string;
75
+ /** Trades per page, 1 to 100. Default 25. */
76
+ limit?: number;
77
+ }
78
+ /** The filters the server applied, defaults included. */
79
+ export interface CongressionalAppliedFilters {
80
+ q: string | null;
81
+ filerKey: string | null;
82
+ ticker: string | null;
83
+ chamber: CongressChamber | "all";
84
+ action: CongressAction | "all";
85
+ instrument: CongressInstrument | "all";
86
+ sort: CongressSort;
87
+ from: string;
88
+ to: string;
89
+ asOf: string;
90
+ cursor: string | null;
91
+ limit: number;
92
+ }
93
+ export interface CongressionalCoverage {
94
+ filings: number;
95
+ events: number;
96
+ failedFilings: number;
97
+ latestAvailableAt: string | null;
98
+ latestProcessedAt: string | null;
99
+ byChamber: Record<CongressChamber, {
100
+ filings: number | null;
101
+ latestFilingDate: string | null;
102
+ }>;
103
+ }
104
+ /** Every disclosure read except the leaderboard and the copy bot. */
105
+ export interface CongressionalEnvelope<T> {
106
+ data: T;
107
+ snapshotId: string;
108
+ asOf: string;
109
+ dataUpdatedAt: string;
110
+ stale: boolean;
111
+ cache: "hit" | "miss" | "stale";
112
+ coverage: CongressionalCoverage | null;
113
+ filters: CongressionalAppliedFilters | null;
114
+ }
115
+ export interface CongressionalTrade {
116
+ /** `<chamber>:<docId>:<rowIndex>`, for example `"house:20035831:0"`. */
117
+ eventId: string;
118
+ version: number;
119
+ filerKey: string;
120
+ filerName: string;
121
+ chamber: CongressChamber;
122
+ owner: CongressOwner;
123
+ action: CongressAction;
124
+ partialSale: boolean;
125
+ instrument: CongressInstrument;
126
+ /** When the member traded. Not public knowledge on this date. */
127
+ transactionDate: string | null;
128
+ filingDate: string;
129
+ /** When the first version became public. `from`, `to` and `sort` use this. */
130
+ firstAvailableAt: string;
131
+ /** When this version became public. The date to trade from. */
132
+ availableAt: string;
133
+ supersededAt: string | null;
134
+ ticker: string | null;
135
+ assetDescription: string;
136
+ assetTypeCode: string | null;
137
+ assetTypeLabel: string | null;
138
+ /** Disclosures report a bracket, never an amount. */
139
+ amountBracket: string | null;
140
+ amountLow: number | null;
141
+ amountHigh: number | null;
142
+ tickerResolutionStatus: string | null;
143
+ sourceDocId: string;
144
+ sourceRowIndex: number;
145
+ sourceUrl: string;
146
+ /** `"scan"` and `"paper"` rows were read from an image. */
147
+ sourceParseMethod: CongressParseMethod | null;
148
+ }
149
+ export interface CongressMemberBadge {
150
+ party: CongressParty | null;
151
+ state: string | null;
152
+ slug: string;
153
+ }
154
+ export interface CongressionalTradePage {
155
+ trades: CongressionalTrade[];
156
+ /** Pass as `cursor` with the same filters; null on the last page. */
157
+ nextCursor: string | null;
158
+ /** `filerKey` to badge, for the members on this page. */
159
+ members?: Record<string, CongressMemberBadge>;
160
+ }
161
+ export interface CongressionalVolumeRank {
162
+ ticker: string;
163
+ events: number;
164
+ amountLow: number | null;
165
+ amountHigh: number | null;
166
+ }
167
+ export interface CongressionalTradeSummary {
168
+ purchaseEvents: number;
169
+ saleEvents: number;
170
+ otherEvents: number;
171
+ activeFilers: number;
172
+ disclosedEvents: number;
173
+ purchaseAmountLow: number | null;
174
+ purchaseAmountHigh: number | null;
175
+ purchaseMissingLow: number;
176
+ purchaseMissingHigh: number;
177
+ saleAmountLow: number | null;
178
+ saleAmountHigh: number | null;
179
+ saleMissingLow: number;
180
+ saleMissingHigh: number;
181
+ netAmountLow: number | null;
182
+ netAmountHigh: number | null;
183
+ unresolvedTickerEvents: number;
184
+ mostPurchased: Array<{
185
+ ticker: string;
186
+ events: number;
187
+ }>;
188
+ mostPurchasedByVolume?: CongressionalVolumeRank[];
189
+ }
190
+ export interface CongressionalFiler {
191
+ filerKey: string;
192
+ displayName: string;
193
+ chamber: CongressChamber;
194
+ disclosureEvents: number;
195
+ purchaseEvents: number;
196
+ saleEvents: number;
197
+ latestDisclosureAt: string | null;
198
+ identityStatus: "member";
199
+ }
200
+ export interface CongressionalFilerYearActivity {
201
+ year: number;
202
+ purchases: number;
203
+ sales: number;
204
+ purchaseMidpoint: number | null;
205
+ saleMidpoint: number | null;
206
+ }
207
+ export interface CongressionalFilerActivity {
208
+ byYear: CongressionalFilerYearActivity[];
209
+ firstPublicAt: string | null;
210
+ lastPublicAt: string | null;
211
+ filings: number;
212
+ /** Filings carrying a trade made public more than 45 days after it. */
213
+ lateFilings: number;
214
+ }
215
+ export interface CongressionalFilerDetail {
216
+ filer: CongressionalFiler;
217
+ summary: CongressionalTradeSummary;
218
+ recentTrades: CongressionalTrade[];
219
+ recentTradesNextCursor: string | null;
220
+ activity: CongressionalFilerActivity;
221
+ }
222
+ /** How long one member's disclosures take to become public. */
223
+ export interface CongressionalFilingLatency {
224
+ filerKey: string;
225
+ displayName: string;
226
+ transactions: number;
227
+ filings: number;
228
+ medianDaysToPublic: number | null;
229
+ p95DaysToPublic: number | null;
230
+ transactionsOverFortyFiveDays: number;
231
+ filingsOverFortyFiveDays: number;
232
+ }
233
+ /** One member's disclosed dollars, as sums of bracket bounds. */
234
+ export interface CongressionalFilerVolume {
235
+ filerKey: string;
236
+ displayName: string;
237
+ transactions: number;
238
+ purchaseTransactions: number;
239
+ saleTransactions: number;
240
+ filings: number;
241
+ volumeLow: number;
242
+ /** Null when any bracket is open-ended. */
243
+ volumeHigh: number | null;
244
+ volumeMidpoint: number;
245
+ openEndedTransactions: number;
246
+ party?: CongressParty | null;
247
+ state?: string | null;
248
+ slug?: string | null;
249
+ }
250
+ export interface CongressCommitteeAssignment {
251
+ id: string;
252
+ name: string;
253
+ title: string | null;
254
+ }
255
+ export interface Politician {
256
+ /** Bioguide ID. */
257
+ memberId: string;
258
+ slug: string;
259
+ displayName: string;
260
+ party: CongressParty | null;
261
+ committees: CongressCommitteeAssignment[];
262
+ imageUrl: string | null;
263
+ chamber: CongressChamber | null;
264
+ state: string | null;
265
+ district: number | null;
266
+ firstTookOffice: string | null;
267
+ lastServedEnd: string | null;
268
+ }
269
+ export interface PoliticianProfile {
270
+ politician: Politician;
271
+ profile: CongressionalFilerDetail;
272
+ }
273
+ export interface PoliticianBotStatistics {
274
+ totalReturn: number;
275
+ cagr: number | null;
276
+ fiveYearEquivalent: number | null;
277
+ spyTotalReturn: number | null;
278
+ spyCagr: number | null;
279
+ spyFiveYearEquivalent: number | null;
280
+ sharpe: number | null;
281
+ sortino: number | null;
282
+ maxDrawdown: number | null;
283
+ closedTrades: number | null;
284
+ fees: number | null;
285
+ medianDeployment: number | null;
286
+ distinctNames: number | null;
287
+ }
288
+ export interface PoliticianBotCurvePoint {
289
+ date: string;
290
+ value: number;
291
+ performanceValue?: number;
292
+ spy: number | null;
293
+ }
294
+ /** A member's copy bot: a cached engine backtest of following their disclosures. */
295
+ export interface PoliticianBot {
296
+ status: "ready" | "stale" | "computing" | "ineligible";
297
+ memberId: string;
298
+ displayName: string | null;
299
+ purchaseCount: number | null;
300
+ minPurchases: number;
301
+ profileId: string | null;
302
+ /** Pass to `forkPublicPortfolio` to copy the bot into your workspace. */
303
+ sharedPortfolioId: string | null;
304
+ windowStart: string | null;
305
+ windowEnd: string | null;
306
+ refreshedAt: string | null;
307
+ refreshRequestedAt: string | null;
308
+ refreshPending: boolean;
309
+ initialValue: number;
310
+ statistics: PoliticianBotStatistics | null;
311
+ curve: PoliticianBotCurvePoint[];
312
+ mixed: boolean;
313
+ }
314
+ export interface CongressionalLeaderboardRow {
315
+ memberId: string;
316
+ displayName: string;
317
+ slug: string | null;
318
+ party: CongressParty | null;
319
+ chamber: CongressChamber | null;
320
+ state: string | null;
321
+ windowStart: string;
322
+ windowEnd: string;
323
+ mixed: boolean;
324
+ totalReturn: number;
325
+ spyTotalReturn: number;
326
+ /** `totalReturn` minus `spyTotalReturn`. */
327
+ excessReturn: number;
328
+ /** `(1 + cagr)^5 - 1`, the ranking basis. */
329
+ fiveYearEquivalent: number | null;
330
+ sharpe: number | null;
331
+ maxDrawdown: number | null;
332
+ purchaseCount: number;
333
+ imageUrl: string | null;
334
+ lastServedEnd: string | null;
335
+ spark: {
336
+ bot: number[];
337
+ spy: Array<number | null>;
338
+ } | null;
339
+ }
340
+ export interface CongressionalLeaderboard {
341
+ /** Members whose copy bot beat SPY, best first. */
342
+ best: CongressionalLeaderboardRow[];
343
+ featured: {
344
+ memberId: string;
345
+ initialValue: number;
346
+ windowEnd: string;
347
+ curve: PoliticianBotCurvePoint[];
348
+ } | null;
349
+ /** Members whose copy bot trailed SPY, worst first. */
350
+ worst: CongressionalLeaderboardRow[];
351
+ byParty: Array<{
352
+ party: CongressParty | "Unknown";
353
+ members: number;
354
+ meanExcessReturn: number;
355
+ }>;
356
+ basis: {
357
+ rankedMembers: number;
358
+ beatSpy: number;
359
+ meanExcessReturn: number | null;
360
+ minPurchases: number;
361
+ minWindowDays: number;
362
+ benchmark: "SPY";
363
+ /** Starting capital of every ranked book. */
364
+ initialValue: number;
365
+ refreshedAt: string | null;
366
+ minPartyMembers: number;
367
+ };
368
+ }
369
+ export interface CongressionalTradeDetail {
370
+ current: CongressionalTrade;
371
+ /** Every version of the disclosure public as of the read, amendments included. */
372
+ history: CongressionalTrade[];
373
+ }
374
+ export interface CongressionalFiling {
375
+ chamber: CongressChamber;
376
+ docId: string;
377
+ filerKey: string | null;
378
+ filerName: string;
379
+ stateDistrict: string | null;
380
+ filingDate: string;
381
+ availableAt: string;
382
+ sourceUrl: string;
383
+ extractionStatus: "ok" | "failed" | "unsupported";
384
+ extractedRows: number;
385
+ amendedReportDate: string | null;
386
+ reportDate: string | null;
387
+ trades: CongressionalTrade[];
388
+ }
389
+ /** Query pairs in one fixed order, so both SDKs put the same bytes on the wire. */
390
+ export declare function congressionalQueryParams(options: ListCongressionalTradesOptions): Record<string, string | undefined>;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Congressional (STOCK Act) disclosure types for the public REST API at
3
+ * `/api/political-disclosures`.
4
+ *
5
+ * `availableAt` is when a disclosure became public. It is the only date a
6
+ * strategy may act on: `transactionDate` is when the member traded, typically
7
+ * weeks before anyone outside Congress could know. Date filters and `sort` use
8
+ * `firstAvailableAt`, when the first version of a disclosure became public.
9
+ */
10
+ /** Query pairs in one fixed order, so both SDKs put the same bytes on the wire. */
11
+ export function congressionalQueryParams(options) {
12
+ return {
13
+ q: options.q,
14
+ filerKey: options.filerKey,
15
+ ticker: options.ticker,
16
+ chamber: options.chamber,
17
+ action: options.action,
18
+ instrument: options.instrument,
19
+ sort: options.sort,
20
+ from: options.fromDate,
21
+ to: options.toDate,
22
+ asOf: options.asOf,
23
+ cursor: options.cursor,
24
+ limit: options.limit === undefined ? undefined : String(options.limit),
25
+ };
26
+ }
@@ -313,6 +313,7 @@ export type DisclosureWatchlistSource = {
313
313
  role?: "Any" | "Officer" | "Director" | "TenPercentOwner" | "OfficerOrDirector";
314
314
  ownerCik?: string;
315
315
  issuerCik?: string;
316
+ includeAwards?: boolean;
316
317
  };
317
318
  export type ScreenMetric = {
318
319
  type: "ObservedPrice" | "BarVolume" | "BarDollarVolume";
@@ -758,6 +759,7 @@ export declare const updateInsiderWatchlist: (config: {
758
759
  role?: "Any" | "Officer" | "Director" | "TenPercentOwner" | "OfficerOrDirector";
759
760
  ownerCik?: string;
760
761
  issuerCik?: string;
762
+ includeAwards?: boolean;
761
763
  output?: UpdateWatchlistAction["output"];
762
764
  }) => UpdateWatchlistAction & {
763
765
  source: Extract<DisclosureWatchlistSource, {
@@ -1269,9 +1271,9 @@ export declare function InitialValue(): Indicator;
1269
1271
  * @param asset Pass CANDIDATE in a dynamic rebalance pipeline.
1270
1272
  * @param ownerCik Exact nonzero SEC reporting owner CIK, up to 10 digits. Omit for a whole company (with issuerCik) or aggregate activity.
1271
1273
  * @param issuerCik Company CIK. With ownerCik, restricts that owner to this company. Alone, every reporting owner's events at this company, a joint filing counted once.
1272
- * @param instrument Disclosed instrument; defaults to Equity. Call/Put, award and acquisition metrics, and budget shares require ownerCik or issuerCik. AwardCount is SEC code A issuer acquisitions, not cash purchases or vested-share proof. Its default Equity bucket includes unresolved restricted units. AcquisitionCount and AcquisitionSharePercent combine public code P purchases with code A issuer acquisitions. Shares use qualifying signal counts across all the owner's tickers, or all the company's tickers under issuerCik alone.
1274
+ * @param instrument Disclosed instrument; defaults to Equity. Call/Put, award and acquisition metrics, and budget shares require ownerCik or issuerCik. AwardCount is SEC code A issuer acquisitions, not cash purchases or vested-share proof. AcquisitionValue is disclosed purchase dollars plus award shares at the target's current price. Its default Equity bucket includes unresolved restricted units. AcquisitionCount and AcquisitionSharePercent combine public code P purchases with code A issuer acquisitions. Shares use qualifying signal counts across all the owner's tickers, or all the company's tickers under issuerCik alone.
1273
1275
  */
1274
- export declare function InsiderTrades(asset: AssetArg, metric: "NetValue" | "BuyValue" | "SellValue" | "NetShares" | "BuyCount" | "SellCount" | "AwardCount" | "AcquisitionCount" | "DistinctBuyers" | "PurchaseSharePercent" | "AcquisitionSharePercent", role: Role, windowDays: number, ownerCik?: string, issuerCik?: string, instrument?: Instrument): Indicator;
1276
+ export declare function InsiderTrades(asset: AssetArg, metric: "NetValue" | "BuyValue" | "SellValue" | "NetShares" | "BuyCount" | "SellCount" | "AwardCount" | "AcquisitionValue" | "AcquisitionCount" | "DistinctBuyers" | "PurchaseSharePercent" | "AcquisitionSharePercent", role: Role, windowDays: number, ownerCik?: string, issuerCik?: string, instrument?: Instrument): Indicator;
1275
1277
  /**
1276
1278
  * Institutional positions in the asset disclosed on SEC Form 13F. Naming a manager follows one institution; an empty manager reads every manager holding the asset (SDK code passes an empty string). Level metrics read the latest quarter whose filing became public on or before the evaluation date; change metrics compare it with the quarter before. Positions are never summed across quarters, and an amended filing replaces the original only from the moment the amendment became public. Range: Counts, shares, dollars or a top-5 share of holdings; 0 when no 13F naming the asset was public within the window.
1277
1279
  * @param asset Ticker name (ex. SPY, BTC)
@@ -2046,9 +2048,9 @@ export declare const geneReplaceExitCondition: (strategyIndex: number, values: {
2046
2048
  /** Sweep EntryCooldownDays (Strategy scope) over a value set. */
2047
2049
  export declare const geneEntryCooldownDays: (strategyIndex: number, values: number[]) => Gene;
2048
2050
  /** Sweep ConditionWindowLength (Strategy scope) over a value set. */
2049
- export declare const geneConditionWindowLength: (strategyIndex: number, path: number[], slot: ConditionNodeSlot, values: number[]) => Gene;
2051
+ export declare const geneConditionWindowLength: (strategyIndex: number, path: number[], slot: ConditionNodeSlot, values: number[], indicatorPath?: number[]) => Gene;
2050
2052
  /** Sweep ConditionThreshold (Strategy scope) over a value set. */
2051
- export declare const geneConditionThreshold: (strategyIndex: number, path: number[], slot: ConditionNodeSlot, values: number[]) => Gene;
2053
+ export declare const geneConditionThreshold: (strategyIndex: number, path: number[], slot: ConditionNodeSlot, values: number[], indicatorPath?: number[], parameter?: string) => Gene;
2052
2054
  /** Sweep RankSignal (Action scope) over a value set. */
2053
2055
  export declare const geneRankSignal: (strategyIndex: number, values: {
2054
2056
  label: string;
@@ -231,7 +231,7 @@ export const updateInsiderWatchlist = (config) => ({
231
231
  type: "UpdateWatchlist", watchlistKey: config.watchlistKey,
232
232
  ...(config.output ? { output: config.output } : {}),
233
233
  source: compact({ type: "InsiderPurchases", windowDays: config.windowDays, role: config.role,
234
- ownerCik: config.ownerCik, issuerCik: config.issuerCik }),
234
+ ownerCik: config.ownerCik, issuerCik: config.issuerCik, includeAwards: config.includeAwards }),
235
235
  });
236
236
  /** Scalar PIT screen: facts are sampled only when due. Volume uses certified completed historical OHLC at the replay interval; live quote/trade volume stays unknown. */
237
237
  export const updateScreenerWatchlist = (config) => ({
@@ -1024,7 +1024,7 @@ export function InitialValue() {
1024
1024
  * @param asset Pass CANDIDATE in a dynamic rebalance pipeline.
1025
1025
  * @param ownerCik Exact nonzero SEC reporting owner CIK, up to 10 digits. Omit for a whole company (with issuerCik) or aggregate activity.
1026
1026
  * @param issuerCik Company CIK. With ownerCik, restricts that owner to this company. Alone, every reporting owner's events at this company, a joint filing counted once.
1027
- * @param instrument Disclosed instrument; defaults to Equity. Call/Put, award and acquisition metrics, and budget shares require ownerCik or issuerCik. AwardCount is SEC code A issuer acquisitions, not cash purchases or vested-share proof. Its default Equity bucket includes unresolved restricted units. AcquisitionCount and AcquisitionSharePercent combine public code P purchases with code A issuer acquisitions. Shares use qualifying signal counts across all the owner's tickers, or all the company's tickers under issuerCik alone.
1027
+ * @param instrument Disclosed instrument; defaults to Equity. Call/Put, award and acquisition metrics, and budget shares require ownerCik or issuerCik. AwardCount is SEC code A issuer acquisitions, not cash purchases or vested-share proof. AcquisitionValue is disclosed purchase dollars plus award shares at the target's current price. Its default Equity bucket includes unresolved restricted units. AcquisitionCount and AcquisitionSharePercent combine public code P purchases with code A issuer acquisitions. Shares use qualifying signal counts across all the owner's tickers, or all the company's tickers under issuerCik alone.
1028
1028
  */
1029
1029
  export function InsiderTrades(asset, metric, role, windowDays, ownerCik, issuerCik, instrument) {
1030
1030
  const d = { type: "InsiderTrades" };
@@ -2207,17 +2207,17 @@ export const geneEntryCooldownDays = (strategyIndex, values) => ({
2207
2207
  values: values,
2208
2208
  });
2209
2209
  /** Sweep ConditionWindowLength (Strategy scope) over a value set. */
2210
- export const geneConditionWindowLength = (strategyIndex, path, slot, values) => ({
2210
+ export const geneConditionWindowLength = (strategyIndex, path, slot, values, indicatorPath) => ({
2211
2211
  field: "ConditionWindowLength",
2212
2212
  scope: "Strategy",
2213
- target: { scope: "Strategy", field: "ConditionWindowLength", strategyIndex, path, slot },
2213
+ target: { scope: "Strategy", field: "ConditionWindowLength", strategyIndex, path, slot, ...(indicatorPath === undefined ? {} : { indicatorPath }) },
2214
2214
  values: values,
2215
2215
  });
2216
2216
  /** Sweep ConditionThreshold (Strategy scope) over a value set. */
2217
- export const geneConditionThreshold = (strategyIndex, path, slot, values) => ({
2217
+ export const geneConditionThreshold = (strategyIndex, path, slot, values, indicatorPath, parameter) => ({
2218
2218
  field: "ConditionThreshold",
2219
2219
  scope: "Strategy",
2220
- target: { scope: "Strategy", field: "ConditionThreshold", strategyIndex, path, slot },
2220
+ target: { scope: "Strategy", field: "ConditionThreshold", strategyIndex, path, slot, ...(indicatorPath === undefined ? {} : { indicatorPath }), ...(parameter === undefined ? {} : { parameter }) },
2221
2221
  values: values,
2222
2222
  });
2223
2223
  /** Sweep RankSignal (Action scope) over a value set. */
@@ -1,7 +1,8 @@
1
1
  export { AgentRun } from "./agent.js";
2
2
  export type { AgentEvent, AgentRunOptions } from "./agent.js";
3
3
  export { HttpTransport, NexusTradeApiError, NexusTradeClient, NexusTradeWorkspaceSessionExpiredError, createCustomIndicator, createPortfolio, waitForOperation, } from "./client.js";
4
- export type { AddStrategiesOperation, BacktestCollateralStatistics, CustomIndicatorInput, CustomIndicatorPointInput, HttpTransportOptions, JsonObject, JsonValue, ListOrdersOptions, ListPortfoliosOptions, NexusTradeClientOptions, PortfolioEditOperation, UpdatePortfolioOperation, PortfolioRenameOperation, RemoveStrategiesOperation, ReplaceStrategiesOperation, ReplaceStrategyOperation, RequestOptions, Transport, UploadTransport, WaitOptions, WorkspaceSessionTransport, } from "./client.js";
4
+ export type { CongressAction, CongressChamber, CongressCommitteeAssignment, CongressInstrument, CongressMemberBadge, CongressOwner, CongressParseMethod, CongressParty, CongressSort, CongressionalAppliedFilters, CongressionalCoverage, CongressionalEnvelope, CongressionalFiler, CongressionalFilerActivity, CongressionalFilerDetail, CongressionalFilerListOptions, CongressionalFilerVolume, CongressionalFilerYearActivity, CongressionalFiling, CongressionalFilingLatency, CongressionalLeaderboard, CongressionalLeaderboardRow, CongressionalMemberRecordOptions, CongressionalTrade, CongressionalTradeDetail, CongressionalTradeFilters, CongressionalTradePage, CongressionalTradeSummary, CongressionalVolumeRank, ListCongressionalTradesOptions, Politician, PoliticianBot, PoliticianBotCurvePoint, PoliticianBotStatistics, PoliticianProfile, } from "./congress.js";
5
+ export type { AddStrategiesOperation, BacktestCollateralStatistics, CustomIndicatorInput, CustomIndicatorPointInput, HttpTransportOptions, JsonObject, JsonValue, ListOrdersOptions, BacktestHistoryOptions, ListBacktestEventsOptions, ListPortfoliosOptions, NexusTradeClientOptions, PortfolioEditOperation, UpdatePortfolioOperation, PortfolioRenameOperation, PublicApiTransport, RemoveStrategiesOperation, ReplaceStrategiesOperation, ReplaceStrategyOperation, RequestOptions, Transport, UploadTransport, WaitOptions, WorkspaceSessionTransport, } from "./client.js";
5
6
  export { PortfolioHandle, portfolioHandleFromWire, } from "./portfolio.js";
6
7
  export type { DeployOutcome, DeployResult, PortfolioHandleOptions, PortfolioListResult, PortfolioType, ReadonlyPortfolioPolicy, } from "./portfolio.js";
7
8
  export * from "./generated/ntSdk.generated.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexustrade",
3
- "version": "5.2.2",
3
+ "version": "5.4.0",
4
4
  "description": "Typed TypeScript SDK for NexusTrade portfolio authoring, backtesting, optimization, and natural-language stock screening",
5
5
  "license": "MIT",
6
6
  "author": "Starks Technology",