@pear-protocol/utils 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  import type { InstrumentId } from '@pear-protocol/types';
2
2
  import BigNumber from 'bignumber.js';
3
+ import type { Fill } from '../fills/fill.types';
3
4
  export type AssetUnrealizedPnL = {
4
5
  id: InstrumentId;
5
6
  signedQuantity: BigNumber;
@@ -45,3 +46,4 @@ export type AssetRealizedPnL = {
45
46
  pearFees: BigNumber;
46
47
  closures: AssetClosure[];
47
48
  };
49
+ export type DeployedCapitalFill = Pick<Fill, 'symbol' | 'side' | 'price' | 'quantity'>;
@@ -1,7 +1,7 @@
1
1
  import type { InstrumentId } from '@pear-protocol/types';
2
2
  import BigNumber from 'bignumber.js';
3
3
  import type { Fill } from '../fills/fill.types';
4
- import type { AssetRealizedPnL, AssetUnrealizedPnL } from './asset.types';
4
+ import type { AssetRealizedPnL, AssetUnrealizedPnL, DeployedCapitalFill } from './asset.types';
5
5
  type ExposureMap = Record<InstrumentId, string>;
6
6
  type PriceMap = Record<InstrumentId, string>;
7
7
  /**
@@ -43,4 +43,44 @@ export declare function computeAssetUnrealizedPnLs(exposureMap: ExposureMap, pri
43
43
  * Formula: Σ(realizedPnL)
44
44
  */
45
45
  export declare function computeAssetRealizedPnLs(fills: Fill[]): AssetRealizedPnL[];
46
+ /**
47
+ * The most cash the position's selected legs had committed at one time.
48
+ *
49
+ * Cash, not market value: each opening fill commits what it actually paid, at its own
50
+ * execution price, and each closing fill releases the share of that commitment the quantity
51
+ * it closed was holding. No price beyond the fills' own is read, which matters because there
52
+ * is none to read — this system keeps no historical price series, so a market-value
53
+ * denominator could only ever be sampled at fills anyway.
54
+ *
55
+ * Sampling it that way was the earlier rule, and it failed in the direction that flatters.
56
+ * Revaluing a whole leg at each fill's price lets the denominator fall BELOW the money the
57
+ * trader put in: buy 10 at 200 then 10 more at 100 and the leg's worth never exceeds 2,000
58
+ * though 3,000 went in, so the return comes out 1.5x too large. Averaging down is ordinary
59
+ * trading, and a public board must not pay for it. Counting cash cannot do this — the
60
+ * denominator only ever rises when money goes in.
61
+ *
62
+ * Walked from the fills rather than read off the size stamped at the open, because a
63
+ * position is routinely scaled up long after it opens. Dividing by the opening size measures
64
+ * a return against capital the trader has since multiplied, and overstates it by exactly
65
+ * that factor — a position opened at 73 and grown to 33,499 reported 774% for a trade that
66
+ * made 1.7%.
67
+ *
68
+ * The peak rather than the running total of everything opened, so a position that reduces
69
+ * and rebuilds is charged for the capital it committed, not for the same capital counted
70
+ * twice. Unsigned per leg, because a pair trade's short leg is size the trader put at risk,
71
+ * not a credit against the long.
72
+ *
73
+ * Every loaded fill moves the commitment, an external one included: exposure has no per-fill
74
+ * provenance, so dropping a venue-merged fill would misstate what the position tied up rather
75
+ * than narrow the measure. Read in the chronological order the reader guarantees — unlike
76
+ * the per-asset realized walk, this total spans every leg at once, so a leg out of sequence
77
+ * misstates the basket in either direction: it can show two legs held together that never
78
+ * were, or miss a pairing that was.
79
+ *
80
+ * Fills sharing one timestamp are separated by symbol, which is alphabetical rather than
81
+ * causal: a leg swapped for another in the same instant may be seen committed alongside it.
82
+ * That only ever adds to the peak, so the denominator errs large and the return it produces
83
+ * errs small — the safe direction for a public board.
84
+ */
85
+ export declare function computeDeployedCapital(fills: DeployedCapitalFill[], assets: Set<string> | undefined): BigNumber;
46
86
  export {};
@@ -1,2 +1,2 @@
1
- export type { AssetClosure, AssetRealizedPnL, AssetUnrealizedPnL } from './asset.types';
1
+ export type { AssetClosure, AssetRealizedPnL, AssetUnrealizedPnL, DeployedCapitalFill } from './asset.types';
2
2
  export * from './compute';
package/dist/index.js CHANGED
@@ -239,6 +239,35 @@ function computeAssetRealizedPnLs(fills) {
239
239
  return result;
240
240
  }
241
241
  __name(computeAssetRealizedPnLs, "computeAssetRealizedPnLs");
242
+ function computeDeployedCapital(fills, assets) {
243
+ const legs = /* @__PURE__ */ new Map();
244
+ let committed = ZERO;
245
+ let peak = ZERO;
246
+ for (const fill of fills) {
247
+ if (assets && !assets.has(fill.symbol.toUpperCase())) {
248
+ continue;
249
+ }
250
+ const leg = legs.get(fill.symbol) ?? {
251
+ quantity: ZERO,
252
+ basis: ZERO
253
+ };
254
+ const delta = signedBySide(fill.quantity, fill.side);
255
+ const closed = closesAgainstHolding(leg.quantity, delta);
256
+ const opened = subtract(abs(delta), closed);
257
+ const released = isZero(leg.quantity) ? ZERO : divide(multiply(leg.basis, closed), abs(leg.quantity));
258
+ const basis = add(subtract(leg.basis, released), multiply(opened, fill.price));
259
+ committed = add(subtract(committed, leg.basis), basis);
260
+ legs.set(fill.symbol, {
261
+ quantity: add(leg.quantity, delta),
262
+ basis
263
+ });
264
+ if (isGreaterThan(committed, peak)) {
265
+ peak = committed;
266
+ }
267
+ }
268
+ return peak;
269
+ }
270
+ __name(computeDeployedCapital, "computeDeployedCapital");
242
271
  function walkAssetFills(fills) {
243
272
  let entryPrice = ZERO;
244
273
  let positionSize = ZERO;
@@ -297,6 +326,13 @@ function walkAssetFills(fills) {
297
326
  };
298
327
  }
299
328
  __name(walkAssetFills, "walkAssetFills");
329
+ function closesAgainstHolding(held, delta) {
330
+ if (isZero(held) || isPositive(held) === isPositive(delta)) {
331
+ return ZERO;
332
+ }
333
+ return min(abs(delta), abs(held));
334
+ }
335
+ __name(closesAgainstHolding, "closesAgainstHolding");
300
336
 
301
337
  // src/basket/compute.ts
302
338
  function computeBasketWeightedRatioV1(basket, priceMap) {
@@ -2316,4 +2352,4 @@ function takeVerifier(handoffId, storage) {
2316
2352
  }
2317
2353
  __name(takeVerifier, "takeVerifier");
2318
2354
 
2319
- export { BIPS, ZERO, abs, add, aggregateRealizedPositionState, baseToContracts, buildApplicables, compareValue, computeAssetEntryNotional, computeAssetGrossRealizedPnL, computeAssetRealizedPnLs, computeAssetUndeterminedSizes, computeAssetUnrealizedPnL, computeAssetUnrealizedPnLs, computeBasketWeightedRatioV1, computeEntryPriceForAsset, computeMaxBasketSize, computeMultiQuoteBasketSize, computePositionEntryPrices, computeRealizedPnlBySymbol, computeRealizedPnlFromFills, computeRealizedPositionState, computeSyncPayload, computeUnrealizedPositionState, computeUnrealizedPositionStateFromEntryPrices, configureProxy, contractsToBase, countDecimals, deriveBasketKey, divide, exponentiate, finishXHandoff, generateDeterministicPositionKey, isEqualTo, isFiniteDecimal, isGreaterThan, isGreaterThanOrEqual, isLessThan, isLessThanOrEqual, isNegative, isPositive, isZero, min, multiply, negate, parse, precisePrice, preciseQuantity, proxyFetch, sideSign, sign, signed, signedBySide, sizeBasket, sizeBasketByLeverageMode, sizeBasketPerAssetLeverage, startXHandoff, stripXReturn, subtract, toDecimalString, validateLeverage, validateQuantity };
2355
+ export { BIPS, ZERO, abs, add, aggregateRealizedPositionState, baseToContracts, buildApplicables, compareValue, computeAssetEntryNotional, computeAssetGrossRealizedPnL, computeAssetRealizedPnLs, computeAssetUndeterminedSizes, computeAssetUnrealizedPnL, computeAssetUnrealizedPnLs, computeBasketWeightedRatioV1, computeDeployedCapital, computeEntryPriceForAsset, computeMaxBasketSize, computeMultiQuoteBasketSize, computePositionEntryPrices, computeRealizedPnlBySymbol, computeRealizedPnlFromFills, computeRealizedPositionState, computeSyncPayload, computeUnrealizedPositionState, computeUnrealizedPositionStateFromEntryPrices, configureProxy, contractsToBase, countDecimals, deriveBasketKey, divide, exponentiate, finishXHandoff, generateDeterministicPositionKey, isEqualTo, isFiniteDecimal, isGreaterThan, isGreaterThanOrEqual, isLessThan, isLessThanOrEqual, isNegative, isPositive, isZero, min, multiply, negate, parse, precisePrice, preciseQuantity, proxyFetch, sideSign, sign, signed, signedBySide, sizeBasket, sizeBasketByLeverageMode, sizeBasketPerAssetLeverage, startXHandoff, stripXReturn, subtract, toDecimalString, validateLeverage, validateQuantity };
@@ -10,6 +10,9 @@ type PositionKeyInput = {
10
10
  * no side — same-asset positions therefore produce the SAME key, which is
11
11
  * exactly what the active-position unique index relies on and what makes the
12
12
  * apply UPSERT find-or-create the single correct target.
13
+ *
14
+ * PHASE-1 LEG ID WARNING: `symbols` must be instrument ids
15
+ * (`leg.id ?? leg.symbol`, or exposure keys). A phase-3 ticker here re-hashes and orphans every position.
13
16
  */
14
17
  export declare function generateDeterministicPositionKey(input: PositionKeyInput): string;
15
18
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pear-protocol/utils",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "Pear Protocol Utility functions",
5
5
  "private": false,
6
6
  "type": "module",
@@ -27,7 +27,7 @@
27
27
  },
28
28
  "dependencies": {
29
29
  "@noble/hashes": "^1.3.2",
30
- "@pear-protocol/types": "^1.28.0",
30
+ "@pear-protocol/types": "^1.32.0",
31
31
  "@scure/base": "^2.3.0",
32
32
  "bignumber.js": "9.3.1"
33
33
  },