@metamask-previews/perps-controller 22.2.0-preview-2ad7fb9 → 22.3.0-preview-55295a2

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.
@@ -0,0 +1,96 @@
1
+ import type { PerpsProviderType, Position } from '../types/index.js';
2
+ /**
3
+ * Inputs to {@link estimateCloseReceive}.
4
+ */
5
+ export type CloseReceiveEstimateParams = {
6
+ /** The position being closed; a `Position` can be passed as-is. */
7
+ position: Pick<Position, 'size' | 'entryPrice' | 'marginUsed' | 'unrealizedPnl'> & {
8
+ leverage: Pick<Position['leverage'], 'type'>;
9
+ };
10
+ /**
11
+ * Provider holding the position. It decides whether isolated `marginUsed`
12
+ * is the position's collateral; for Lighter or an unknown provider,
13
+ * isolated margin returned is undefined. `Position.providerId` is only set
14
+ * under aggregation, so pass the provider explicitly.
15
+ */
16
+ providerId: PerpsProviderType;
17
+ /**
18
+ * Size to close in base units, unsigned: the whole position or part of it.
19
+ * A size above the position size closes the whole position.
20
+ */
21
+ closeSize: number | string;
22
+ /**
23
+ * Price the close executes at: the limit price of a limit close, else the
24
+ * live price. Undefined until known.
25
+ */
26
+ price: number | string | undefined;
27
+ /**
28
+ * Total fee rate for the close as a decimal (0.00145 = 0.145%), such as
29
+ * `FeeCalculationResult.feeRate` from `calculateFees` for this close, which
30
+ * already applies the maker or taker rate and any fee discount. Undefined
31
+ * until quoted.
32
+ */
33
+ feeRate: number | undefined;
34
+ };
35
+ /**
36
+ * The cash a close returns, in USD. Each figure is undefined while an input it
37
+ * needs is missing or unusable; none falls back to 0.
38
+ */
39
+ export type CloseReceiveEstimate = {
40
+ /** The closed share of the margin backing the position, unrealized PnL excluded. */
41
+ marginReturned: number | undefined;
42
+ /** PnL realized on the closed size at the close price. */
43
+ realizedPnl: number | undefined;
44
+ /** Fee on the closed notional at the supplied fee rate. */
45
+ fee: number | undefined;
46
+ /**
47
+ * `marginReturned + realizedPnl`, less `fee`, each of the two rounded first
48
+ * to `CLOSE_POSITION_CONFIG.UsdDecimalPlaces` decimals, half away from zero.
49
+ * A margin row that includes the PnL and a fee row, shown at that rounding,
50
+ * add up to it. Undefined unless all three are known.
51
+ */
52
+ receive: number | undefined;
53
+ };
54
+ /**
55
+ * Inputs to {@link calculateNetClosedPnl}. An `OrderFill` can be passed as-is.
56
+ */
57
+ export type NetClosedPnlParams = {
58
+ /** Realized PnL the venue reported for the fill (`OrderFill.pnl`). */
59
+ pnl?: number | string;
60
+ /** Fee paid on the fill (`OrderFill.fee`). */
61
+ fee?: number | string;
62
+ };
63
+ /**
64
+ * Estimate the cash a close returns: the closed share of the position's
65
+ * backing margin, plus the PnL realized at the close price, minus the fee.
66
+ *
67
+ * Backing margin is `marginUsed`, less the unrealized PnL for Hyperliquid
68
+ * isolated margin, which holds it. Cross margin is taken as reported. Lighter
69
+ * isolated `marginUsed` is required margin, not the allocated collateral, so
70
+ * its margin returned and receive are undefined. The realized PnL replaces the
71
+ * mark-price PnL, so a limit close is quoted at its limit price. A close is
72
+ * reduce-only, so a `closeSize` above the position size closes the whole
73
+ * position.
74
+ *
75
+ * @param params - The close inputs.
76
+ * @param params.position - The position being closed.
77
+ * @param params.providerId - Provider holding the position.
78
+ * @param params.closeSize - Unsigned size to close, in base units.
79
+ * @param params.price - Price the close executes at.
80
+ * @param params.feeRate - Total fee rate for the close, as a decimal.
81
+ * @returns The estimate; a figure is undefined while an input it needs is
82
+ * missing or unusable.
83
+ */
84
+ export declare function estimateCloseReceive({ position, providerId, closeSize, price, feeRate, }: CloseReceiveEstimateParams): CloseReceiveEstimate;
85
+ /**
86
+ * A fill's closed PnL net of its fee: the venue's realized PnL less the fee
87
+ * paid on the fill.
88
+ *
89
+ * @param params - The fill figures.
90
+ * @param params.pnl - Realized PnL the venue reported.
91
+ * @param params.fee - Fee paid on the fill.
92
+ * @returns The net PnL in USD, or undefined when either figure is missing,
93
+ * empty or not a finite number.
94
+ */
95
+ export declare function calculateNetClosedPnl({ pnl, fee, }: NetClosedPnlParams): number | undefined;
96
+ //# sourceMappingURL=closeCalculations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"closeCalculations.d.ts","sourceRoot":"","sources":["../../src/utils/closeCalculations.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAerE;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC,mEAAmE;IACnE,QAAQ,EAAE,IAAI,CACZ,QAAQ,EACR,MAAM,GAAG,YAAY,GAAG,YAAY,GAAG,eAAe,CACvD,GAAG;QACF,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,CAAC;KAC9C,CAAC;IACF;;;;;OAKG;IACH,UAAU,EAAE,iBAAiB,CAAC;IAC9B;;;OAGG;IACH,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC;IAC3B;;;OAGG;IACH,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACnC;;;;;OAKG;IACH,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;CAC7B,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC,oFAAoF;IACpF,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,0DAA0D;IAC1D,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,2DAA2D;IAC3D,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;IACxB;;;;;OAKG;IACH,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;CAC7B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACtB,8CAA8C;IAC9C,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;CACvB,CAAC;AAgDF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,QAAQ,EACR,UAAU,EACV,SAAS,EACT,KAAK,EACL,OAAO,GACR,EAAE,0BAA0B,GAAG,oBAAoB,CAiDnD;AAED;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CAAC,EACpC,GAAG,EACH,GAAG,GACJ,EAAE,kBAAkB,GAAG,MAAM,GAAG,SAAS,CAMzC"}
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Close-position figures shared by Mobile, Extension and Terminal: the cash a
3
+ * close returns ("You'll receive") and a fill's closed PnL net of its fee.
4
+ */
5
+ import { BigNumber } from 'bignumber.js';
6
+ import { CLOSE_POSITION_CONFIG } from '../constants/perpsConfig.js';
7
+ /**
8
+ * Whether a provider's isolated `Position.marginUsed` is the collateral
9
+ * backing the position. Hyperliquid's is, with the unrealized PnL at mark
10
+ * included. Lighter's is the initial margin the position requires at its
11
+ * current value; its allocated collateral is not on `Position`, so the margin
12
+ * a Lighter isolated close returns is unknown. Cross `marginUsed` is taken as
13
+ * reported and never holds the unrealized PnL.
14
+ */
15
+ const ISOLATED_MARGIN_USED_IS_COLLATERAL = {
16
+ hyperliquid: true,
17
+ lighter: false,
18
+ };
19
+ function toDecimal(value) {
20
+ if (value === undefined) {
21
+ return undefined;
22
+ }
23
+ const decimal = new BigNumber(value);
24
+ return decimal.isFinite() ? decimal : undefined;
25
+ }
26
+ function toPositiveDecimal(value) {
27
+ const decimal = toDecimal(value);
28
+ return decimal?.isGreaterThan(0) ? decimal : undefined;
29
+ }
30
+ /**
31
+ * The unrealized PnL the position's margin holds: all of it for isolated
32
+ * margin that is the position's collateral, none for cross margin.
33
+ *
34
+ * @param position - The position being closed.
35
+ * @param providerId - Provider holding the position.
36
+ * @returns The held PnL, or undefined when it or the collateral is unknown.
37
+ */
38
+ function heldUnrealizedPnl(position, providerId) {
39
+ if (position.leverage.type !== 'isolated') {
40
+ return new BigNumber(0);
41
+ }
42
+ if (!Object.hasOwn(ISOLATED_MARGIN_USED_IS_COLLATERAL, providerId) ||
43
+ !ISOLATED_MARGIN_USED_IS_COLLATERAL[providerId]) {
44
+ return undefined;
45
+ }
46
+ return toDecimal(position.unrealizedPnl);
47
+ }
48
+ function roundUsd(value) {
49
+ return value.decimalPlaces(CLOSE_POSITION_CONFIG.UsdDecimalPlaces, BigNumber.ROUND_HALF_UP);
50
+ }
51
+ /**
52
+ * Estimate the cash a close returns: the closed share of the position's
53
+ * backing margin, plus the PnL realized at the close price, minus the fee.
54
+ *
55
+ * Backing margin is `marginUsed`, less the unrealized PnL for Hyperliquid
56
+ * isolated margin, which holds it. Cross margin is taken as reported. Lighter
57
+ * isolated `marginUsed` is required margin, not the allocated collateral, so
58
+ * its margin returned and receive are undefined. The realized PnL replaces the
59
+ * mark-price PnL, so a limit close is quoted at its limit price. A close is
60
+ * reduce-only, so a `closeSize` above the position size closes the whole
61
+ * position.
62
+ *
63
+ * @param params - The close inputs.
64
+ * @param params.position - The position being closed.
65
+ * @param params.providerId - Provider holding the position.
66
+ * @param params.closeSize - Unsigned size to close, in base units.
67
+ * @param params.price - Price the close executes at.
68
+ * @param params.feeRate - Total fee rate for the close, as a decimal.
69
+ * @returns The estimate; a figure is undefined while an input it needs is
70
+ * missing or unusable.
71
+ */
72
+ export function estimateCloseReceive({ position, providerId, closeSize, price, feeRate, }) {
73
+ const size = toDecimal(position.size);
74
+ const positionSize = size?.isZero() ? undefined : size;
75
+ const requested = toPositiveDecimal(closeSize);
76
+ const closing = requested !== undefined && positionSize !== undefined
77
+ ? BigNumber.min(requested, positionSize.abs())
78
+ : requested;
79
+ const closePrice = toPositiveDecimal(price);
80
+ const entryPrice = toPositiveDecimal(position.entryPrice);
81
+ const rate = toDecimal(feeRate);
82
+ const marginUsed = toDecimal(position.marginUsed);
83
+ const heldPnl = heldUnrealizedPnl(position, providerId);
84
+ const marginReturned = marginUsed !== undefined &&
85
+ heldPnl !== undefined &&
86
+ positionSize !== undefined &&
87
+ closing !== undefined
88
+ ? marginUsed.minus(heldPnl).times(closing).div(positionSize.abs())
89
+ : undefined;
90
+ const realizedPnl = positionSize !== undefined &&
91
+ closing !== undefined &&
92
+ closePrice !== undefined &&
93
+ entryPrice !== undefined
94
+ ? (positionSize.isNegative()
95
+ ? entryPrice.minus(closePrice)
96
+ : closePrice.minus(entryPrice)).times(closing)
97
+ : undefined;
98
+ const fee = closing !== undefined && closePrice !== undefined && rate !== undefined
99
+ ? closing.times(closePrice).times(rate)
100
+ : undefined;
101
+ const receive = marginReturned !== undefined &&
102
+ realizedPnl !== undefined &&
103
+ fee !== undefined
104
+ ? roundUsd(marginReturned.plus(realizedPnl)).minus(roundUsd(fee))
105
+ : undefined;
106
+ return {
107
+ marginReturned: marginReturned?.toNumber(),
108
+ realizedPnl: realizedPnl?.toNumber(),
109
+ fee: fee?.toNumber(),
110
+ receive: receive?.toNumber(),
111
+ };
112
+ }
113
+ /**
114
+ * A fill's closed PnL net of its fee: the venue's realized PnL less the fee
115
+ * paid on the fill.
116
+ *
117
+ * @param params - The fill figures.
118
+ * @param params.pnl - Realized PnL the venue reported.
119
+ * @param params.fee - Fee paid on the fill.
120
+ * @returns The net PnL in USD, or undefined when either figure is missing,
121
+ * empty or not a finite number.
122
+ */
123
+ export function calculateNetClosedPnl({ pnl, fee, }) {
124
+ const gross = toDecimal(pnl);
125
+ const cost = toDecimal(fee);
126
+ return gross === undefined || cost === undefined
127
+ ? undefined
128
+ : gross.minus(cost).toNumber();
129
+ }
130
+ //# sourceMappingURL=closeCalculations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"closeCalculations.js","sourceRoot":"","sources":["../../src/utils/closeCalculations.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAGpE;;;;;;;GAOG;AACH,MAAM,kCAAkC,GAAuC;IAC7E,WAAW,EAAE,IAAI;IACjB,OAAO,EAAE,KAA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,KAAK,CAAC,OAAO,CAAC;QAClB,CAAC,CAAC,SAAS,CAAC;IAChB,MAAM,GAAG,GACP,OAAO,KAAK,SAAS,IAAI,UAAU,KAAK,SAAS,IAAI,IAAI,KAAK,SAAS;QACrE,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC;QACvC,CAAC,CAAC,SAAS,CAAC;IAChB,MAAM,OAAO,GACX,cAAc,KAAK,SAAS;QAC5B,WAAW,KAAK,SAAS;QACzB,GAAG,KAAK,SAAS;QACf,CAAC,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QACjE,CAAC,CAAC,SAAS,CAAC;IAEhB,OAAO;QACL,cAAc,EAAE,cAAc,EAAE,QAAQ,EAAE;QAC1C,WAAW,EAAE,WAAW,EAAE,QAAQ,EAAE;QACpC,GAAG,EAAE,GAAG,EAAE,QAAQ,EAAE;QACpB,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE;KAC7B,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,qBAAqB,CAAC,EACpC,GAAG,EACH,GAAG,GACgB;IACnB,MAAM,KAAK,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,MAAM,IAAI,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;IAC5B,OAAO,KAAK,KAAK,SAAS,IAAI,IAAI,KAAK,SAAS;QAC9C,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Close-position figures shared by Mobile, Extension and Terminal: the cash a\n * close returns (\"You'll receive\") and a fill's closed PnL net of its fee.\n */\nimport { BigNumber } from 'bignumber.js';\n\nimport { CLOSE_POSITION_CONFIG } from '../constants/perpsConfig.js';\nimport type { PerpsProviderType, Position } from '../types/index.js';\n\n/**\n * Whether a provider's isolated `Position.marginUsed` is the collateral\n * backing the position. Hyperliquid's is, with the unrealized PnL at mark\n * included. Lighter's is the initial margin the position requires at its\n * current value; its allocated collateral is not on `Position`, so the margin\n * a Lighter isolated close returns is unknown. Cross `marginUsed` is taken as\n * reported and never holds the unrealized PnL.\n */\nconst ISOLATED_MARGIN_USED_IS_COLLATERAL: Record<PerpsProviderType, boolean> = {\n hyperliquid: true,\n lighter: false,\n};\n\n/**\n * Inputs to {@link estimateCloseReceive}.\n */\nexport type CloseReceiveEstimateParams = {\n /** The position being closed; a `Position` can be passed as-is. */\n position: Pick<\n Position,\n 'size' | 'entryPrice' | 'marginUsed' | 'unrealizedPnl'\n > & {\n leverage: Pick<Position['leverage'], 'type'>;\n };\n /**\n * Provider holding the position. It decides whether isolated `marginUsed`\n * is the position's collateral; for Lighter or an unknown provider,\n * isolated margin returned is undefined. `Position.providerId` is only set\n * under aggregation, so pass the provider explicitly.\n */\n providerId: PerpsProviderType;\n /**\n * Size to close in base units, unsigned: the whole position or part of it.\n * A size above the position size closes the whole position.\n */\n closeSize: number | string;\n /**\n * Price the close executes at: the limit price of a limit close, else the\n * live price. Undefined until known.\n */\n price: number | string | undefined;\n /**\n * Total fee rate for the close as a decimal (0.00145 = 0.145%), such as\n * `FeeCalculationResult.feeRate` from `calculateFees` for this close, which\n * already applies the maker or taker rate and any fee discount. Undefined\n * until quoted.\n */\n feeRate: number | undefined;\n};\n\n/**\n * The cash a close returns, in USD. Each figure is undefined while an input it\n * needs is missing or unusable; none falls back to 0.\n */\nexport type CloseReceiveEstimate = {\n /** The closed share of the margin backing the position, unrealized PnL excluded. */\n marginReturned: number | undefined;\n /** PnL realized on the closed size at the close price. */\n realizedPnl: number | undefined;\n /** Fee on the closed notional at the supplied fee rate. */\n fee: number | undefined;\n /**\n * `marginReturned + realizedPnl`, less `fee`, each of the two rounded first\n * to `CLOSE_POSITION_CONFIG.UsdDecimalPlaces` decimals, half away from zero.\n * A margin row that includes the PnL and a fee row, shown at that rounding,\n * add up to it. Undefined unless all three are known.\n */\n receive: number | undefined;\n};\n\n/**\n * Inputs to {@link calculateNetClosedPnl}. An `OrderFill` can be passed as-is.\n */\nexport type NetClosedPnlParams = {\n /** Realized PnL the venue reported for the fill (`OrderFill.pnl`). */\n pnl?: number | string;\n /** Fee paid on the fill (`OrderFill.fee`). */\n fee?: number | string;\n};\n\nfunction toDecimal(value: number | string | undefined): BigNumber | undefined {\n if (value === undefined) {\n return undefined;\n }\n const decimal = new BigNumber(value);\n return decimal.isFinite() ? decimal : undefined;\n}\n\nfunction toPositiveDecimal(\n value: number | string | undefined,\n): BigNumber | undefined {\n const decimal = toDecimal(value);\n return decimal?.isGreaterThan(0) ? decimal : undefined;\n}\n\n/**\n * The unrealized PnL the position's margin holds: all of it for isolated\n * margin that is the position's collateral, none for cross margin.\n *\n * @param position - The position being closed.\n * @param providerId - Provider holding the position.\n * @returns The held PnL, or undefined when it or the collateral is unknown.\n */\nfunction heldUnrealizedPnl(\n position: CloseReceiveEstimateParams['position'],\n providerId: PerpsProviderType,\n): BigNumber | undefined {\n if (position.leverage.type !== 'isolated') {\n return new BigNumber(0);\n }\n if (\n !Object.hasOwn(ISOLATED_MARGIN_USED_IS_COLLATERAL, providerId) ||\n !ISOLATED_MARGIN_USED_IS_COLLATERAL[providerId]\n ) {\n return undefined;\n }\n return toDecimal(position.unrealizedPnl);\n}\n\nfunction roundUsd(value: BigNumber): BigNumber {\n return value.decimalPlaces(\n CLOSE_POSITION_CONFIG.UsdDecimalPlaces,\n BigNumber.ROUND_HALF_UP,\n );\n}\n\n/**\n * Estimate the cash a close returns: the closed share of the position's\n * backing margin, plus the PnL realized at the close price, minus the fee.\n *\n * Backing margin is `marginUsed`, less the unrealized PnL for Hyperliquid\n * isolated margin, which holds it. Cross margin is taken as reported. Lighter\n * isolated `marginUsed` is required margin, not the allocated collateral, so\n * its margin returned and receive are undefined. The realized PnL replaces the\n * mark-price PnL, so a limit close is quoted at its limit price. A close is\n * reduce-only, so a `closeSize` above the position size closes the whole\n * position.\n *\n * @param params - The close inputs.\n * @param params.position - The position being closed.\n * @param params.providerId - Provider holding the position.\n * @param params.closeSize - Unsigned size to close, in base units.\n * @param params.price - Price the close executes at.\n * @param params.feeRate - Total fee rate for the close, as a decimal.\n * @returns The estimate; a figure is undefined while an input it needs is\n * missing or unusable.\n */\nexport function estimateCloseReceive({\n position,\n providerId,\n closeSize,\n price,\n feeRate,\n}: CloseReceiveEstimateParams): CloseReceiveEstimate {\n const size = toDecimal(position.size);\n const positionSize = size?.isZero() ? undefined : size;\n const requested = toPositiveDecimal(closeSize);\n const closing =\n requested !== undefined && positionSize !== undefined\n ? BigNumber.min(requested, positionSize.abs())\n : requested;\n const closePrice = toPositiveDecimal(price);\n const entryPrice = toPositiveDecimal(position.entryPrice);\n const rate = toDecimal(feeRate);\n\n const marginUsed = toDecimal(position.marginUsed);\n const heldPnl = heldUnrealizedPnl(position, providerId);\n\n const marginReturned =\n marginUsed !== undefined &&\n heldPnl !== undefined &&\n positionSize !== undefined &&\n closing !== undefined\n ? marginUsed.minus(heldPnl).times(closing).div(positionSize.abs())\n : undefined;\n const realizedPnl =\n positionSize !== undefined &&\n closing !== undefined &&\n closePrice !== undefined &&\n entryPrice !== undefined\n ? (positionSize.isNegative()\n ? entryPrice.minus(closePrice)\n : closePrice.minus(entryPrice)\n ).times(closing)\n : undefined;\n const fee =\n closing !== undefined && closePrice !== undefined && rate !== undefined\n ? closing.times(closePrice).times(rate)\n : undefined;\n const receive =\n marginReturned !== undefined &&\n realizedPnl !== undefined &&\n fee !== undefined\n ? roundUsd(marginReturned.plus(realizedPnl)).minus(roundUsd(fee))\n : undefined;\n\n return {\n marginReturned: marginReturned?.toNumber(),\n realizedPnl: realizedPnl?.toNumber(),\n fee: fee?.toNumber(),\n receive: receive?.toNumber(),\n };\n}\n\n/**\n * A fill's closed PnL net of its fee: the venue's realized PnL less the fee\n * paid on the fill.\n *\n * @param params - The fill figures.\n * @param params.pnl - Realized PnL the venue reported.\n * @param params.fee - Fee paid on the fill.\n * @returns The net PnL in USD, or undefined when either figure is missing,\n * empty or not a finite number.\n */\nexport function calculateNetClosedPnl({\n pnl,\n fee,\n}: NetClosedPnlParams): number | undefined {\n const gross = toDecimal(pnl);\n const cost = toDecimal(fee);\n return gross === undefined || cost === undefined\n ? undefined\n : gross.minus(cost).toNumber();\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { PositionModifyPreviewParams, PositionModifyPreviewResult } from '../types/index.js';
1
+ import type { MarketInfo, PerpsProviderType, Position, PositionModifyPreviewParams, PositionModifyPreviewResult } from '../types/index.js';
2
2
  export type HyperLiquidMarginTier = {
3
3
  /** Inclusive notional lower bound in USD. */
4
4
  lowerBound: number;
@@ -18,6 +18,52 @@ type MaintenanceScheduleTier = {
18
18
  maintenanceMarginRate: number;
19
19
  maintenanceDeduction: number;
20
20
  };
21
+ /**
22
+ * Inputs to {@link estimateIsolatedLeverageChange}.
23
+ */
24
+ export type IsolatedLeverageChangeParams = {
25
+ /** The open position; a `Position` can be passed as-is. */
26
+ position: Pick<Position, 'size' | 'marginUsed' | 'positionValue'> & {
27
+ leverage: Pick<Position['leverage'], 'type' | 'value'>;
28
+ };
29
+ /**
30
+ * Provider holding the position. Only Hyperliquid isolated positions are
31
+ * modelled; others return undefined.
32
+ */
33
+ providerId: PerpsProviderType;
34
+ /**
35
+ * The position's market, whose `marginMode` says whether margin may leave
36
+ * it. A `MarketInfo` from `getMarkets` can be passed as-is. Undefined while
37
+ * the market is unknown, which makes every figure undefined. So does
38
+ * `onlyIsolated` without `marginMode`: Hyperliquid sends both, and the
39
+ * restriction is lost where `marginMode` was dropped.
40
+ */
41
+ market: Pick<MarketInfo, 'marginMode' | 'onlyIsolated'> | undefined;
42
+ /** Leverage the position moves to, at least 1. Undefined until chosen. */
43
+ leverage: number | undefined;
44
+ /**
45
+ * Margin tiers for the asset, as {@link resolveHyperLiquidMarginTiers}
46
+ * returns. The tier the position's notional is in caps `leverage`; tiers
47
+ * that do not cover the notional make every figure undefined. Without
48
+ * tiers the cap is not checked and the liquidation price is undefined.
49
+ */
50
+ marginTiers?: HyperLiquidMarginTier[] | null;
51
+ };
52
+ /**
53
+ * An isolated position after a leverage change with no size change.
54
+ */
55
+ export type IsolatedLeverageChange = {
56
+ /**
57
+ * Margin the change frees: the drop in initial margin, notional / current
58
+ * leverage less notional / new leverage, limited to what may leave the
59
+ * position. 0 unless leverage rises, and 0 on a strict isolated market.
60
+ */
61
+ removableMargin: number | undefined;
62
+ /** Margin afterwards, once `removableMargin` is removed. */
63
+ margin: number | undefined;
64
+ /** Liquidation price at `margin`. */
65
+ liquidationPrice: number | undefined;
66
+ };
21
67
  /**
22
68
  * Resolves the HyperLiquid margin table into preview tiers.
23
69
  *
@@ -99,21 +145,57 @@ export declare function estimateIsolatedLiquidationPriceAtTier(params: {
99
145
  positionSize: number;
100
146
  marginTiers: HyperLiquidMarginTier[] | null | undefined;
101
147
  }): number | null;
148
+ /**
149
+ * An isolated position after its leverage changes with no size change: the
150
+ * margin the change frees, and the margin and liquidation price afterwards.
151
+ *
152
+ * Hyperliquid keeps an isolated position's margin when leverage changes. On a
153
+ * rise, the change frees the drop in initial margin, notional / current
154
+ * leverage less notional / new leverage, at mark. Only margin above the
155
+ * transfer requirement may leave: the larger of the initial margin at the new
156
+ * leverage and `MARGIN_ADJUSTMENT_CONFIG.MarginRemovalSafetyBuffer` of
157
+ * notional, plus 1% of notional held back for the mark moving. Margin added
158
+ * on top of the initial margin and unrealized profit stay. `margin` assumes
159
+ * `removableMargin` is removed. A strict isolated market prohibits removing
160
+ * margin from an open position, so nothing is removable there and `margin`
161
+ * is the margin held. A fall frees nothing, and the venue rejects one the
162
+ * margin cannot cover.
163
+ *
164
+ * @param params - The position, provider, market, new leverage and margin
165
+ * tiers.
166
+ * @param params.position - The open position.
167
+ * @param params.providerId - Provider holding the position.
168
+ * @param params.market - The position's market, which says whether margin may
169
+ * leave it.
170
+ * @param params.leverage - Leverage the position moves to.
171
+ * @param params.marginTiers - Margin tiers for the asset, which cap the
172
+ * leverage and set the maintenance rate.
173
+ * @returns The change. Every figure is undefined for cross margin, a provider
174
+ * other than Hyperliquid, an unknown market or margin mode, a leverage above
175
+ * the max leverage of the margin tier the position's notional is in, a fall
176
+ * the margin cannot cover, or a missing or unusable input. Without margin
177
+ * tiers the leverage limit is not checked and the liquidation price is
178
+ * undefined.
179
+ */
180
+ export declare function estimateIsolatedLeverageChange({ position, providerId, market, leverage, marginTiers, }: IsolatedLeverageChangeParams): IsolatedLeverageChange;
102
181
  /**
103
182
  * Projects the isolated position that would remain after a proposed order.
104
183
  *
105
- * Models HyperLiquid's isolated `updateLeverage` (the selected leverage is
106
- * applied to the whole asset before the fill) and maintenance tiers at the
107
- * resulting liquidation notional. Liquidation uses the projected mark, not
108
- * average entry, because isolated `marginUsed` is mark-based equity.
184
+ * Models HyperLiquid's isolated `updateLeverage`, which keeps the existing
185
+ * margin when the selected leverage differs; the order then margins only its
186
+ * own size at the selected leverage. The venue rejects a lower leverage that
187
+ * the existing margin cannot cover, so margin and liquidation are unavailable
188
+ * then. Maintenance tiers apply at the resulting liquidation notional.
189
+ * Liquidation uses the projected mark, not average entry, because isolated
190
+ * `marginUsed` is mark-based equity.
109
191
  * Cross-margin positions return `{ status: 'unsupported', reason: 'cross_margin' }`.
110
192
  *
111
193
  * `price` is the fill or resting-limit price the caller expects. A marketable
112
194
  * order should pass its execution price; a limit should pass the limit. The
113
195
  * preview does not distinguish order types itself, does not model whether a
114
196
  * resting limit would fill, and treats scale/TWAP/chase as one aggregated fill.
115
- * Decrease margin is the remaining isolated collateral after leverage
116
- * reallocation; close fees and realized PnL settle to the account, not the
197
+ * Decrease margin is the remaining share of the isolated collateral after the
198
+ * leverage change; close fees and realized PnL settle to the account, not the
117
199
  * leftover margin.
118
200
  *
119
201
  * @param params - Live isolated position, proposed order, and optional tiers.
@@ -1 +1 @@
1
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