Vest: a claim that never reached Vest stops holding the account, and each claim counts once

A claim of unknown outcome now lapses where history is read (bookHistory),
not only in claimPending: its callers wait on historyReady, and the books
check held the account while it counted that claim, so one that never went
in held the account for good. The lapse is the same (no WITHDRAW within 30
min of it, a read an hour on) and is saved; an accepted claim still holds.

An account token that can't be minted means the request never went out:
an order, stop or take-profit reads as not placed, and a claim records no
unknown claim. Only the request's own failure may be "unknown".

A claim Vest dates on the other side of 20:00 ET than it was booked here
no longer leaves a second fund row: the history read takes the local day
back (and the latest fund date with it), and sameDayClaims counts the
claim on Vest's day. A claim Vest doesn't show yet stays on its day.

The report counts payouts one per claim (Vest's WITHDRAWs and the claims
they don't show yet, never fewer than the negative fund rows) for the
account list, payout states and the completion stage, where two claims on
one Vest day were one row. Same-day cycles still share a cycle key; that
needs the master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Li
2026-10-27 14:14:38 -05:00
co-authored by Claude Opus 5.5
parent beddbdcf6c
commit 9fe7fc0ea3
7 changed files with 334 additions and 72 deletions
+79 -63
View File
@@ -42,7 +42,7 @@ import { currentTradeDateCT, rankForTarget, dllReserve, resetClearStop } from '.
import { sizingHoldHours } from './person-size';
import {
saveDailyPnL, loadDailyPnL, loadAccountMeta, saveAccountMeta, loadFundTransactions, saveFundTransactions,
saveEndedCycleStart, saveTrades, markTrade, getOrCreateSetting, TRADES_SINCE_SETTING, openTradeAccounts,
saveEndedCycleStart, dropFundTransaction, saveTrades, markTrade, getOrCreateSetting, TRADES_SINCE_SETTING, openTradeAccounts,
} from './db';
import { getCachedFirm } from './firm-catalog';
import { firmInstruments } from './instruments';
@@ -54,8 +54,9 @@ import {
vestAccountId, vestAccountName, vestDayOf, lastVestResetMs, nextVestResetMs, parseCapitalAccount, parsePosition, parseOpenOrder,
parseTxn, bookTxns, awaitingLegs, unrealizedPnl, hourlyVolatility, marketOpen, num, toMs, formatDecimal, resetSafeStop,
parseHistoryPosition, jwtClaimStrings, accountScopedToken, VEST_STATUS_ACTIVE, VEST_TXN, VEST_STOP_SLIPPAGE_FRACTION,
VestApiError, VestNotSentError, nothingWentIn, tokenForRequest, settleClaims, claimFundRows, payoutCount, payoutsSince,
} from './vest-helpers';
import type { VestCapitalAccount, VestPosition, VestOpenOrder, VestTxn, VestTrade } from './vest-helpers';
import type { VestCapitalAccount, VestPosition, VestOpenOrder, VestTxn, VestTrade, OwnClaim } from './vest-helpers';
const BASE = 'https://api-gateway.hz.vestmarkets.com';
/** The web app's origin: the gateway serves it, so requests say they are its. */
@@ -113,29 +114,10 @@ const RESET_ENTRY_BLOCK_MS = RESET_GUARD_MS + 2 * 60_000;
const GUARD_ECHO_MS = 30_000;
/** account_meta key of the profit claims this client made, per account. */
const CLAIMS_META = 'vest_claims';
/** A claim shows in Vest's transactions as a WITHDRAW of the same amount
* within this long of it. */
const CLAIM_MATCH_MS = 30 * 60_000;
/** A claim of unknown outcome (the request failed in transit) that no
* WITHDRAW matches in a history read this long after it never happened. */
const UNKNOWN_CLAIM_EXPIRES_MS = 60 * 60_000;
/** A claim this client sent: the amount, when, and the balance it left.
* unknown = the request failed in transit, so it may or may not have gone
* in — it holds further claims, but nothing is booked on it. */
interface OwnClaim { at: number; amount: number; base: number; unknown?: true }
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const round2 = (n: number) => Math.round(n * 100) / 100;
/** The gateway answered with an error status. */
class VestApiError extends Error {
constructor(message: string, readonly status: number, readonly code: string | undefined) {
super(message);
this.name = 'VestApiError';
}
}
interface SymbolSpec {
symbol: string;
assetId: number;
@@ -350,8 +332,10 @@ export class VestClient implements PlatformClient {
* none (`auth: false`, public data). Non-2xx answers become VestApiError
* with the gateway's own code; transport failures a plain Error carrying
* only the message — never the axios error, whose config holds the token.
* A refused account token is re-minted once; a refused user token is
* dropped, so nothing keeps knocking with it until a fresh one arrives.
* An account token that can't be minted is VestNotSentError: the call
* itself never went out. A refused account token is re-minted once; a
* refused user token is dropped, so nothing keeps knocking with it until
* a fresh one arrives.
*/
private async request<T>(
bucket: Bucket,
@@ -361,7 +345,8 @@ export class VestClient implements PlatformClient {
): Promise<{ data: T }> {
let token: string | null = null;
if (opts.auth !== false) {
token = opts.account ? await this.accountToken(opts.account) : this.userToken();
const account = opts.account;
token = account ? await tokenForRequest(path, () => this.accountToken(account)) : this.userToken();
if (!token) throw new VestApiError(`${path}: no Vest session`, 401, 'NO_SESSION');
}
await this.gate(bucket);
@@ -784,10 +769,18 @@ export class VestClient implements PlatformClient {
saveAccountMeta(accountId, CLAIMS_META, JSON.stringify(kept));
}
/** Vest's transactions show the claim: a WITHDRAW of its amount near it. */
private claimShown(accountId: number, c: OwnClaim): boolean {
return (this.withdrawals.get(accountId) ?? [])
.some((w) => Math.abs(Math.abs(w.amount) - c.amount) < 0.01 && Math.abs(w.at - c.at) < CLAIM_MATCH_MS);
/** The claims Vest's transactions, as last read (at `readAt`), don't
* show yet. One of unknown outcome still not shown an hour on never went
* in: it's dropped here (settleClaims). */
private outstandingClaims(accountId: number, readAt: number): OwnClaim[] {
const list = this.claimsOf(accountId);
const { pending, lapsed } = settleClaims(list, this.withdrawals.get(accountId) ?? [], readAt);
if (lapsed.length > 0) {
const name = this.accountList.find((a) => a.id === accountId)?.name ?? accountId;
this.saveClaims(accountId, list.filter((c) => !lapsed.includes(c)));
for (const c of lapsed) console.warn(`${this.tag} ${name}: the claim of $${c.amount} with an unknown outcome never showed on Vest — taken as not made`);
}
return pending;
}
/**
@@ -808,13 +801,22 @@ export class VestClient implements PlatformClient {
}
/** See PlatformClient: the payouts since the last 20:00 ET — this client's
* own claims, or the WITHDRAW transactions Vest shows, whichever counts
* more (a claim made by hand shows only there). */
* own claims, on Vest's day once its transactions show them, or the
* WITHDRAW transactions Vest shows, whichever counts more (a claim made
* by hand shows only there). */
public sameDayClaims(accountId: number): number {
const reset = lastVestResetMs(Date.now());
const mine = this.madeClaims(accountId).filter((c) => c.at >= reset).length;
const seen = (this.withdrawals.get(accountId) ?? []).filter((w) => w.at >= reset).length;
return Math.max(mine, seen);
return payoutsSince(this.withdrawals.get(accountId) ?? [], this.claimsOf(accountId), lastVestResetMs(Date.now()));
}
/** See PlatformClient: one per payout — Vest's WITHDRAW transactions, and
* this client's claims they don't show yet (payoutCount) — where a fund
* row holds a whole Vest day's. Undefined until the account's history
* is read. */
public withdrawalCount(accountId: number): number | undefined {
const withdrawals = this.withdrawals.get(accountId);
const fundRows = this.fundTransactions[accountId];
if (!withdrawals || !fundRows || !this.historyLoadedIds.has(accountId)) return undefined;
return payoutCount(withdrawals, this.claimsOf(accountId), fundRows);
}
/**
@@ -826,7 +828,8 @@ export class VestClient implements PlatformClient {
* The payout is booked here at once — today's fund row, the cycle cut,
* the P&L base — so the account can trade its next stage without waiting
* for the hourly history read, which then rebooks it from Vest's own
* transactions (the same day's row, the same amount).
* transactions (the same day's row, the same amount — or the day Vest
* dates it, when a claim at 20:00 ET lands on the other side).
*/
public async claimProfit(accountId: number, amount: number): Promise<{ claimed: number; received: number | null }> {
const uuid = this.uuidById.get(accountId);
@@ -860,10 +863,11 @@ export class VestClient implements PlatformClient {
},
}));
} catch (err) {
// Only a refusal proves nothing went in. A timeout, a reset or a
// 5xx may have: hold every further claim on the account until
// Vest's transactions say either way (claimPending).
if (!(err instanceof VestApiError && err.status >= 400 && err.status < 500 && err.status !== 408)) {
// Only a refusal, or no account token to send it with, proves
// nothing went in. A timeout, a reset or a 5xx may have: hold
// every further claim on the account until Vest's transactions
// say either way (claimPending).
if (!nothingWentIn(err)) {
this.saveClaims(accountId, [...this.claimsOf(accountId), { at: Date.now(), amount: claimed, base: round2(cash.amount - claimed), unknown: true }]);
this.claimSeq.set(accountId, this.syncGeneration);
console.error(`${this.tag} ${account.name}: claim of $${claimed} — outcome unknown (${errorMessage(err)}); no further claim on it until Vest's transactions settle it`);
@@ -900,15 +904,8 @@ export class VestClient implements PlatformClient {
*/
public claimPending(accountId: number): boolean {
const now = Date.now();
const readAt = this.historyReadAt.get(accountId) ?? 0;
const list = this.claimsOf(accountId);
const lapsed = list.filter((c) => c.unknown && !this.claimShown(accountId, c) && readAt - c.at > UNKNOWN_CLAIM_EXPIRES_MS);
const pending = this.outstandingClaims(accountId, this.historyReadAt.get(accountId) ?? 0);
const name = this.accountList.find((a) => a.id === accountId)?.name ?? accountId;
if (lapsed.length > 0) {
this.saveClaims(accountId, list.filter((c) => !lapsed.includes(c)));
for (const c of lapsed) console.warn(`${this.tag} ${name}: the claim of $${c.amount} with an unknown outcome never showed on Vest — taken as not made`);
}
const pending = this.claimsOf(accountId).filter((c) => !this.claimShown(accountId, c));
for (const c of pending) {
const key = `${accountId}:${c.at}`;
if (!c.unknown && now - c.at > 60 * 60_000 && !this.unmatchedClaimLogged.has(key)) {
@@ -1331,13 +1328,23 @@ export class VestClient implements PlatformClient {
.sort((x, y) => x.date.localeCompare(y.date));
saveDailyPnL(account.id, account.name, fresh);
const fundRows = [...funds.entries()]
.map(([date, amount]) => ({ date, amount: round2(amount) }))
.filter((f) => f.amount !== 0)
.sort((x, y) => x.date.localeCompare(y.date));
const withdrawals = txns.filter((t) => t.type === VEST_TXN.WITHDRAW).map((t) => ({ at: t.time, amount: t.amount }));
this.withdrawals.set(account.id, withdrawals);
const readAt = Date.now();
this.historyReadAt.set(account.id, readAt);
// Settled here, not only in claimPending: its callers wait on
// historyReady, which a claim that never went in would hold below
// for good.
const outstanding = this.outstandingClaims(account.id, readAt);
// A claim Vest dates on the other side of 20:00 ET than it was booked
// here leaves that day's row to this client alone: taken back, so the
// payout counts once, on Vest's day.
const { rows: fundRows, dropped } = claimFundRows({
funds, claims: this.claimsOf(account.id), withdrawals, stored: loadFundTransactions(account.id),
});
if (dropped.length > 0) this.dropClaimDays(account, dropped);
this.applyFundRows(account, fundRows);
this.withdrawals.set(account.id, txns.filter((t) => t.type === VEST_TXN.WITHDRAW).map((t) => ({ at: t.time, amount: t.amount })));
this.historyReadAt.set(account.id, Date.now());
// Books check: the balance must be what the transactions add up to
// (the opening capital included). A payout or credit booked under a
@@ -1346,10 +1353,7 @@ export class VestClient implements PlatformClient {
const cash = this.accountCashBalances[account.id];
// A claim this client just made may not show in Vest's transactions
// yet: count it until its WITHDRAW row does (same amount, near time).
const shown = txns.filter((t) => t.type === VEST_TXN.WITHDRAW);
const unbooked = this.claimsOf(account.id)
.filter((c) => !shown.some((w) => Math.abs(Math.abs(w.amount) - c.amount) < 0.01 && Math.abs(w.time - c.at) < 30 * 60_000))
.reduce((s, c) => s + c.amount, 0);
const unbooked = outstanding.reduce((s, c) => s + c.amount, 0);
const expected = txns.reduce((s, t) => s + (t.kind === 'margin' ? 0 : t.amount), 0) + (hasDeposit ? 0 : a?.initialCapital ?? 0) - unbooked;
if (account.active && cash && !this.positions[account.id] && Math.abs(cash.amount - expected) >= BOOKS_TOLERANCE) {
this.booksHeld.add(account.id);
@@ -1379,6 +1383,18 @@ export class VestClient implements PlatformClient {
this.applyCycleSlice(account.id);
}
/** Take back fund rows only a claim of this client's put there (see
* claimFundRows), and the latest fund date with them when it was one —
* back to the latest row left. The ended-cycle start that date saved
* stays: the next fund day saves the same one. */
private dropClaimDays(account: PlatformAccount, days: string[]): void {
const stored = loadAccountMeta(account.id, 'last_fund_date');
const left = loadFundTransactions(account.id).map((f) => f.date).filter((d) => !days.includes(d));
const last = stored !== null && !days.includes(stored) ? stored : left.reduce<string | null>((x, y) => (x === null || y > x ? y : x), null);
for (const day of days) dropFundTransaction(account.id, day, { last_fund_date: last });
console.warn(`${this.tag} ${account.name}: the claim booked on ${days.join(', ')} shows on another Vest day — that row taken back`);
}
private fallBackToCache(account: PlatformAccount, msg: string): void {
const cached = loadDailyPnL(account.id);
this.fundTransactions[account.id] ??= loadFundTransactions(account.id);
@@ -1739,9 +1755,10 @@ export class VestClient implements PlatformClient {
}
/**
* POST an order. Only an answer that proves nothing was placed becomes
* OrderNotPlacedError (a 4xx with the gateway's refusal); a transport
* failure or a 5xx stays a plain Error — it may have gone in.
* POST an order. Only a failure that proves nothing was placed becomes
* OrderNotPlacedError (a 4xx with the gateway's refusal, or no account
* token to send it with); a transport failure or a 5xx stays a plain
* Error — it may have gone in.
*/
private async submit(uuid: string, path: string, body: Record<string, unknown>): Promise<{ orderId?: string; positionId?: string }> {
try {
@@ -1751,9 +1768,8 @@ export class VestClient implements PlatformClient {
positionId: typeof data?.positionId === 'string' ? data.positionId : undefined,
};
} catch (err) {
if (err instanceof VestApiError && err.status >= 400 && err.status < 500 && err.status !== 408) {
throw new OrderNotPlacedError(`Vest refused the order: ${err.message}`);
}
if (err instanceof VestNotSentError) throw new OrderNotPlacedError(`Vest order not sent: ${err.message}`);
if (nothingWentIn(err)) throw new OrderNotPlacedError(`Vest refused the order: ${errorMessage(err)}`);
throw new Error(`Vest order outcome unknown (it may still have been placed): ${errorMessage(err)}`);
}
}