Legs: cheapest symbol that reaches the target hold, last stands, a reserve that grows with size

- A batch sizes its leg on every mapped candidate, each at the leverage
  the broker states for it, and trades the cheapest (spread, commissions,
  expected swap) that reaches the target hold — else the quickest. The
  dashboard ranks the same way from a half-hourly candidate survey.
- Last stand: when a daily-loss stop-out would leave the account within
  15% of that loss above its max-drawdown floor (the account type's static
  max loss, or the broker's liquidation floor), the leg carries no
  daily-loss stop and is sized against the firm's own breach.
- The daily-loss reserve is 10% of the limit or 0.1% of the position,
  whichever is more, since a stop's slippage grows with the position.
- The account type's max notional is gone: the broker's margin rates cap
  each symbol. planLegSize holds the one sizing rule fireLeg, the pick and
  the dashboard share.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Li
2026-09-26 18:26:12 -05:00
co-authored by Claude Opus 5.5
parent a2d9df5ba4
commit a2cd3a94c9
12 changed files with 477 additions and 172 deletions
+124 -76
View File
@@ -13,8 +13,8 @@ import { getCachedFirm, getTradableFirms } from './firm-catalog';
import { getAccountConfig } from './account-type-resolver';
import {
combineCmeSessions, computeDayPlan, groupLegFraction, pickLegAmount, resolveEffectiveConfig, currentTradeDateCT,
obfuscationStopDollars, takeProfitPlan, percentFee, dllRoom, dllStopDollars, dllViable, stopTicks, sizeNotional,
notionalCap, expectedSwapToWin,
obfuscationStopDollars, takeProfitPlan, percentFee, dllRoom, dllStopDollars, dllViable, stopTicks,
expectedSwapToWin, planLegSize, maxLossRoom, breachDistance,
DEFAULT_TARGET_HOLD_HOURS,
isNoTradeTime, isPastSessionClose,
BIG_DAY_THRESHOLD, LEG_COMPLETION_EPSILON, MAX_LEGS_PER_DAY, POINT_VALUES,
@@ -22,7 +22,7 @@ import {
type DayPlan,
} from './trading-logic';
import { getSetting, setSetting } from './db';
import { errorMessage, isClientReady, isOrderNotPlaced, type PlatformClient, type PlatformContract } from './platform-client';
import { errorMessage, isClientReady, isOrderNotPlaced, type PlatformClient, type PlatformContract, type PickContext } from './platform-client';
// ── process-wide state ───────────────────────────────────────────────────────
@@ -757,6 +757,9 @@ interface LegItem {
dllRoom: number;
}
/** What sizing a leg needs before its instrument is known. */
type SizingItem = Omit<LegItem, 'contract' | 'pv'>;
async function runTradeLocked(
action: 'Buy' | 'Sell' | 'Auto',
symbol: string,
@@ -816,27 +819,31 @@ async function runTradeLocked(
// snapshot) skips that firm, never the batch — a rejection here would
// fail the Promise.all and every other firm would sit the tick out.
try {
const contract = await client.findFrontMonthContract(resolvedSymbol);
if (!contract) return;
const pv = contract.pointValue ?? basePointValue;
if (!pv) {
console.log(`[auto-trade] ${firm.name}: no point value for ${resolvedSymbol} — skipping firm`);
return;
}
const found: EligibleItem[] = [];
// The accounts first: a platform that chooses between
// instruments ranks them by how the batch's leg would size.
const evaluated: (SizingItem & { daysTraded: number; isExtraDay: boolean })[] = [];
for (const acc of client.accountList) {
const ev = evaluateAccountForTrade(client, acc, tradeDate);
if (!ev || !ev.eligible || !ev.plan) continue;
found.push({
firmName: firm.name, firm, client, acc, contract, pv,
evaluated.push({
firmName: firm.name, firm, client, acc,
cash: ev.cash, dailyPnL: ev.dailyPnL, daysTraded: ev.daysTraded,
plan: ev.plan, isExtraDay: ev.isExtraDay, drain: ev.drain,
prefix: getAccountConfig(acc.id).accountType?.prefix ?? '',
dllRoom: ev.dllRoom,
});
}
if (evaluated.length === 0) return;
const contract = await client.findFrontMonthContract(
resolvedSymbol, pickContextFor(evaluated.filter((it) => !it.isExtraDay && !it.drain), tradeDate));
if (!contract) return;
const pv = contract.pointValue ?? basePointValue;
if (!pv) {
console.log(`[auto-trade] ${firm.name}: no point value for ${resolvedSymbol} — skipping firm`);
return;
}
const found: EligibleItem[] = evaluated.map((it) => ({ ...it, contract, pv }));
allEligible.push(...found);
} catch (err) {
console.error(`[auto-trade] ${firm.name}: skipped — ${errorMessage(err)}`);
@@ -962,6 +969,73 @@ async function flattenAndFail(
throw new Error(`entry filled @ ${entryPrice}; flattened — ${why}`);
}
/**
* The leg an account trades next. Split-allowed big days carve a ≥$500
* piece; everything else trades the full remaining amount in one go. The
* carve fraction is seeded per (prefix, date, leg number) so like accounts in
* a batch split their targets the same way, or close to it when remainders
* differ. An account type's min-legs setting forces at least that many
* carves on BIG days only — a day at or below the threshold still trades as
* one leg. Set per prefix, so like accounts still split alike.
*/
function legAmountFor(item: SizingItem, tradeDate: string): number {
const cfg = getAccountConfig(item.acc.id).accountType!;
const minLegs = item.plan.dayTarget > BIG_DAY_THRESHOLD ? (cfg.minLegs ?? 0) : 0;
return item.plan.splitAllowed
? pickLegAmount(
item.plan.remainingToday,
() => groupLegFraction(item.prefix, tradeDate, legsToday(item.acc.id, tradeDate)),
minLegs - legsToday(item.acc.id, tradeDate),
)
: item.plan.remainingToday;
}
/** How this account's leg would size on `contract` (see planLegSize), with
* the account's live funds, its max-drawdown floor and its stops. */
function sizeLeg(item: SizingItem, contract: LegContract, legAmount: number, tradeDate: string) {
const cfg = getAccountConfig(item.acc.id).accountType!;
const live = item.client.accountCashBalances[item.acc.id] ?? item.cash;
const pct = contract.commissionPct ?? item.firm.commissionPct ?? 0;
const floorRoom = maxLossRoom({
balance: live.amount, accountSize: cfg.accountSize, maxLoss: cfg.maxLoss ?? 0,
autoLiqThreshold: item.client.autoLiqThresholds?.[item.acc.id],
});
const obfuscation = obfuscationStopDollars(cfg, item.dailyPnL, item.plan, tradeDate, legAmount);
const plan = planLegSize({
leg: legAmount,
contract,
commissionPct: pct,
targetHoldHours: item.firm.targetHoldHours || DEFAULT_TARGET_HOLD_HOURS,
financingPctPerDay: item.firm.financingPctPerDay ?? 0,
dailyLossLimit: cfg.dailyLossLimit ?? 0,
dllRoom: item.dllRoom,
maxLossRoom: floorRoom,
obfuscationDollars: obfuscation,
availableFunds: live.availableFunds ?? live.amount,
});
return { ...plan, pct, obfuscation, maxLossRoom: floorRoom };
}
/**
* The batch's leg, for a platform that chooses between instruments: the
* first account of the firm's largest prefix group — the group the batch
* will fire — sized on each candidate.
*/
function pickContextFor(items: SizingItem[], tradeDate: string): PickContext | undefined {
const groups = new Map<string, SizingItem[]>();
for (const it of items) groups.set(it.prefix, [...(groups.get(it.prefix) ?? []), it]);
const lead = [...groups.values()].sort((a, b) => b.length - a.length)[0]?.[0];
if (!lead) return undefined;
const legAmount = legAmountFor(lead, tradeDate);
return {
targetHoldHours: lead.firm.targetHoldHours || DEFAULT_TARGET_HOLD_HOURS,
evaluate: (contract) => {
const { sizing, cost } = sizeLeg(lead, contract, legAmount, tradeDate);
return sizing && cost !== null ? { notional: sizing.notional, holdHours: sizing.predictedHoldHours, cost } : null;
},
};
}
/**
* Trade one leg toward the account's remaining target for today — shared by
* the batch and copy-trade, so every fee, stop and sizing rule lives once.
@@ -988,24 +1062,10 @@ async function fireLeg(
symbolLabel: string,
tradeDate: string,
): Promise<LegResult> {
const { client, acc, firm } = item;
const { client, acc } = item;
const cfg = getAccountConfig(acc.id).accountType!;
// Trade one leg toward today's remaining target. Split-allowed big days carve a
// ≥$500 piece; everything else trades the full remaining amount in one go. The
// carve fraction is seeded per (prefix, date, leg number) so like accounts in a
// batch split their targets the same way, or close to it when remainders differ.
// An account type's min-legs setting forces at least that many carves
// on BIG days only — a day at or below the threshold still trades as
// one leg. Set per prefix, so like accounts still split alike.
const minLegs = item.plan.dayTarget > BIG_DAY_THRESHOLD ? (cfg.minLegs ?? 0) : 0;
const legAmount = item.plan.splitAllowed
? pickLegAmount(
item.plan.remainingToday,
() => groupLegFraction(item.prefix, tradeDate, legsToday(acc.id, tradeDate)),
minLegs - legsToday(acc.id, tradeDate),
)
: item.plan.remainingToday;
const legAmount = legAmountFor(item, tradeDate);
// Counted before anything is sent so the runaway guard sees it while
// the batch is in flight; taken back only if the entry never reached
// the broker (here, or in sendEntry).
@@ -1013,7 +1073,6 @@ async function fireLeg(
const dll = cfg.dailyLossLimit ?? 0;
const dllOn = Number.isFinite(item.dllRoom) && dll > 0;
const obfuscation = obfuscationStopDollars(cfg, item.dailyPnL, item.plan, tradeDate, legAmount);
// Everything before the entry goes out: a failure here never reached the
// broker, so the leg is taken back.
@@ -1021,48 +1080,26 @@ async function fireLeg(
let pv: number;
let pct: number;
let contracts: number;
let sizing: ReturnType<typeof sizeNotional> = null;
let plan: ReturnType<typeof sizeLeg>;
try {
const inst = await legInstrument(client, item.drain, item.contract, item.pv);
legContract = inst.contract;
pv = inst.pointValue;
pct = legContract.commissionPct ?? firm.commissionPct ?? 0;
plan = sizeLeg(item, legContract, legAmount, tradeDate);
pct = plan.pct;
const stepNotional = legContract.stepNotional ?? 0;
if (stepNotional > 0) {
const liveCash = client.accountCashBalances[acc.id] ?? item.cash;
const cap = notionalCap({
maxNotional: cfg.maxNotional ?? 0,
marginRate: legContract.marginRate,
availableFunds: liveCash.availableFunds ?? liveCash.amount,
});
const obfStop = Number.isFinite(obfuscation) && obfuscation > 0 ? obfuscation : Infinity;
const stopDollarsAt = (notional: number) => Math.min(
obfStop,
dllOn ? dllStopDollars({ room: item.dllRoom, dailyLossLimit: dll, entryFee: (pct / 100) * notional, commissionPct: pct }) : Infinity,
);
sizing = sizeNotional({
leg: legAmount,
stopDollarsAt,
volatilityPerHour: legContract.volatilityPerHour,
targetHoldHours: firm.targetHoldHours || DEFAULT_TARGET_HOLD_HOURS,
commissionPct: pct,
spreadFraction: legContract.spreadFraction,
financingPctPerDay: firm.financingPctPerDay ?? 0,
maxNotional: cap,
});
if (!sizing) {
if (!plan.sizing) {
throw new Error(`no position size for ${legContract.name} — its recent volatility is unknown`);
}
contracts = Math.max(1, Math.round(sizing.notional / stepNotional));
if (cap > 0) contracts = Math.min(contracts, Math.max(1, Math.floor(cap / stepNotional)));
contracts = Math.max(1, Math.round(plan.sizing.notional / stepNotional));
if (plan.cap > 0) contracts = Math.min(contracts, Math.max(1, Math.floor(plan.cap / stepNotional)));
if ((legContract.maxContracts ?? 0) > 0) contracts = Math.min(contracts, legContract.maxContracts!);
contracts = Math.max(contracts, legContract.minContracts ?? 1);
// The real size is known now: re-check the daily-loss room with it.
if (dllOn) {
const estimate = dllStopDollars({
room: item.dllRoom, dailyLossLimit: dll, entryFee: (pct / 100) * contracts * stepNotional, commissionPct: pct,
});
if (dllOn && !plan.lastStand) {
const estimate = plan.walkAt(contracts * stepNotional);
if (estimate < DLL_MIN_STOP) {
throw new Error(`daily loss limit: $${round2(item.dllRoom)} room leaves a $${round2(estimate)} stop at this size — not trading`);
}
@@ -1075,6 +1112,7 @@ async function fireLeg(
unrecordLeg(acc.id, tradeDate, legAmount);
throw err;
}
const { sizing, obfuscation } = plan;
const fill = await sendEntry(tag, client, acc, legContract.name, contracts, action, tradeDate, legAmount);
const exitAction: 'Buy' | 'Sell' = action === 'Buy' ? 'Sell' : 'Buy';
@@ -1095,9 +1133,14 @@ async function fireLeg(
entryFee = measured ?? FALLBACK_COMMISSION_PER_CONTRACT * contracts;
}
// The stop. On a measured-fee firm whose fee didn't show, the daily-loss
// stop reserves the worst per-contract fee, not the $2.50 fallback.
// stop reserves the worst per-contract fee, not the $2.50 fallback. A
// last stand carries no daily-loss stop: a stop-out would leave the
// account nothing to trade on, so the firm's own breach is the far side.
const dllFee = pct > 0 ? entryFee : (measured ?? MAX_COMMISSION_PER_CONTRACT * contracts);
const dllDollars = dllOn ? dllStopDollars({ room: item.dllRoom, dailyLossLimit: dll, entryFee: dllFee, commissionPct: pct }) : Infinity;
const notional = fill.price * pv * contracts;
const dllDollars = dllOn && !plan.lastStand
? dllStopDollars({ room: item.dllRoom, dailyLossLimit: dll, entryFee: dllFee, commissionPct: pct, notional })
: Infinity;
const ticks = stopTicks({ obfuscationDollars: obfuscation, dllDollars, pointValue: pv, contracts, tickSize: legContract.tickSize });
if (ticks === 0) {
await flattenAndFail(tag, client, acc, legContract.name, contracts, exitAction, fill.price,
@@ -1106,12 +1149,15 @@ async function fireLeg(
// The take-profit clears the leg, both fees and — where the firm charges
// overnight swap — what a winning leg is expected to pay in it.
const orderStop = ticks !== null ? ticks * legContract.tickSize * pv * contracts : Infinity;
const swapReserve = expectedSwapToWin({
distance: legAmount + 2 * entryFee,
stopDollars: ticks !== null ? ticks * legContract.tickSize * pv * contracts : Infinity,
notional: fill.price * pv * contracts,
stopDollars: plan.lastStand
? Math.min(orderStop, breachDistance({ dllRoom: item.dllRoom, maxLossRoom: plan.maxLossRoom, entryFee }))
: orderStop,
notional,
volatilityPerHour: legContract.volatilityPerHour,
financingPctPerDay: firm.financingPctPerDay ?? 0,
financingPctPerDay: item.firm.financingPctPerDay ?? 0,
});
const tp = takeProfitPlan({
side: action, entry: fill.price, leg: legAmount + swapReserve, pointValue: pv, contracts,
@@ -1157,10 +1203,11 @@ async function fireLeg(
? ` | notional $${Math.round(contracts * (legContract.stepNotional ?? 0))} (hold ~${sizing.predictedHoldHours.toFixed(1)}h`
+ `${sizing.winProbability !== null ? `, win ${Math.round(sizing.winProbability * 100)}%` : ''})`
: '';
const stopNote = stopPrice !== null
const stopNote = (stopPrice !== null
? ` / stop @ ${stopPrice}`
+ (dllOn ? ` (dll room $${round2(item.dllRoom)} → $${round2(dllDollars)}${Number.isFinite(obfuscation) && obfuscation > 0 ? `, obf $${round2(obfuscation)}` : ''})` : '')
: '';
+ (dllOn && !plan.lastStand ? ` (dll room $${round2(item.dllRoom)} → $${round2(dllDollars)}${Number.isFinite(obfuscation) && obfuscation > 0 ? `, obf $${round2(obfuscation)}` : ''})` : '')
: '')
+ (plan.lastStand ? ` | LAST STAND — no daily-loss stop: $${round2(plan.maxLossRoom ?? 0)} to the max-drawdown floor, $${round2(item.dllRoom)} of the day's` : '');
console.log(`${tag} ${acc.name} (${item.firmName}) ${action} ${contracts}x${instrumentLabel} @ ${fill.price} | leg $${legAmount} of day $${item.plan.dayTarget} (remaining $${item.plan.remainingToday}) [${item.plan.path}${item.drain ? ' drain' : ''}] (+$${tp.totalCommission.toFixed(2)} comm${swapReserve > 0 ? `, +$${swapReserve.toFixed(2)} expected swap` : ''})${sizeNote} | exit @ ${tp.exitPrice}${stopNote} (orderId=${exitOrder.orderId})`);
return {
@@ -1434,7 +1481,12 @@ export async function fireManualLeg(accountId: number, action: 'Buy' | 'Sell' |
const state = getState();
const symbol = state.symbol !== 'Auto' ? state.symbol : 'NQ';
const resolvedAction: 'Buy' | 'Sell' = heldSide ?? (action === 'Auto' ? (Math.random() < 0.5 ? 'Buy' : 'Sell') : action);
const contract = await client.findFrontMonthContract(symbol);
const sizingItem: SizingItem = {
firmName: firm.name, firm, client, acc,
cash: ev.cash, dailyPnL: ev.dailyPnL, plan: ev.plan, drain: ev.drain,
prefix: cfg.prefix, dllRoom: room,
};
const contract = await client.findFrontMonthContract(symbol, ev.drain ? undefined : pickContextFor([sizingItem], tradeDate));
if (!contract) throw new Error(`no instrument for ${symbol}`);
if (held.length > 0 && String(contract.id) !== [...heldContracts][0]) {
throw new Error(`the ${laneName(lane)} lane holds ${[...heldContracts][0]}, not ${contract.id} — not adding to it`);
@@ -1445,11 +1497,7 @@ export async function fireManualLeg(accountId: number, action: 'Buy' | 'Sell' |
const lease = acquireTradeMutex('[manual-leg]', lane);
if (lease === null) throw new Error('another batch is in flight in this lane');
try {
const item: LegItem = {
firmName: firm.name, firm, client, acc, contract, pv,
cash: ev.cash, dailyPnL: ev.dailyPnL, plan: ev.plan, drain: ev.drain,
prefix: cfg.prefix, dllRoom: room,
};
const item: LegItem = { ...sizingItem, contract, pv };
console.log(`[manual-leg] ${acc.name} (${firm.name}): firing one leg by hand`);
runtime().lastFireAt = Date.now();
return await withAccountInFlight(acc.id, () => fireLeg('[manual-leg]', item, resolvedAction, symbol, tradeDate));
+51 -22
View File
@@ -31,7 +31,7 @@
*/
import axios from 'axios';
import { currentTradeDateCT, FIRM_RESET_UTC_HOUR, DEFAULT_TARGET_HOLD_HOURS } from './trading-logic';
import { currentTradeDateCT, FIRM_RESET_UTC_HOUR, DEFAULT_TARGET_HOLD_HOURS, rankForTarget } from './trading-logic';
import {
saveDailyPnL, loadDailyPnL, loadAccountMeta, saveAccountMeta, loadFundTransactions, saveFundTransactions,
saveEndedCycleStart,
@@ -39,7 +39,7 @@ import {
import { getAccountConfig } from './account-type-resolver';
import { getCachedFirm } from './firm-catalog';
import type { SymbolMapCandidate } from './master-protocol';
import type { PlatformClient, PlatformAccount, PlatformContract, ClientHealth } from './platform-client';
import type { PlatformClient, PlatformAccount, PlatformContract, ClientHealth, PickContext } from './platform-client';
import { OrderNotPlacedError, isOrderNotPlaced, errorMessage } from './platform-client';
import {
dxAccountId, accountDisplayName, accountCodeOf, encodeContractName, decodeContractName, roundToStep,
@@ -78,6 +78,8 @@ const OCO_POLL_MS = 5_000;
/** A pick is reused this long, so a batch's lookups (Phase 1, drain legs)
* all land on the same symbol. */
const PICK_TTL_MS = 45_000;
/** How often the dashboard's candidates (quotes, spreads) are refreshed. */
const SURVEY_INTERVAL_MS = 30 * 60_000;
const INSTRUMENT_TTL_MS = 60 * 60_000;
const ACCOUNT_INSTRUMENT_TTL_MS = 10 * 60_000;
const CANDLE_TTL_MS = 15 * 60_000;
@@ -304,10 +306,11 @@ export class DXTradeClient implements PlatformClient {
private accountInstrumentCache = new Map<string, { det: Record<string, unknown>; at: number }>();
/** Volatility per symbol, measured once per trade date (see volatility). */
private candleCache = new Map<string, { vol: number | null; candles: number; at: number; tradeDate: string }>();
/** The last instrument the selector picked — what the dashboard's hold
* estimate sizes against. */
public lastPickedContract: PlatformContract | null = null;
private lastPickTradeDate = '';
/** Every mapped instrument that could trade at the last full look — what
* the dashboard ranks each account's next leg across. */
public lastCandidates: PlatformContract[] = [];
private lastSurveyTradeDate = '';
private lastSurveyAt = 0;
private unmappedLoggedAt = new Map<string, number>();
constructor(cfg: DXTradeConfig, onSync: () => Promise<void>) {
@@ -676,12 +679,14 @@ export class DXTradeClient implements PlatformClient {
console.log(`${this.tag} sync — ${list.length} account(s), ${Object.keys(this.positions).length} open position(s)`);
this.maybeFetchDaysTraded();
// Measure the day's volatility (and so the hold estimate) at the
// first good sync of each trade date, whether or not a batch fires.
if (this.historyLoaded && this.lastPickTradeDate !== currentTradeDateCT()) {
this.lastPickTradeDate = currentTradeDateCT();
void this.findFrontMonthContract('*').catch((err) =>
console.warn(`${this.tag} daily volatility check failed: ${errorMessage(err)}`));
// Measure the day's volatility at the first good sync of each trade
// date, and refresh the candidates the dashboard sizes against
// every half hour, whether or not a batch fires.
if (this.historyLoaded && (this.lastSurveyTradeDate !== currentTradeDateCT() || Date.now() - this.lastSurveyAt >= SURVEY_INTERVAL_MS)) {
this.lastSurveyTradeDate = currentTradeDateCT();
this.lastSurveyAt = Date.now();
void this.surveyCandidates().catch((err) =>
console.warn(`${this.tag} candidate survey failed: ${errorMessage(err)}`));
}
this.syncComplete = true;
@@ -1157,12 +1162,15 @@ export class DXTradeClient implements PlatformClient {
}
/**
* The contract a CME root trades as on this firm right now: the cheapest
* tradable candidate from the symbol map, per unit of volatility (see
* scoreCandidate). Sticky while an account
* holds one of the candidates, cached briefly so a batch's lookups agree.
* The contract a CME root trades as on this firm right now, from the
* symbol map. With a pick context (the batch's leg), each candidate is
* sized as the leg would be — at its own leverage — and the cheapest one
* that reaches the target hold wins (else the quickest); without one, the
* cheapest per unit of volatility (see scoreCandidate). Sticky while an
* account holds one of the candidates; a batch's pick is reused briefly
* so its other lookups (drain legs) agree.
*/
public async findFrontMonthContract(root: string): Promise<PlatformContract | null> {
public async findFrontMonthContract(root: string, ctx?: PickContext): Promise<PlatformContract | null> {
if (!this.token) return null;
const firm = getCachedFirm(this.cfg.firmId);
const map = firm?.symbolMap ?? {};
@@ -1177,16 +1185,26 @@ export class DXTradeClient implements PlatformClient {
}
const held = new Set([...this.positionsDetail.values()].flat().map((p) => p.symbol));
const sticky = candidates.find((c) => held.has(c.symbol));
if (!sticky) {
if (!sticky && !ctx) {
const cached = this.pickCache.get(root);
if (cached && now - cached.at < PICK_TTL_MS) return cached.contract;
}
const pick = await this.pickCandidate(root, sticky ? [sticky] : candidates, sticky !== undefined);
const pick = await this.pickCandidate(root, sticky ? [sticky] : candidates, sticky !== undefined, ctx);
if (pick && !sticky) this.pickCache.set(root, { contract: pick, at: now });
return pick;
}
private async pickCandidate(root: string, candidates: SymbolMapCandidate[], sticky: boolean): Promise<PlatformContract | null> {
/** Every mapped symbol, looked at afresh whatever the accounts hold: the
* day's volatility, and the candidates the dashboard ranks. */
private async surveyCandidates(): Promise<void> {
const all = new Map<string, SymbolMapCandidate>();
for (const list of Object.values(getCachedFirm(this.cfg.firmId)?.symbolMap ?? {})) {
for (const c of list) if (!all.has(c.symbol)) all.set(c.symbol, c);
}
if (all.size > 0) await this.pickCandidate('survey', [...all.values()], false);
}
private async pickCandidate(root: string, candidates: SymbolMapCandidate[], sticky: boolean, ctx?: PickContext): Promise<PlatformContract | null> {
const ref = this.referenceAccount();
if (!ref) return null;
const firm = getCachedFirm(this.cfg.firmId);
@@ -1270,14 +1288,25 @@ export class DXTradeClient implements PlatformClient {
});
}
const ranked = board.filter((b) => b.contract).sort((a, b) => a.score! - b.score!);
let ranked = board.filter((b) => b.contract).sort((a, b) => a.score! - b.score!);
if (ctx) {
// Size the batch's leg on each: cheapest that reaches the target
// hold, else quickest.
const sized = ranked.flatMap((b) => {
const ev = ctx.evaluate(b.contract!);
if (!ev) { b.note += ', can\'t size'; return []; }
b.note += `, $${Math.round(ev.notional / 1000)}k → ${ev.holdHours.toFixed(1)}h, ~$${Math.round(ev.cost)}`;
return [{ b, holdHours: ev.holdHours, cost: ev.cost }];
});
ranked = rankForTarget(sized, ctx.targetHoldHours).map((i) => sized[i].b);
}
const winner = ranked[0];
const summary = board
.map((b) => `${b.symbol}${b.score !== null ? ` ${b.score.toFixed(4)}` : ''} (${b.note})`)
.join('; ');
this.lastFetchRaw[`pick:${root}`] = `${new Date().toISOString()} → ${winner?.symbol ?? 'none'} — ${summary}`;
console.log(`${this.tag} ${root}${sticky ? ' (held)' : ''} → ${winner?.symbol ?? 'nothing tradable'} — ${summary}`);
if (winner?.contract) this.lastPickedContract = winner.contract;
if (!sticky) this.lastCandidates = board.flatMap((b) => (b.contract ? [b.contract] : []));
return winner?.contract ?? null;
}
-1
View File
@@ -233,7 +233,6 @@ function validatePayload(raw: unknown): FirmCatalogPayload {
minDayStop: type.minDayStop === true,
// Lenient: no hard daily limit, no notional cap.
dailyLossLimit: nonNegative(type.dailyLossLimit),
maxNotional: nonNegative(type.maxNotional),
// The firm's calendar, stamped on every type so the cfg-based
// paths (projections, completion, the dashboard) all see it.
tradesEveryDay,
-3
View File
@@ -209,9 +209,6 @@ export interface CatalogAccountType {
* stop that keeps the firm's day from losing more than this, less a 10%
* reserve and fees. Optional: an older master doesn't send it. */
dailyLossLimit?: number;
/** Cap on one position's notional in dollars (0 = none), where the
* platform prices positions (DXTrade). */
maxNotional?: number;
/** Copied from the firm by the catalog sync, so every cfg-based path sees
* it: the firm trades every calendar day (24/7). */
tradesEveryDay?: boolean;
+11 -1
View File
@@ -18,6 +18,13 @@ export interface PlatformAccount {
active: boolean;
}
/** How the batch's leg would size on a candidate instrument (see planLegSize):
* null when it can't be sized there. */
export interface PickContext {
targetHoldHours: number;
evaluate(contract: PlatformContract): { notional: number; holdHours: number; cost: number } | null;
}
export interface PlatformContract {
id: number | string;
name: string;
@@ -105,7 +112,10 @@ export interface PlatformClient {
/** Drop the account's history from memory (the wipe routes), so it reads
* unloaded until the next fetch rebuilds it. */
forgetHistory(accountId: number, accountName: string): void;
findFrontMonthContract(productName: string): Promise<PlatformContract | null>;
/** The contract a product trades as. A platform that chooses between
* instruments (DXTrade's symbol map) ranks them with `pick` when given —
* how a leg would size on each — and platforms that don't, ignore it. */
findFrontMonthContract(productName: string, pick?: PickContext): Promise<PlatformContract | null>;
fetchInstrumentFees(symbols: string[]): Promise<{ [symbol: string]: number }>;
sendOrder(
+137 -13
View File
@@ -1182,6 +1182,14 @@ export function obfuscationStopDollars(
/** Share of a hard daily loss limit the bot never spends — room for a stop
* that fills worse than its price (gaps, thin weekend books). */
export const DLL_RESERVE_FRACTION = 0.10;
/** …or this share of the position's notional, when that is more: a stop's
* slippage grows with the position, a flat reserve doesn't. */
export const DLL_SLIPPAGE_FRACTION = 0.001;
/** The part of the day's room a stop leaves unspent. */
export function dllReserve(dailyLossLimit: number, notional = 0): number {
return Math.max(DLL_RESERVE_FRACTION * dailyLossLimit, DLL_SLIPPAGE_FRACTION * Math.max(0, notional));
}
/** Smallest daily-loss stop worth trading. Under a fair walk a leg of L with a
* stop of S wins S/(S + L) of the time — about 9% for $50 against $500 — so
* anything tighter just spends the day's room on fees. */
@@ -1218,11 +1226,55 @@ export function dllRoom(o: {
* entryFee + r × (stop distance) — a short's stop sits above its entry — so
* the worst loss is d(1 + r) + 2·entryFee, plus a cent of fee rounding.
* Infinity when there is no limit. Can go negative: no room at all.
*
* Overnight swap needs no reserve of its own while a day's swap is below the
* commission rate (Tradeify: 0.033% < 0.04%): a position carried past the
* reset has its entry fee on the old day's books, and the swap takes no more
* than that slot on the new day's.
*/
export function dllStopDollars(o: { room: number; dailyLossLimit: number; entryFee: number; commissionPct: number }): number {
export function dllStopDollars(o: { room: number; dailyLossLimit: number; entryFee: number; commissionPct: number; notional?: number }): number {
if (!Number.isFinite(o.room)) return Infinity;
const r = Math.max(0, o.commissionPct) / 100;
return (o.room - DLL_RESERVE_FRACTION * o.dailyLossLimit - 2 * o.entryFee - 0.01) / (1 + r);
return (o.room - dllReserve(o.dailyLossLimit, o.notional) - 2 * o.entryFee - 0.01) / (1 + r);
}
/**
* How far the account's balance is above its max-drawdown floor, or null when
* it isn't known: the broker's liquidation floor where it reports one, else
* the account type's static max loss below the starting size — whichever is
* higher.
*/
export function maxLossRoom(o: { balance: number; accountSize: number; maxLoss: number; autoLiqThreshold?: number }): number | null {
const floors: number[] = [];
if ((o.autoLiqThreshold ?? 0) > 0) floors.push(o.autoLiqThreshold!);
if (Math.abs(o.maxLoss) > 0 && o.accountSize > 0) floors.push(o.accountSize - Math.abs(o.maxLoss));
return floors.length > 0 ? round2(o.balance - Math.max(...floors)) : null;
}
/** A daily-loss stop is kept only while a stop-out would leave at least this
* share of its loss above the max-drawdown floor. */
export const LAST_STAND_FRACTION = 0.15;
/**
* Whether a leg should ride without its daily-loss stop. The stop is there to
* keep the account alive for another day; when a stop-out would leave it
* within 15% of that loss of its max-drawdown floor — or the floor is nearer
* than the stop — there is no useful day after, and the stop only gives up
* room (the reserve, and whatever the floor allows past it) for nothing. The
* leg then runs until its take-profit or the firm's own breach.
*/
export function lastStand(o: { dllRoom: number; dailyLossLimit: number; maxLossRoom: number | null }): boolean {
if (o.maxLossRoom === null || !(o.dailyLossLimit > 0) || !Number.isFinite(o.dllRoom)) return false;
const stopOut = o.dllRoom - DLL_RESERVE_FRACTION * o.dailyLossLimit;
if (!(stopOut > 0)) return false;
return o.maxLossRoom - stopOut <= LAST_STAND_FRACTION * stopOut;
}
/** On a last stand: how far price can move against the leg before the firm's
* nearer floor breaches the account — its equity carries the entry fee, not
* the exit's. What sizing and the swap estimate take as the walk's far side. */
export function breachDistance(o: { dllRoom: number; maxLossRoom: number | null; entryFee: number }): number {
return Math.min(o.dllRoom, o.maxLossRoom ?? Infinity) - o.entryFee;
}
/** Is there enough daily-loss room left to trade at all? */
@@ -1274,18 +1326,13 @@ export const DEFAULT_TARGET_HOLD_HOURS = 12;
export const MARGIN_HEADROOM = 0.97;
/**
* The largest position an account may open: the account type's notional cap
* and, where the broker states the instrument's margin rate, what the
* account's available funds can margin (the firm's leverage — 5:1 on crypto,
* 2:1 on stocks at Tradeify247). 0 = no cap.
* The largest position an account may open: what its available funds can
* margin at the broker's rate for the instrument — the firm's leverage per
* symbol (5:1 crypto, 2:1 stocks at Tradeify247). 0 = no cap known.
*/
export function notionalCap(o: { maxNotional: number; marginRate?: number; availableFunds?: number }): number {
const caps: number[] = [];
if (o.maxNotional > 0) caps.push(o.maxNotional);
if ((o.marginRate ?? 0) > 0 && Number.isFinite(o.availableFunds) && o.availableFunds! > 0) {
caps.push((MARGIN_HEADROOM * o.availableFunds!) / o.marginRate!);
}
return caps.length > 0 ? Math.min(...caps) : 0;
export function notionalCap(o: { marginRate?: number; availableFunds?: number }): number {
if (!((o.marginRate ?? 0) > 0) || !Number.isFinite(o.availableFunds) || !(o.availableFunds! > 0)) return 0;
return (MARGIN_HEADROOM * o.availableFunds!) / o.marginRate!;
}
/** The swap reserve never grows past this share of the take-profit distance
@@ -1398,6 +1445,83 @@ export function sizeNotional(o: {
};
}
/**
* One leg's size on one instrument for one account — the rule fireLeg
* trades, the instrument pick ranks by and the dashboard shows.
*
* The walk's far side (what sizing, the win chance and the swap estimate
* use) is the stop the leg carries: the tighter of the obfuscation stop and
* the hard daily-loss stop. On a last stand there is no daily-loss stop and
* the far side is the firm's own breach. `cost` is what the leg is expected
* to spend: spread and both commissions on its notional, plus swap over its
* expected hold.
*/
export function planLegSize(o: {
leg: number;
contract: { stepNotional?: number; volatilityPerHour?: number; spreadFraction?: number; marginRate?: number };
/** Per side, percent. */
commissionPct: number;
targetHoldHours: number;
financingPctPerDay: number;
dailyLossLimit: number;
/** Infinity = no hard daily limit. */
dllRoom: number;
maxLossRoom: number | null;
/** Infinity (or ≤ 0) = no obfuscation stop. */
obfuscationDollars: number;
availableFunds?: number;
}): {
lastStand: boolean;
cap: number;
walkAt: (notional: number) => number;
sizing: ReturnType<typeof sizeNotional>;
cost: number | null;
} {
const dllOn = Number.isFinite(o.dllRoom) && o.dailyLossLimit > 0;
const stand = dllOn && lastStand({ dllRoom: o.dllRoom, dailyLossLimit: o.dailyLossLimit, maxLossRoom: o.maxLossRoom });
const obf = Number.isFinite(o.obfuscationDollars) && o.obfuscationDollars > 0 ? o.obfuscationDollars : Infinity;
const r = Math.max(0, o.commissionPct) / 100;
const walkAt = (notional: number) => Math.min(
obf,
!dllOn ? Infinity
: stand ? breachDistance({ dllRoom: o.dllRoom, maxLossRoom: o.maxLossRoom, entryFee: r * notional })
: dllStopDollars({ room: o.dllRoom, dailyLossLimit: o.dailyLossLimit, entryFee: r * notional, commissionPct: o.commissionPct, notional }),
);
const cap = notionalCap({ marginRate: o.contract.marginRate, availableFunds: o.availableFunds });
const sizing = (o.contract.stepNotional ?? 0) > 0
? sizeNotional({
leg: o.leg,
stopDollarsAt: walkAt,
volatilityPerHour: o.contract.volatilityPerHour,
targetHoldHours: o.targetHoldHours,
commissionPct: o.commissionPct,
spreadFraction: o.contract.spreadFraction,
financingPctPerDay: o.financingPctPerDay,
maxNotional: cap,
})
: null;
const cost = sizing
? sizing.notional * (Math.max(0, o.contract.spreadFraction ?? 0) + 2 * r)
+ (Math.max(0, o.financingPctPerDay) / 100) * sizing.notional * (sizing.predictedHoldHours / 24)
: null;
return { lastStand: stand, cap, walkAt, sizing, cost };
}
/**
* Order candidates for a leg: those that reach the target hold (within a
* few percent) first, cheapest first; then those whose leverage cap keeps
* them short of it, quickest first. Returns indices into `options`.
*/
export function rankForTarget(options: { holdHours: number; cost: number }[], targetHoldHours: number): number[] {
const reaches = (h: number) => h <= targetHoldHours * 1.02 + 0.01;
return options
.map((opt, i) => ({ ...opt, i, reach: reaches(opt.holdHours) }))
.sort((a, b) => (a.reach === b.reach
? (a.reach ? a.cost - b.cost : a.holdHours - b.holdHours) || a.i - b.i
: a.reach ? -1 : 1))
.map((x) => x.i);
}
// ── trading hours ────────────────────────────────────────────────────────────
/** Tradeify247 (and DXtrade brokers generally) roll the trading day at 22:00