Merge branch 'vest-fix-display' into vest-fixes

# Conflicts:
#	package.json
#	scripts/check-trading-logic.mjs
This commit is contained in:
Brandon Li
2026-10-27 14:51:59 -05:00
11 changed files with 350 additions and 60 deletions
+107
View File
@@ -0,0 +1,107 @@
// Checks for the firm catalog sync in lib/firm-catalog.ts, against a stand-in
// master on a local port and a throwaway database — never the live DB or the
// real master.
//
// npm run check
import { after, test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { registerHooks } from 'node:module';
import { createServer } from 'node:http';
import { once } from 'node:events';
// Resolve the extensionless local imports used by Next, without a build.
function resolveTypes(specifier, context, nextResolve) {
try {
return nextResolve(specifier, context);
} catch (err) {
if (err.code !== 'ERR_MODULE_NOT_FOUND' || !specifier.startsWith('.')) throw err;
return nextResolve(`${specifier}.ts`, context);
}
}
registerHooks({ resolve: resolveTypes });
const directory = mkdtempSync(join(tmpdir(), 'autofirmer-catalog-'));
process.env.AUTOFIRMER_DB = join(directory, 'test.sqlite');
after(() => rmSync(directory, { recursive: true, force: true }));
const { getSetting, setSetting } = await import('../lib/db.ts');
const { syncCatalog, getCachedCatalog, getKeptRuleIdsForFirm, CATALOG_PARSER_VERSION } = await import('../lib/firm-catalog.ts');
const firm = (id, name, platform) => ({
id, name, platform, keptAccountRules: [], updatedAt: '2026-10-26T19:00:00.000Z',
accountTypes: [{
id: `${id}-50k`, firmId: id, label: '50k', prefix: `${id.toUpperCase()}-`, updatedAt: '2026-10-26T19:00:00.000Z',
accountSize: 50000, profitTarget: 3000, consistency: 0, minDayPnL: 0, minTradingDays: 0, maxLoss: 3000,
maxPositionSize: 0, withdrawalStages: [],
}],
});
const apex = firm('apex', 'Apex', 'tradovate');
const vest = firm('vest', 'VestMarkets', 'vest');
// The master's catalog, answering ?since= as app/api/firms/catalog does, and
// the `since` each sync sent (null = a full fetch).
let served = { version: 41, updatedAt: '2026-10-26T19:20:00.000Z', firms: [apex, vest] };
const sinceSent = [];
const server = createServer((req, res) => {
const since = new URL(req.url, 'http://master').searchParams.get('since');
sinceSent.push(since);
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(since !== null && Number(since) === served.version
? { version: served.version, updatedAt: served.updatedAt, unchanged: true }
: served));
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
after(() => server.close());
const master = `http://127.0.0.1:${server.address().port}`;
/** This machine's cache as some build stored it, read afresh as after a restart. */
function storedCache(payload) {
setSetting('master_dashboard_url', master);
setSetting('catalog_source_url', master);
setSetting('catalog_version', String(payload.version));
setSetting('catalog_payload', JSON.stringify(payload));
globalThis.__firmCatalog = undefined;
sinceSent.length = 0;
}
const names = () => getCachedCatalog().map((f) => f.name);
test('a cache a pre-Vest build stored is fetched in full by a build that knows Vest', async (t) => {
t.mock.method(console, 'log', () => {});
// Parser 2 skipped the Vest firm and said nothing of it; the master's
// catalog hasn't changed since, so ?since= would answer "unchanged".
storedCache({ version: 41, updatedAt: served.updatedAt, firms: [apex], parser: 2 });
assert.equal((await syncCatalog()).ok, true);
assert.deepEqual(sinceSent, [null]);
assert.deepEqual(names(), ['Apex', 'VestMarkets']);
// Current from then on: the next sync asks ?since= again.
await syncCatalog();
assert.deepEqual(sinceSent, [null, '41']);
});
test('a skipped platform is named in the cache, and a build that knows it fetches in full', async (t) => {
t.mock.method(console, 'log', () => {});
t.mock.method(console, 'warn', () => {});
// The master adds a firm on a platform this build doesn't know.
served = { version: 42, updatedAt: '2026-10-27T15:00:00.000Z', firms: [apex, vest, firm('px', 'PX Firm', 'projectx')] };
storedCache({ version: 41, updatedAt: '2026-10-26T19:20:00.000Z', firms: [apex, vest], parser: CATALOG_PARSER_VERSION });
await syncCatalog();
assert.deepEqual(names(), ['Apex', 'VestMarkets']);
assert.deepEqual(JSON.parse(getSetting('catalog_payload')).skippedPlatforms, ['projectx']);
// While this build still doesn't know it, syncs stay incremental, and the
// cache still vouches for the kept rule sets of the firms it holds.
globalThis.__firmCatalog = undefined;
sinceSent.length = 0;
await syncCatalog();
assert.deepEqual(sinceSent, ['42']);
assert.deepEqual(getKeptRuleIdsForFirm('apex'), []);
// A build that knows the platform it skipped (Vest here) fetches in full.
storedCache({ version: 42, updatedAt: served.updatedAt, firms: [apex], parser: CATALOG_PARSER_VERSION, skippedPlatforms: ['vest'] });
await syncCatalog();
assert.deepEqual(sinceSent, [null]);
assert.ok(names().includes('VestMarkets'));
});
+91 -1
View File
@@ -11,7 +11,7 @@ import assert from 'node:assert/strict';
import {
percentFee, takeProfitPlan, onTick, obfuscationStopDollars, dllRoom, dllStopDollars, dllViable, stopTicks,
botStopsActive, sizeNotional, isNoTradeTime, isPastSessionClose, nextTradingDate, effectiveCombine, DEFAULT_TARGET_HOLD_HOURS,
projectPerfectPath, cycleCompletion, DLL_RESERVE_FRACTION, DLL_MIN_STOP, notionalCap, expectedSwapToWin, MARGIN_HEADROOM,
projectPerfectPath, cycleCompletion, endedCycleCompletion, DLL_RESERVE_FRACTION, DLL_MIN_STOP, notionalCap, expectedSwapToWin, MARGIN_HEADROOM,
dllReserve, DLL_SLIPPAGE_FRACTION, maxLossRoom, lastStand, breachDistance, LAST_STAND_FRACTION, planLegSize, rankForTarget,
currentTradeDateCT, foldReason, withinFirmCaps, personSizeFactor, personHoldHours, PERSON_SIZE_SPREAD, machineSide,
resolveEffectiveConfig, stageInputsFor, floorRoom, resetClearStop, shortestNextLeg, computeDayPlan, clearsClose, RESET_CLEAR_HOLDS,
@@ -306,6 +306,22 @@ test('dllViable and botStopsActive', () => {
assert.equal(botStopsActive({ firstDayStop: true, minDayStop: false, dailyLossLimit: 0 }), true);
});
test('botStopsActive: the current stage\'s daily loss limit, which a stage may set on a type with none', () => {
const cfg = { firstDayStop: false, minDayStop: false, dailyLossLimit: 0 };
const stages = [{ profit: 3000, consistency: 0, minTradingDays: 0, dailyLossLimit: 3000 }];
const paidOnce = [{ date: '2026-10-25', amount: -1500 }];
// Stage 2 places its $3,000 stop: a red day there is the personal DLL.
const stage2 = resolveEffectiveConfig(1500, 0, 0, false, stages, 0, paidOnce, 0, { dailyLossLimit: 0 });
assert.equal(botStopsActive(cfg, stage2), true);
// Stage 1 of the same type places none.
assert.equal(botStopsActive(cfg, resolveEffectiveConfig(1500, 0, 0, false, stages, 0, [], 0, { dailyLossLimit: 0 })), false);
// A stage that sets 0 lifts the type's limit.
const lifted = resolveEffectiveConfig(1500, 0, 0, false, [{ ...stages[0], dailyLossLimit: 0 }], 0, paidOnce, 0, { dailyLossLimit: 1229 });
assert.equal(botStopsActive({ ...cfg, dailyLossLimit: 1229 }, lifted), false);
// The obfuscation stops count whatever the stage.
assert.equal(botStopsActive({ ...cfg, minDayStop: true }, lifted), true);
});
// ── sizing ───────────────────────────────────────────────────────────────────
const btcSigma = 0.03 / Math.sqrt(24); // 3%/day
@@ -1268,3 +1284,77 @@ test('the engine says what each order is for, and both position-based clients go
assert.match(src, /= orderEffect\(\{[^}]*\bintent\b[^}]*\}\) === 'close' \? held : undefined;/, `${file}: orderEffect doesn't pick the route`);
}
});
// The Vest 50k Funded type: $1,500 and claim it all, then $3,000 on the room
// the claim freed — and every new day back at $1,500.
const vestFunded = {
profitTarget: 1500, consistency: 0, minDayPnL: 0, minTradingDays: 0, accountSize: 50000,
targetSameEquity: false, splitEnabled: true, payoutable: true, tradesEveryDay: true, combineCmeHolidays: false,
withdrawalStages: [{ profit: 3000, consistency: 0, minTradingDays: 0, dailyLossLimit: 3000 }],
};
const claimedBefore = [{ date: '2026-10-20', amount: 50000 }, { date: '2026-10-25', amount: -1500 }];
test('projectPerfectPath: a same-day type trades each projected day from the base stage, then its next stages that day', () => {
const opts = {
accountId: 7, cfg: vestFunded, cycleDailyPnL: [], fundTransactions: claimedBefore,
balance: 50000, realizedPnL: 0, payout: { withdrawalPct: 1 }, now: cdt('2026-10-27T12:00:00'),
};
const firstOf = (path, n) => path.slice(0, n).map((d) => [d.date, d.stage, d.withdrawal]);
// An earlier day's claim doesn't count: today and every day after it
// make $1,500 on stage 1 and claim it, then $3,000 on stage 2 and claim
// that — once through the stages a day.
const fresh = projectPerfectPath({ ...opts, stageInputs: { dailyLossLimit: 1229, stagesSameDay: true, sameDayWithdrawals: 0 } });
assert.deepEqual(firstOf(fresh, 5), [
['2026-10-27', 1, -1500], ['2026-10-27', 2, -3000],
['2026-10-28', 1, -1500], ['2026-10-28', 2, -3000],
['2026-10-29', 1, -1500],
]);
// Claimed once already today: today's cycle is stage 2's $3,000, tomorrow $1,500 and $3,000 again.
const claimedToday = projectPerfectPath({ ...opts, stageInputs: { dailyLossLimit: 1229, stagesSameDay: true, sameDayWithdrawals: 1 } });
assert.deepEqual(firstOf(claimedToday, 3), [['2026-10-27', 2, -3000], ['2026-10-28', 1, -1500], ['2026-10-28', 2, -3000]]);
// A cycle that stood complete yesterday is claimed today, so today trades stage 2.
const unclaimed = projectPerfectPath({
...opts, cycleDailyPnL: [{ date: '2026-10-26', pnl: 1500 }], balance: 51500,
stageInputs: { dailyLossLimit: 1229, stagesSameDay: true, sameDayWithdrawals: 0 },
});
assert.deepEqual(firstOf(unclaimed, 3), [['2026-10-26', 1, -1500], ['2026-10-27', 2, -3000], ['2026-10-28', 1, -1500]]);
// Two listed stages: three payouts a day, and the day after starts over.
const twoStages = projectPerfectPath({
...opts, cfg: { ...vestFunded, withdrawalStages: [...vestFunded.withdrawalStages, { profit: 2000, consistency: 0, minTradingDays: 0 }] },
maxWithdrawals: 10, stageInputs: { stagesSameDay: true, sameDayWithdrawals: 0 },
});
assert.deepEqual(firstOf(twoStages, 4).map(([date, stage]) => [date, stage]), [
['2026-10-27', 1], ['2026-10-27', 2], ['2026-10-27', 3], ['2026-10-28', 1],
]);
// Any other type counts every withdrawal, as it always has.
const lifetime = projectPerfectPath(opts);
assert.deepEqual(firstOf(lifetime, 3), [['2026-10-27', 2, -3000], ['2026-10-28', 3, -3000], ['2026-10-29', 4, -3000]]);
assert.deepEqual(projectPerfectPath({ ...opts, stageInputs: { dailyLossLimit: 1229, stagesSameDay: false, sameDayWithdrawals: 0 } }), lifetime);
});
test('endedCycleCompletion: a same-day type\'s ended cycle is judged on its day\'s base stage', () => {
// 2026-10-26 made $1,500 and the auto-claim took it before the reporter
// saw the final day; the account had claimed the day before too. The
// claim ended that day's stage 1, not a $3,000 stage 2.
const opts = {
accountId: 7, rawTradeDate: '2026-10-26',
fullDailyPnL: [{ date: '2026-10-25', pnl: 1500 }, { date: '2026-10-26', pnl: 1500 }],
cycleDailyPnL: [],
fundTransactions: [...claimedBefore, { date: '2026-10-26', amount: -1500 }],
lastFundDate: '2026-10-26',
endedCycleStart: { fundDate: '2026-10-25', includesDay: false },
rawRealizedPnL: 0, equityProfit: 0,
cfg: { ...vestFunded, stagesSameDay: true },
now: cdt('2026-10-26T12:00:00'),
};
// Its stage stays the payout's number among the account's withdrawals,
// which the master clears the entry by.
assert.deepEqual(endedCycleCompletion(opts), { date: '2026-10-26', stage: 2, drain: false, cycle: '2026-10-25' });
// Any other type: judged on stage 2's $3,000, as before.
assert.equal(endedCycleCompletion({ ...opts, cfg: vestFunded }), null);
});