Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 68 additions & 17 deletions cli/src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2883,7 +2883,7 @@ export async function brokerageGetAllResults(
}
if (!cursor) return all; // unparseable/missing cursor — stop rather than loop forever
}
return all; // hit maxPages guard; return what we have (caller decides if that's suspicious)
throw new Error(`pagination limit (${maxPages} pages) reached for ${url}; refusing to return a truncated result`);
}

/** Non-throwing brokerageGetJson — returns {ok:false,error} instead of throwing. */
Expand Down Expand Up @@ -10424,9 +10424,30 @@ export interface UnifiedHistoryEvent {
/** Unified transaction history: equity + options + crypto orders + ACH transfers, newest first. */
export async function getUnifiedHistory(
opts: { days?: number; accountNumber?: string },
deps: { getJson?: typeof brokerageGetJson; now?: () => number } = {},
deps: {
getJson?: typeof brokerageGetJson;
getAll?: typeof brokerageGetAllResults;
now?: () => number;
} = {},
): Promise<UnifiedHistoryEvent[]> {
const getJson = deps.getJson ?? brokerageGetJson;
const getAll = deps.getAll
? deps.getAll
: deps.getJson
? async (url: string, params: Record<string, string> = {}, query: Record<string, string> = {}) => {
const all: any[] = [];
let cursor: string | undefined;
for (let page = 0; page < 50; page++) {
const data = await getJson(url, params, cursor ? { ...query, cursor } : query);
if (Array.isArray(data?.results)) all.push(...data.results);
const next = String(data?.next ?? "");
if (!next) return all;
cursor = new URL(next).searchParams.get("cursor") ?? undefined;
if (!cursor) return all;
}
throw new Error(`pagination limit (50 pages) reached for ${url}; refusing to return a truncated result`);
}
: brokerageGetAllResults;
const now = deps.now ?? Date.now;
const days = Math.max(1, opts.days ?? 3);
const cutoffMs = now() - days * 86400000;
Expand All @@ -10447,6 +10468,18 @@ export async function getUnifiedHistory(
return { ok: false as const, error };
}
};
const safeGetAll = async (
url: string,
params: Record<string, string> = {},
query: Record<string, string> = {},
) => {
try {
return { ok: true as const, data: await getAll(url, params, query) };
} catch (error) {
if (error instanceof Error && error.message.includes("pagination limit")) throw error;
return { ok: false as const, error };
}
};

// The web History screen uses Wormhole. This surface carries symbol, account-scoped recent
// orders, realized P&L, and—critically—`placedBy: PLACED_BY_RISK` for broker liquidations.
Expand Down Expand Up @@ -10500,28 +10533,46 @@ export async function getUnifiedHistory(
}

// Legacy equity orders supplement Wormhole for longer windows.
const eq = await safeGet(
`https://api.robinhood.com/orders/${opts.accountNumber ? `?account_number=${encodeURIComponent(opts.accountNumber)}` : ""}`,
);
if (eq.ok)
for (const r of (eq.data as any)?.results ?? []) {
if (r.id && seenOrderIds.has(String(r.id))) continue;
for (const { acct } of owned) {
const eq = await safeGetAll(
"https://api.robinhood.com/orders/",
{},
{ account_number: acct },
);
if (!eq.ok) continue;
for (const r of eq.data) {
const id = String(r.id ?? "");
if (id && seenOrderIds.has(id)) continue;
const t = r.updated_at ?? r.created_at;
if (inWindow(t))
if (inWindow(t)) {
if (id) seenOrderIds.add(id);
const side = String(r.side ?? "?").toLowerCase();
const quantity = finiteNumber(r.quantity);
const averagePrice = finiteNumber(r.average_price ?? r.price);
events.push({
time: String(t),
kind: "equity",
summary: `${r.side ?? "?"} ${r.quantity ?? "?"} @ ${r.average_price ?? r.price ?? "?"}`,
state: String(r.state ?? "?"),
state: String(r.state ?? "?").toLowerCase(),
orderId: id || undefined,
accountLast4: acct.slice(-4),
accountLabel: owned.find((account) => account.acct === acct)?.label || undefined,
side,
quantity: Number.isFinite(quantity) ? quantity : undefined,
averagePrice: Number.isFinite(averagePrice) ? averagePrice : undefined,
});
}
}
}

// Options orders
const op = await safeGet(
`https://api.robinhood.com/options/orders/${opts.accountNumber ? `?account_numbers=${encodeURIComponent(opts.accountNumber)}` : ""}`,
const op = await safeGetAll(
"https://api.robinhood.com/options/orders/",
{},
opts.accountNumber ? { account_numbers: opts.accountNumber } : {},
);
if (op.ok)
for (const r of (op.data as any)?.results ?? []) {
for (const r of op.data) {
if (r.id && seenOrderIds.has(String(r.id))) continue;
const t = r.updated_at ?? r.created_at;
if (inWindow(t))
Expand All @@ -10535,9 +10586,9 @@ export async function getUnifiedHistory(
}

// Crypto orders
const cx = await safeGet("https://nummus.robinhood.com/orders/");
const cx = await safeGetAll("https://nummus.robinhood.com/orders/");
if (cx.ok)
for (const r of (cx.data as any)?.results ?? []) {
for (const r of cx.data) {
const t = r.updated_at ?? r.created_at;
if (inWindow(t))
events.push({
Expand All @@ -10549,9 +10600,9 @@ export async function getUnifiedHistory(
}

// ACH transfers
const ach = await safeGet("https://api.robinhood.com/ach/transfers/");
const ach = await safeGetAll("https://api.robinhood.com/ach/transfers/");
if (ach.ok)
for (const r of (ach.data as any)?.results ?? []) {
for (const r of ach.data) {
const t = r.updated_at ?? r.created_at;
if (inWindow(t))
events.push({
Expand Down
91 changes: 91 additions & 0 deletions cli/test/margin-call-intelligence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,97 @@ describe("margin-call intelligence", () => {
]);
});

it("includes an in-window legacy equity order from a later cursor page", async () => {
const olderSale = {
id: "older-sale",
side: "sell",
quantity: "1.25",
average_price: "28.00",
state: "filled",
updated_at: "2026-09-03T15:58:44.978Z",
};
const getJson = async (url: string, _params?: Record<string, string>, query?: Record<string, string>) => {
if (url.includes("transfer/accounts")) return accounts;
if (url.includes("wormhole/bw/orders/recent")) return { results: [] };
if (url === "https://api.robinhood.com/orders/") {
return query?.cursor === "page-2"
? { results: [olderSale], next: null }
: { results: [], next: "https://api.robinhood.com/orders/?cursor=page-2" };
}
if (url.includes("options/orders")) return { results: [] };
if (url.includes("nummus.robinhood.com")) return { results: [] };
if (url.includes("ach/transfers")) return { results: [] };
throw new Error(`unexpected ${url}`);
};

const events = await getUnifiedHistory(
{ accountNumber: "873870497", days: 7 },
{ getJson: getJson as never, now: () => Date.parse("2026-09-04T21:00:00Z") },
);

expect(events).toContainEqual(
expect.objectContaining({
kind: "equity",
orderId: "older-sale",
side: "sell",
quantity: 1.25,
averagePrice: 28,
accountLast4: "0497",
state: "filled",
summary: "sell 1.25 @ 28.00",
}),
);
});

it("reads legacy equity pages separately for every owned account", async () => {
const getJson = async (url: string, _params?: Record<string, string>, query?: Record<string, string>) => {
if (url.includes("transfer/accounts"))
return {
results: [
...accounts.results,
{ type: "ira_roth", account_number: "710276346", account_name: "Roth IRA", state: "active" },
],
};
if (url.includes("wormhole/bw/orders/recent")) return { results: [] };
if (url === "https://api.robinhood.com/orders/") {
const updated_at = "2026-09-03T15:58:44.978Z";
if (query?.account_number === "873870497")
return { results: [{ id: "far-sale", side: "sell", quantity: "1", average_price: "10", state: "filled", updated_at }] };
if (query?.account_number === "710276346")
return { results: [{ id: "roth-sale", side: "sell", quantity: "2", average_price: "20", state: "filled", updated_at }] };
return { results: [] };
}
if (url.includes("options/orders")) return { results: [] };
if (url.includes("nummus.robinhood.com")) return { results: [] };
if (url.includes("ach/transfers")) return { results: [] };
throw new Error(`unexpected ${url}`);
};

const events = await getUnifiedHistory(
{ days: 7 },
{ getJson: getJson as never, now: () => Date.parse("2026-09-04T21:00:00Z") },
);

expect(events.filter((event) => event.kind === "equity" && event.state === "filled")).toHaveLength(2);
});

it("does not silently return a truncated legacy order history at the pagination guard", async () => {
const getJson = async (url: string) => {
if (url.includes("transfer/accounts")) return accounts;
if (url.includes("wormhole/bw/orders/recent")) return { results: [] };
if (url === "https://api.robinhood.com/orders/")
return { results: [], next: "https://api.robinhood.com/orders/?cursor=still-more" };
if (url.includes("options/orders")) return { results: [] };
if (url.includes("nummus.robinhood.com")) return { results: [] };
if (url.includes("ach/transfers")) return { results: [] };
throw new Error(`unexpected ${url}`);
};

await expect(
getUnifiedHistory({ accountNumber: "873870497", days: 7 }, { getJson: getJson as never }),
).rejects.toThrow("pagination limit");
});

it("reports the true maintenance buffer and recent risk-sale totals", async () => {
const getJson = async (url: string) => {
if (url.includes("transfer/accounts")) return accounts;
Expand Down
Loading