@accounter/server
Version:
Accounter GraphQL server
70 lines • 2.9 kB
JavaScript
import { SecurityTradeType } from '../../../shared/enums.js';
import { dateToTimelessDateString } from '../../../shared/helpers/misc.js';
import { toSecurityTradeType } from './security-execution-enums.helper.js';
/**
* How each kind of execution moves the holding. Cash-only actions — a dividend or an interest
* payment — leave the position untouched, which is why this is not the same map as the
* matcher's cash direction.
*/
const QUANTITY_DIRECTION = {
[]: 1,
[]: -1,
[]: -1,
[]: 1,
[]: 1,
[]: -1,
[]: 1,
[]: -1,
[]: 0,
[]: 0,
};
const toNumber = (value) => {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : 0;
};
/**
* The holding a security's ingested executions add up to, plus what was paid for it.
*
* Derived, not reported: the bank's own balances are not ingested. Corporate actions that
* change the unit count without an execution row (a split, say) are therefore invisible, and a
* history that starts mid-life starts from zero — hence `historyStartDate`.
*/
export function calculateSecurityPosition(executions) {
let quantity = 0;
let boughtQuantity = 0;
let totalBought = 0;
let totalSold = 0;
let currency = null;
let historyStart = null;
let lastExecution = null;
for (const execution of executions) {
const tradeType = toSecurityTradeType(execution.trade_type);
const units = toNumber(execution.nv);
const netValue = Math.abs(toNumber(execution.net_value_trade_currency));
quantity += QUANTITY_DIRECTION[tradeType] * units;
if (tradeType === SecurityTradeType.Buy) {
boughtQuantity += units;
totalBought += netValue;
}
if (tradeType === SecurityTradeType.Sell || tradeType === SecurityTradeType.Redemption) {
totalSold += netValue;
}
currency ??= execution.trade_currency;
if (!historyStart || execution.trade_date < historyStart) {
historyStart = execution.trade_date;
}
if (!lastExecution || execution.trade_date > lastExecution) {
lastExecution = execution.trade_date;
}
}
return {
quantity,
averageCost: boughtQuantity > 0 ? totalBought / boughtQuantity : null,
totalBought,
totalSold,
currency,
historyStartDate: historyStart ? dateToTimelessDateString(historyStart) : null,
lastExecutionDate: lastExecution ? dateToTimelessDateString(lastExecution) : null,
};
}
//# sourceMappingURL=security-position.helper.js.map