fix(execution): include unpaid fees in funding checks
This commit is contained in:
parent
74ba3b97f5
commit
a21a1b8cb8
3 changed files with 248 additions and 19 deletions
|
|
@ -5,6 +5,7 @@ import {
|
|||
amount,
|
||||
applyFill,
|
||||
decimal,
|
||||
fillPrice,
|
||||
fingerprint,
|
||||
riskViolations,
|
||||
terminal,
|
||||
|
|
@ -101,10 +102,17 @@ export class SimulationExecution {
|
|||
quote.timestamp > timestamp
|
||||
? 'Missing, stale, or future market quote'
|
||||
: undefined;
|
||||
const price = quote && !invalid ? this.fillPrice(order, quote) : 0;
|
||||
const price = quote && !invalid ? fillPrice(order, quote) : 0;
|
||||
const violations = invalid
|
||||
? [invalid]
|
||||
: riskViolations(tx.account, request, await tx.openOrders(), price, timestamp);
|
||||
: riskViolations(
|
||||
tx.account,
|
||||
request,
|
||||
await tx.openOrders(),
|
||||
price,
|
||||
timestamp,
|
||||
order.policy.commission
|
||||
);
|
||||
if (violations.length) {
|
||||
order.report.status = 'rejected';
|
||||
order.report.rejectionReason = violations.join('; ');
|
||||
|
|
@ -119,19 +127,6 @@ export class SimulationExecution {
|
|||
await this.journalChange(tx, change);
|
||||
return change;
|
||||
}
|
||||
private fillPrice(order: StoredOrder, quote: Quote) {
|
||||
const raw =
|
||||
order.request.side === 'buy'
|
||||
? quote.ask * (1 + order.policy.slippage)
|
||||
: quote.bid * (1 - order.policy.slippage);
|
||||
return amount(
|
||||
order.request.orderType === 'limit'
|
||||
? order.request.side === 'buy'
|
||||
? Math.min(raw, defined(order.request.limitPrice))
|
||||
: Math.max(raw, defined(order.request.limitPrice))
|
||||
: raw
|
||||
);
|
||||
}
|
||||
async fill(
|
||||
tx: ExecutionTransaction,
|
||||
order: StoredOrder,
|
||||
|
|
@ -166,13 +161,14 @@ export class SimulationExecution {
|
|||
}
|
||||
return [];
|
||||
}
|
||||
const price = this.fillPrice(order, quote);
|
||||
const price = fillPrice(order, quote);
|
||||
const violations = riskViolations(
|
||||
tx.account,
|
||||
{ ...request, quantity: remaining },
|
||||
reservations.filter(o => o.report.orderId !== order.report.orderId),
|
||||
price,
|
||||
this.clock.now(quote)
|
||||
this.clock.now(quote),
|
||||
order.policy.commission
|
||||
);
|
||||
if (violations.length) {
|
||||
order.report.status = 'cancelled';
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import Decimal from 'decimal.js-light';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { MarketData, OrderRequest } from '../types';
|
||||
|
||||
export interface RiskLimits {
|
||||
|
|
@ -171,13 +172,28 @@ export function accountMetrics(account: Account) {
|
|||
dailyPnl: account.dailyPnl,
|
||||
};
|
||||
}
|
||||
/** The same stored pricing policy values both fills and their unpaid commissions. */
|
||||
export function fillPrice(order: StoredOrder, quote: Quote) {
|
||||
const raw =
|
||||
order.request.side === 'buy'
|
||||
? quote.ask * (1 + order.policy.slippage)
|
||||
: quote.bid * (1 - order.policy.slippage);
|
||||
return amount(
|
||||
order.request.orderType === 'limit'
|
||||
? order.request.side === 'buy'
|
||||
? Math.min(raw, defined(order.request.limitPrice))
|
||||
: Math.max(raw, defined(order.request.limitPrice))
|
||||
: raw
|
||||
);
|
||||
}
|
||||
/** Quantities are shares; exposure/loss limits are account-currency notional amounts. */
|
||||
export function riskViolations(
|
||||
account: Account,
|
||||
request: OrderRequest,
|
||||
reservations: StoredOrder[],
|
||||
price: number,
|
||||
timestamp: number
|
||||
timestamp: number,
|
||||
commission: number
|
||||
): string[] {
|
||||
const violations: string[] = [];
|
||||
if (request.quantity > account.limits.maxOrderSize) {
|
||||
|
|
@ -195,10 +211,21 @@ export function riskViolations(
|
|||
}
|
||||
const proposed = current + signed;
|
||||
quantities.set(request.symbol, { long: proposed, short: proposed });
|
||||
// Paid fees already reduce equity. Reserve only the remaining, unpaid liability.
|
||||
let unpaidFees = decimal(amount(decimal(request.quantity).times(price).times(commission)));
|
||||
for (const order of reservations) {
|
||||
if (terminal(order.report.status)) {
|
||||
continue;
|
||||
}
|
||||
const qty = amount(
|
||||
decimal(order.request.quantity).minus(order.report.fills.reduce((n, f) => n + f.quantity, 0))
|
||||
);
|
||||
const quote = account.quotes[order.request.symbol];
|
||||
if (quote) {
|
||||
unpaidFees = unpaidFees.plus(
|
||||
amount(decimal(qty).times(fillPrice(order, quote)).times(order.policy.commission))
|
||||
);
|
||||
}
|
||||
const q = quantities.get(order.request.symbol) ?? { long: 0, short: 0 };
|
||||
if (order.request.side === 'buy') {
|
||||
q.long = amount(decimal(q.long).plus(qty));
|
||||
|
|
@ -234,7 +261,7 @@ export function riskViolations(
|
|||
if (gross.gt(account.limits.maxGrossExposure) && !reducing) {
|
||||
violations.push('Gross notional limit');
|
||||
}
|
||||
if (gross.gt(Math.max(0, accountMetrics(account).equity)) && !reducing) {
|
||||
if (gross.plus(unpaidFees).gt(Math.max(0, accountMetrics(account).equity)) && !reducing) {
|
||||
violations.push('Unlevered capital exposure limit');
|
||||
}
|
||||
return violations;
|
||||
|
|
|
|||
206
test/integration/fee-funding.test.ts
Normal file
206
test/integration/fee-funding.test.ts
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository';
|
||||
import { config, makeExecution, order, quote, start } from '../fixtures/execution';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
const runId = '00000000-0000-4000-8000-000000000003';
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
async function fixture() {
|
||||
const repository = new BacktestExecutionRepository();
|
||||
const runtime = makeExecution(repository);
|
||||
await runtime.execution.initialize(
|
||||
{
|
||||
...config,
|
||||
runId,
|
||||
commission: 0.01,
|
||||
riskLimits: {
|
||||
maxOrderSize: 10000,
|
||||
maxPositionSize: 10000,
|
||||
maxDailyLoss: 1000000,
|
||||
maxSymbolExposure: 1000000,
|
||||
maxGrossExposure: 1000000,
|
||||
},
|
||||
},
|
||||
runtime.engine
|
||||
);
|
||||
cleanup.push(() => runtime.execution.shutdown());
|
||||
return { ...runtime, repository };
|
||||
}
|
||||
|
||||
describe('fee-inclusive legacy capital commitments', () => {
|
||||
test('fee_budget_10000: an otherwise fully funded buy rejects without financial mutation', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q'));
|
||||
const before = await execution.getAccount();
|
||||
|
||||
const report = await execution.submitOrder(order('unfunded', 'buy', 100));
|
||||
|
||||
expect(report.status).toBe('rejected');
|
||||
expect(report.rejectionReason).toBe('Unlevered capital exposure limit');
|
||||
expect(report.fills).toEqual([]);
|
||||
expect(await execution.getAccount()).toEqual(before);
|
||||
expect(await execution.getPositions()).toEqual([]);
|
||||
});
|
||||
|
||||
test('fee_budget_99: entry fees leave exactly one unit of cash', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q'));
|
||||
|
||||
const report = await execution.submitOrder(order('funded', 'buy', 99));
|
||||
|
||||
expect(report.status).toBe('filled');
|
||||
expect(report.fills.map(fill => fill.commission)).toEqual([99]);
|
||||
expect((await execution.getAccount()).cash).toBe(1);
|
||||
expect((await execution.getAccount()).equity).toBe(9901);
|
||||
expect((await execution.getPositions())[0]?.quantity).toBe(99);
|
||||
});
|
||||
|
||||
test('pending_fee_commitments and cancelled_commitment_released: two commitments of 5050 cannot fit 10000', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('a', 100, 0));
|
||||
await execution.onMarketData(quote('b', 100, 0, start, 'B'));
|
||||
const first = await execution.submitOrder(order('first', 'buy', 50));
|
||||
expect(first.status).toBe('accepted');
|
||||
expect(first.fills).toEqual([]);
|
||||
|
||||
const second = await execution.submitOrder({ ...order('second', 'buy', 50), symbol: 'B' });
|
||||
expect(second.status).toBe('rejected');
|
||||
expect(second.rejectionReason).toBe('Unlevered capital exposure limit');
|
||||
expect((await execution.getAccount()).cash).toBe(10000);
|
||||
|
||||
expect(await execution.cancelOrder(first.orderId)).toBe(true);
|
||||
const replacement = await execution.submitOrder({
|
||||
...order('replacement', 'buy', 99),
|
||||
symbol: 'B',
|
||||
});
|
||||
expect(replacement.status).toBe('accepted');
|
||||
await execution.onMarketData(quote('b-fill', 100, 99, start + 1, 'B'));
|
||||
expect((await execution.getOrderStatus(replacement.orderId))?.status).toBe('filled');
|
||||
expect((await execution.getAccount()).cash).toBe(1);
|
||||
expect((await execution.getOrderStatus(first.orderId))?.fills).toEqual([]);
|
||||
});
|
||||
|
||||
test('partial_fee_not_double_counted: fills 10 then 89 charge 99 once, including duplicate events', async () => {
|
||||
const { execution } = await fixture();
|
||||
const firstQuote = quote('q1', 100, 10);
|
||||
await execution.onMarketData(firstQuote);
|
||||
const first = await execution.submitOrder(order('partial', 'buy', 99));
|
||||
expect(first.status).toBe('partiallyFilled');
|
||||
expect(first.fills.map(fill => [fill.quantity, fill.commission])).toEqual([[10, 10]]);
|
||||
expect((await execution.getAccount()).cash).toBe(8990);
|
||||
|
||||
expect(await execution.submitOrder(order('partial', 'buy', 99))).toEqual(first);
|
||||
expect(await execution.onMarketData(firstQuote)).toBe(false);
|
||||
const nextQuote = quote('q2', 100, 89, start + 1);
|
||||
await execution.onMarketData(nextQuote);
|
||||
const complete = await execution.getOrderStatus(first.orderId);
|
||||
expect(complete?.status).toBe('filled');
|
||||
expect(complete?.fills.map(fill => [fill.quantity, fill.commission])).toEqual([
|
||||
[10, 10],
|
||||
[89, 89],
|
||||
]);
|
||||
expect((await execution.getAccount()).cash).toBe(1);
|
||||
const beforeRetry = await execution.getAccount();
|
||||
expect(await execution.onMarketData(nextQuote)).toBe(false);
|
||||
expect(await execution.submitOrder(order('partial', 'buy', 99))).toEqual(complete);
|
||||
expect(await execution.getAccount()).toEqual(beforeRetry);
|
||||
});
|
||||
|
||||
test('frozen_order_fee_policy: pending commitments retain their original commission', async () => {
|
||||
const { execution, repository } = await fixture();
|
||||
await execution.onMarketData(quote('q', 100, 0));
|
||||
const first = await execution.submitOrder(order('first', 'buy', 50));
|
||||
expect(first.status).toBe('accepted');
|
||||
await repository.transact(runId, async tx => {
|
||||
tx.account.commission = 0;
|
||||
});
|
||||
|
||||
const second = await execution.submitOrder(order('second', 'buy', 50));
|
||||
expect(second.status).toBe('rejected');
|
||||
expect(second.rejectionReason).toBe('Unlevered capital exposure limit');
|
||||
await execution.onMarketData(quote('fill', 100, 50, start + 1));
|
||||
expect((await execution.getOrderStatus(first.orderId))?.fills[0]?.commission).toBe(50);
|
||||
expect((await execution.getAccount()).cash).toBe(4950);
|
||||
});
|
||||
|
||||
test('a partially filled pending order reserves only its unpaid remaining fees for another order', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q1', 100, 10));
|
||||
const partial = await execution.submitOrder(order('partial', 'buy', 50));
|
||||
expect(partial.status).toBe('partiallyFilled');
|
||||
expect(partial.fills[0]?.commission).toBe(10);
|
||||
|
||||
const pending = await execution.submitOrder(order('other', 'buy', 49));
|
||||
expect(pending.status).toBe('accepted');
|
||||
await execution.onMarketData(quote('q2', 100, 89, start + 1));
|
||||
const first = await execution.getOrderStatus(partial.orderId);
|
||||
const second = await execution.getOrderStatus(pending.orderId);
|
||||
expect(first?.status).toBe('filled');
|
||||
expect(first?.fills.map(fill => fill.commission)).toEqual([10, 40]);
|
||||
expect(second?.status).toBe('filled');
|
||||
expect(second?.fills.map(fill => fill.commission)).toEqual([49]);
|
||||
expect((await execution.getAccount()).cash).toBe(1);
|
||||
});
|
||||
|
||||
test('frozen_order_fee_policy: fill-time admission uses stored rather than current commission', async () => {
|
||||
const { execution, repository } = await fixture();
|
||||
await execution.onMarketData(quote('q', 100, 0));
|
||||
const pending = await execution.submitOrder(order('pending', 'buy', 99));
|
||||
expect(pending.status).toBe('accepted');
|
||||
await repository.transact(runId, async tx => {
|
||||
tx.account.commission = 0.5;
|
||||
});
|
||||
|
||||
await execution.onMarketData(quote('fill', 100, 99, start + 1));
|
||||
const report = await execution.getOrderStatus(pending.orderId);
|
||||
expect(report?.status).toBe('filled');
|
||||
expect(report?.fills[0]?.commission).toBe(99);
|
||||
expect((await execution.getAccount()).cash).toBe(1);
|
||||
});
|
||||
|
||||
test('fill-time repricing cannot consume capital reserved for unpaid fees', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q', 99, 0));
|
||||
const pending = await execution.submitOrder(order('pending', 'buy', 100));
|
||||
expect(pending.status).toBe('accepted');
|
||||
|
||||
await execution.onMarketData(quote('gap', 100, 100, start + 1));
|
||||
const report = await execution.getOrderStatus(pending.orderId);
|
||||
expect(report?.status).toBe('cancelled');
|
||||
expect(report?.rejectionReason).toBe('Unlevered capital exposure limit');
|
||||
expect(report?.fills).toEqual([]);
|
||||
expect((await execution.getAccount()).cash).toBe(10000);
|
||||
});
|
||||
|
||||
test('existing long/short reversal behavior is unchanged', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('q'));
|
||||
for (const [id, side, quantity] of [
|
||||
['long', 'buy', 10],
|
||||
['reverse', 'sell', 20],
|
||||
['close', 'buy', 10],
|
||||
] as const) {
|
||||
expect((await execution.submitOrder(order(id, side, quantity))).status).toBe('filled');
|
||||
}
|
||||
expect((await execution.getAccount()).cash).toBe(9960);
|
||||
expect((await execution.getPositions())[0]?.quantity).toBe(0);
|
||||
});
|
||||
|
||||
test('reducing-order exemption still permits an insolvent short cover under legacy policy', async () => {
|
||||
const { execution } = await fixture();
|
||||
await execution.onMarketData(quote('short', 100, 99));
|
||||
expect((await execution.submitOrder(order('short', 'sell', 99))).status).toBe('filled');
|
||||
await execution.onMarketData(quote('gap', 200, 99, start + 1));
|
||||
|
||||
const report = await execution.submitOrder(order('cover', 'buy', 99));
|
||||
expect(report.status).toBe('filled');
|
||||
expect(report.fills[0]?.commission).toBe(198);
|
||||
expect((await execution.getAccount()).cash).toBe(-197);
|
||||
expect((await execution.getPositions())[0]?.quantity).toBe(0);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue