@metamask-previews/perps-controller 25.0.0-preview-74f76ac55 → 25.0.0-preview-a7bdec3
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.
- package/CHANGELOG.md +40 -0
- package/dist/constants/eventNames.d.ts +32 -0
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +38 -0
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.ts +4 -0
- package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
- package/dist/constants/hyperLiquidConfig.js +2 -0
- package/dist/constants/hyperLiquidConfig.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +25 -0
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +26 -0
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/index.d.ts +13 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -6
- package/dist/index.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +4 -10
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +10 -0
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/types/index.d.ts +16 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/accountUtils.d.ts +10 -0
- package/dist/utils/accountUtils.d.ts.map +1 -1
- package/dist/utils/accountUtils.js +17 -0
- package/dist/utils/accountUtils.js.map +1 -1
- package/dist/utils/closeCalculations.d.ts +41 -0
- package/dist/utils/closeCalculations.d.ts.map +1 -1
- package/dist/utils/closeCalculations.js +44 -0
- package/dist/utils/closeCalculations.js.map +1 -1
- package/dist/utils/feeAmounts.d.ts +55 -0
- package/dist/utils/feeAmounts.d.ts.map +1 -0
- package/dist/utils/feeAmounts.js +92 -0
- package/dist/utils/feeAmounts.js.map +1 -0
- package/dist/utils/hyperLiquidScaleOrders.d.ts +73 -0
- package/dist/utils/hyperLiquidScaleOrders.d.ts.map +1 -0
- package/dist/utils/hyperLiquidScaleOrders.js +195 -0
- package/dist/utils/hyperLiquidScaleOrders.js.map +1 -0
- package/dist/utils/index.d.ts +13 -4
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +9 -2
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/orderBookGrouping.d.ts +62 -1
- package/dist/utils/orderBookGrouping.d.ts.map +1 -1
- package/dist/utils/orderBookGrouping.js +96 -1
- package/dist/utils/orderBookGrouping.js.map +1 -1
- package/dist/utils/orderBookSlippage.d.ts +39 -0
- package/dist/utils/orderBookSlippage.d.ts.map +1 -0
- package/dist/utils/orderBookSlippage.js +72 -0
- package/dist/utils/orderBookSlippage.js.map +1 -0
- package/dist/utils/orderFills.d.ts +24 -0
- package/dist/utils/orderFills.d.ts.map +1 -0
- package/dist/utils/orderFills.js +71 -0
- package/dist/utils/orderFills.js.map +1 -0
- package/dist/utils/positionCalculations.d.ts +22 -0
- package/dist/utils/positionCalculations.d.ts.map +1 -0
- package/dist/utils/positionCalculations.js +54 -0
- package/dist/utils/positionCalculations.js.map +1 -0
- package/dist/utils/priceDeviation.d.ts +27 -0
- package/dist/utils/priceDeviation.d.ts.map +1 -0
- package/dist/utils/priceDeviation.js +58 -0
- package/dist/utils/priceDeviation.js.map +1 -0
- package/dist/utils/pricePrecision.d.ts +20 -0
- package/dist/utils/pricePrecision.d.ts.map +1 -0
- package/dist/utils/pricePrecision.js +52 -0
- package/dist/utils/pricePrecision.js.map +1 -0
- package/dist/utils/tpslCalculations.d.ts +22 -0
- package/dist/utils/tpslCalculations.d.ts.map +1 -1
- package/dist/utils/tpslCalculations.js +29 -0
- package/dist/utils/tpslCalculations.js.map +1 -1
- package/docs/client-contract.md +31 -8
- package/docs/contracts/events.md +33 -31
- package/docs/venues/lighter/capabilities.md +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { ScaleLadderSizing } from '../types/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Scale ladder prices on Hyperliquid's price grid: the evenly spaced ladder
|
|
4
|
+
* from `computeScalePriceLadder`, each rung rounded with
|
|
5
|
+
* `formatHyperLiquidPrice`.
|
|
6
|
+
*
|
|
7
|
+
* @param params - Ladder parameters.
|
|
8
|
+
* @param params.minPrice - Lowest raw price.
|
|
9
|
+
* @param params.maxPrice - Highest raw price.
|
|
10
|
+
* @param params.count - Number of rungs.
|
|
11
|
+
* @param params.szDecimals - The market's size decimals, which set its price grid.
|
|
12
|
+
* @returns The rung prices, ascending.
|
|
13
|
+
* @throws `ORDER_SCALE_RANGE_INVALID` when two rungs round to the same price,
|
|
14
|
+
* and the `computeScalePriceLadder` errors for an invalid count or range.
|
|
15
|
+
*/
|
|
16
|
+
export declare function normalizeHyperLiquidScalePriceLadder(params: {
|
|
17
|
+
minPrice: number;
|
|
18
|
+
maxPrice: number;
|
|
19
|
+
count: number;
|
|
20
|
+
szDecimals: number;
|
|
21
|
+
}): string[];
|
|
22
|
+
/**
|
|
23
|
+
* Size a Hyperliquid scale ladder.
|
|
24
|
+
*
|
|
25
|
+
* An exact `size` must sit on the size grid. It is split across the rungs,
|
|
26
|
+
* and the sizing fails unless the rungs add up to exactly `size`: the split
|
|
27
|
+
* runs on a float, which cannot hold every step of a very large size.
|
|
28
|
+
*
|
|
29
|
+
* A `usdAmount` is a target the ladder meets, as Mobile's Pro order form sizes
|
|
30
|
+
* it. The first guess is the amount over the skew-weighted average price,
|
|
31
|
+
* rounded up to the size grid. When that total splits:
|
|
32
|
+
* - it is the result if its rungs reach the target;
|
|
33
|
+
* - otherwise the result is the smallest larger total that reaches it, found
|
|
34
|
+
* by a doubling then binary search. A candidate that cannot be split counts
|
|
35
|
+
* as falling short.
|
|
36
|
+
*
|
|
37
|
+
* When the first guess cannot be split (a skewed rung rounds to zero), the
|
|
38
|
+
* result is the smallest smaller total that splits and reaches the target,
|
|
39
|
+
* scanning up from the least total that could reach it, within the 10,000
|
|
40
|
+
* size steps below the first guess. Larger totals are not tried, so the
|
|
41
|
+
* ladder never grows past the first guess; with no such total the sizing
|
|
42
|
+
* fails, as Mobile's does. A first guess beyond the safe-integer range of size
|
|
43
|
+
* steps fails at once.
|
|
44
|
+
*
|
|
45
|
+
* The notional can exceed `usdAmount`, unlike `sizeScaleLadder`, which keeps
|
|
46
|
+
* a budget as a ceiling. Rung minimums are not checked here; compare each
|
|
47
|
+
* rung's notional with the venue minimum (`validateScaleOrder`).
|
|
48
|
+
*
|
|
49
|
+
* @param params - Sizing parameters.
|
|
50
|
+
* @param params.prices - Rung prices from {@link normalizeHyperLiquidScalePriceLadder}.
|
|
51
|
+
* @param params.sizeDecimals - The market's size decimals.
|
|
52
|
+
* @param params.skew - Rung-size weight of the last rung relative to the
|
|
53
|
+
* first. Defaults to 1 (even).
|
|
54
|
+
* @param params.size - Exact total size in base units, on the size grid.
|
|
55
|
+
* @param params.usdAmount - Target order value in USD.
|
|
56
|
+
* @returns The rung sizes, total size and total notional.
|
|
57
|
+
* @throws `ORDER_SCALE_SIZE_CONSERVATION_FAILED` for an exact size off the
|
|
58
|
+
* size grid or one the split cannot preserve; `ORDER_SCALE_SIZE_TOO_SMALL` when no total under these rules
|
|
59
|
+
* reaches the target;
|
|
60
|
+
* and the `splitScaleSizes` errors for an exact size that cannot be split.
|
|
61
|
+
*/
|
|
62
|
+
export declare function sizeHyperLiquidScaleLadder(params: {
|
|
63
|
+
prices: readonly string[];
|
|
64
|
+
sizeDecimals: number;
|
|
65
|
+
skew?: number;
|
|
66
|
+
} & ({
|
|
67
|
+
size: string;
|
|
68
|
+
usdAmount?: never;
|
|
69
|
+
} | {
|
|
70
|
+
usdAmount: string;
|
|
71
|
+
size?: never;
|
|
72
|
+
})): ScaleLadderSizing;
|
|
73
|
+
//# sourceMappingURL=hyperLiquidScaleOrders.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hyperLiquidScaleOrders.d.ts","sourceRoot":"","sources":["../../src/utils/hyperLiquidScaleOrders.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAoB3D;;;;;;;;;;;;;GAaG;AACH,wBAAgB,oCAAoC,CAAC,MAAM,EAAE;IAC3D,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;CACpB,GAAG,MAAM,EAAE,CASX;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE;IACN,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B,YAAY,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,GAAG,CACA;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,KAAK,CAAA;CAAE,GACnC;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,KAAK,CAAA;CAAE,CACtC,GACA,iBAAiB,CAqJnB"}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { BigNumber } from 'bignumber.js';
|
|
2
|
+
import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
|
|
3
|
+
import { formatHyperLiquidPrice } from './hyperLiquidAdapter.js';
|
|
4
|
+
import { computeScalePriceLadder, splitScaleSizes, } from './orderCalculations.js';
|
|
5
|
+
/**
|
|
6
|
+
* Steps each search stage may take: a binary search over the safe-integer
|
|
7
|
+
* range of size units needs at most 53 halvings.
|
|
8
|
+
*/
|
|
9
|
+
const SIZE_SEARCH_MAX_STEPS = Math.ceil(Math.log2(Number.MAX_SAFE_INTEGER));
|
|
10
|
+
/**
|
|
11
|
+
* Most totals the starved-rung fallback tries, counting down from the first
|
|
12
|
+
* guess. A rung only starves while the total is small, so a feasible total is
|
|
13
|
+
* normally a few steps away; the cap keeps a synchronous preview bounded.
|
|
14
|
+
*/
|
|
15
|
+
const SPLIT_FALLBACK_MAX_CANDIDATES = 10_000;
|
|
16
|
+
/**
|
|
17
|
+
* Scale ladder prices on Hyperliquid's price grid: the evenly spaced ladder
|
|
18
|
+
* from `computeScalePriceLadder`, each rung rounded with
|
|
19
|
+
* `formatHyperLiquidPrice`.
|
|
20
|
+
*
|
|
21
|
+
* @param params - Ladder parameters.
|
|
22
|
+
* @param params.minPrice - Lowest raw price.
|
|
23
|
+
* @param params.maxPrice - Highest raw price.
|
|
24
|
+
* @param params.count - Number of rungs.
|
|
25
|
+
* @param params.szDecimals - The market's size decimals, which set its price grid.
|
|
26
|
+
* @returns The rung prices, ascending.
|
|
27
|
+
* @throws `ORDER_SCALE_RANGE_INVALID` when two rungs round to the same price,
|
|
28
|
+
* and the `computeScalePriceLadder` errors for an invalid count or range.
|
|
29
|
+
*/
|
|
30
|
+
export function normalizeHyperLiquidScalePriceLadder(params) {
|
|
31
|
+
const { szDecimals, ...ladderParams } = params;
|
|
32
|
+
const prices = computeScalePriceLadder(ladderParams).map((price) => formatHyperLiquidPrice({ price, szDecimals }));
|
|
33
|
+
if (new Set(prices).size !== prices.length) {
|
|
34
|
+
throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);
|
|
35
|
+
}
|
|
36
|
+
return prices;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Size a Hyperliquid scale ladder.
|
|
40
|
+
*
|
|
41
|
+
* An exact `size` must sit on the size grid. It is split across the rungs,
|
|
42
|
+
* and the sizing fails unless the rungs add up to exactly `size`: the split
|
|
43
|
+
* runs on a float, which cannot hold every step of a very large size.
|
|
44
|
+
*
|
|
45
|
+
* A `usdAmount` is a target the ladder meets, as Mobile's Pro order form sizes
|
|
46
|
+
* it. The first guess is the amount over the skew-weighted average price,
|
|
47
|
+
* rounded up to the size grid. When that total splits:
|
|
48
|
+
* - it is the result if its rungs reach the target;
|
|
49
|
+
* - otherwise the result is the smallest larger total that reaches it, found
|
|
50
|
+
* by a doubling then binary search. A candidate that cannot be split counts
|
|
51
|
+
* as falling short.
|
|
52
|
+
*
|
|
53
|
+
* When the first guess cannot be split (a skewed rung rounds to zero), the
|
|
54
|
+
* result is the smallest smaller total that splits and reaches the target,
|
|
55
|
+
* scanning up from the least total that could reach it, within the 10,000
|
|
56
|
+
* size steps below the first guess. Larger totals are not tried, so the
|
|
57
|
+
* ladder never grows past the first guess; with no such total the sizing
|
|
58
|
+
* fails, as Mobile's does. A first guess beyond the safe-integer range of size
|
|
59
|
+
* steps fails at once.
|
|
60
|
+
*
|
|
61
|
+
* The notional can exceed `usdAmount`, unlike `sizeScaleLadder`, which keeps
|
|
62
|
+
* a budget as a ceiling. Rung minimums are not checked here; compare each
|
|
63
|
+
* rung's notional with the venue minimum (`validateScaleOrder`).
|
|
64
|
+
*
|
|
65
|
+
* @param params - Sizing parameters.
|
|
66
|
+
* @param params.prices - Rung prices from {@link normalizeHyperLiquidScalePriceLadder}.
|
|
67
|
+
* @param params.sizeDecimals - The market's size decimals.
|
|
68
|
+
* @param params.skew - Rung-size weight of the last rung relative to the
|
|
69
|
+
* first. Defaults to 1 (even).
|
|
70
|
+
* @param params.size - Exact total size in base units, on the size grid.
|
|
71
|
+
* @param params.usdAmount - Target order value in USD.
|
|
72
|
+
* @returns The rung sizes, total size and total notional.
|
|
73
|
+
* @throws `ORDER_SCALE_SIZE_CONSERVATION_FAILED` for an exact size off the
|
|
74
|
+
* size grid or one the split cannot preserve; `ORDER_SCALE_SIZE_TOO_SMALL` when no total under these rules
|
|
75
|
+
* reaches the target;
|
|
76
|
+
* and the `splitScaleSizes` errors for an exact size that cannot be split.
|
|
77
|
+
*/
|
|
78
|
+
export function sizeHyperLiquidScaleLadder(params) {
|
|
79
|
+
const { prices, sizeDecimals, skew = 1 } = params;
|
|
80
|
+
const count = prices.length;
|
|
81
|
+
const unit = new BigNumber(10).pow(sizeDecimals);
|
|
82
|
+
const toSize = (units) => units.dividedBy(unit).toFixed(sizeDecimals);
|
|
83
|
+
const split = (totalSize) => splitScaleSizes({
|
|
84
|
+
totalSize: Number(totalSize),
|
|
85
|
+
count,
|
|
86
|
+
szDecimals: sizeDecimals,
|
|
87
|
+
skew,
|
|
88
|
+
});
|
|
89
|
+
// A total whose rungs cannot all get a size step has no ladder.
|
|
90
|
+
const trySplit = (totalSize) => {
|
|
91
|
+
try {
|
|
92
|
+
return split(totalSize);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (error instanceof Error &&
|
|
96
|
+
error.message === PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL) {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
const value = (sizes) => sizes.reduce((total, size, index) => total.plus(new BigNumber(size).times(prices[index])), new BigNumber(0));
|
|
103
|
+
const result = (sizes) => ({
|
|
104
|
+
sizes,
|
|
105
|
+
totalSize: BigNumber.sum(...sizes).toFixed(),
|
|
106
|
+
totalNotional: value(sizes).toFixed(),
|
|
107
|
+
});
|
|
108
|
+
if (params.usdAmount === undefined) {
|
|
109
|
+
const total = new BigNumber(params.size);
|
|
110
|
+
if (!total.times(unit).isInteger()) {
|
|
111
|
+
throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_CONSERVATION_FAILED);
|
|
112
|
+
}
|
|
113
|
+
// The split works on a float, which can drop a grid step from a large
|
|
114
|
+
// size: the rungs must still add up to exactly what was asked for.
|
|
115
|
+
const sizes = split(params.size);
|
|
116
|
+
if (!BigNumber.sum(...sizes).eq(total)) {
|
|
117
|
+
throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_CONSERVATION_FAILED);
|
|
118
|
+
}
|
|
119
|
+
return result(sizes);
|
|
120
|
+
}
|
|
121
|
+
const target = new BigNumber(params.usdAmount);
|
|
122
|
+
const reaches = (sizes) => sizes !== undefined && value(sizes).gte(target);
|
|
123
|
+
const weights = prices.map((_price, index) => 1 + ((skew - 1) * index) / (count - 1));
|
|
124
|
+
const weightTotal = BigNumber.sum(...weights);
|
|
125
|
+
const weightedAveragePrice = prices
|
|
126
|
+
.reduce((total, price, index) => total.plus(new BigNumber(price).times(weights[index])), new BigNumber(0))
|
|
127
|
+
.dividedBy(weightTotal);
|
|
128
|
+
const initialSize = target
|
|
129
|
+
.dividedBy(weightedAveragePrice)
|
|
130
|
+
.decimalPlaces(sizeDecimals, BigNumber.ROUND_CEIL)
|
|
131
|
+
.toFixed(sizeDecimals);
|
|
132
|
+
const initialUnits = new BigNumber(initialSize)
|
|
133
|
+
.times(unit)
|
|
134
|
+
.integerValue(BigNumber.ROUND_HALF_UP);
|
|
135
|
+
// No total at or past the safe-integer range can be split.
|
|
136
|
+
if (initialUnits.gt(Number.MAX_SAFE_INTEGER)) {
|
|
137
|
+
throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);
|
|
138
|
+
}
|
|
139
|
+
const initialSizes = trySplit(initialSize);
|
|
140
|
+
if (initialSizes === undefined) {
|
|
141
|
+
// Below this many units even every rung at the top price falls short.
|
|
142
|
+
const highestPrice = BigNumber.max(...prices);
|
|
143
|
+
const leastUnits = BigNumber.max(count, target
|
|
144
|
+
.dividedBy(highestPrice)
|
|
145
|
+
.times(unit)
|
|
146
|
+
.integerValue(BigNumber.ROUND_CEIL), initialUnits.minus(SPLIT_FALLBACK_MAX_CANDIDATES));
|
|
147
|
+
for (let units = leastUnits; units.lt(initialUnits); units = units.plus(1)) {
|
|
148
|
+
const sizes = trySplit(toSize(units));
|
|
149
|
+
if (reaches(sizes)) {
|
|
150
|
+
return result(sizes);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);
|
|
154
|
+
}
|
|
155
|
+
if (reaches(initialSizes)) {
|
|
156
|
+
return result(initialSizes);
|
|
157
|
+
}
|
|
158
|
+
let lowerUnits = initialUnits;
|
|
159
|
+
let upper;
|
|
160
|
+
// Bracket a total that reaches the target in doubling steps, so a steep
|
|
161
|
+
// skew does not walk one size step at a time.
|
|
162
|
+
let step = new BigNumber(1);
|
|
163
|
+
for (let attempt = 0; attempt < SIZE_SEARCH_MAX_STEPS; attempt += 1) {
|
|
164
|
+
const units = initialUnits.plus(step);
|
|
165
|
+
if (units.gt(Number.MAX_SAFE_INTEGER)) {
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
const sizes = trySplit(toSize(units));
|
|
169
|
+
if (reaches(sizes)) {
|
|
170
|
+
upper = { units, sizes };
|
|
171
|
+
break;
|
|
172
|
+
}
|
|
173
|
+
lowerUnits = units;
|
|
174
|
+
step = step.times(2);
|
|
175
|
+
}
|
|
176
|
+
if (upper === undefined) {
|
|
177
|
+
throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);
|
|
178
|
+
}
|
|
179
|
+
// Narrow the bracket to the smallest total that reaches the target.
|
|
180
|
+
for (let attempt = 0; attempt < SIZE_SEARCH_MAX_STEPS && upper.units.minus(lowerUnits).gt(1); attempt += 1) {
|
|
181
|
+
const units = lowerUnits
|
|
182
|
+
.plus(upper.units)
|
|
183
|
+
.dividedBy(2)
|
|
184
|
+
.integerValue(BigNumber.ROUND_FLOOR);
|
|
185
|
+
const sizes = trySplit(toSize(units));
|
|
186
|
+
if (reaches(sizes)) {
|
|
187
|
+
upper = { units, sizes };
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
lowerUnits = units;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return result(upper.sizes);
|
|
194
|
+
}
|
|
195
|
+
//# sourceMappingURL=hyperLiquidScaleOrders.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":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,CAAC,KAAK,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EACtE,OAAO,IAAI,CAAC,EACZ,CAAC;QACD,MAAM,KAAK,GAAG,UAAU;aACrB,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;aACjB,SAAS,CAAC,CAAC,CAAC;aACZ,YAAY,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QACvC,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QACtC,IAAI,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACnB,KAAK,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;QAC3B,CAAC;aAAM,CAAC;YACN,UAAU,GAAG,KAAK,CAAC;QACrB,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type { ScaleLadderSizing } from '../types/index.js';\nimport { formatHyperLiquidPrice } from './hyperLiquidAdapter.js';\nimport {\n computeScalePriceLadder,\n splitScaleSizes,\n} from './orderCalculations.js';\n\n/**\n * Steps each search stage may take: a binary search over the safe-integer\n * range of size units needs at most 53 halvings.\n */\nconst SIZE_SEARCH_MAX_STEPS = Math.ceil(Math.log2(Number.MAX_SAFE_INTEGER));\n\n/**\n * Most totals the starved-rung fallback tries, counting down from the first\n * guess. A rung only starves while the total is small, so a feasible total is\n * normally a few steps away; the cap keeps a synchronous preview bounded.\n */\nconst SPLIT_FALLBACK_MAX_CANDIDATES = 10_000;\n\n/**\n * Scale ladder prices on Hyperliquid's price grid: the evenly spaced ladder\n * from `computeScalePriceLadder`, each rung rounded with\n * `formatHyperLiquidPrice`.\n *\n * @param params - Ladder parameters.\n * @param params.minPrice - Lowest raw price.\n * @param params.maxPrice - Highest raw price.\n * @param params.count - Number of rungs.\n * @param params.szDecimals - The market's size decimals, which set its price grid.\n * @returns The rung prices, ascending.\n * @throws `ORDER_SCALE_RANGE_INVALID` when two rungs round to the same price,\n * and the `computeScalePriceLadder` errors for an invalid count or range.\n */\nexport function normalizeHyperLiquidScalePriceLadder(params: {\n minPrice: number;\n maxPrice: number;\n count: number;\n szDecimals: number;\n}): string[] {\n const { szDecimals, ...ladderParams } = params;\n const prices = computeScalePriceLadder(ladderParams).map((price) =>\n formatHyperLiquidPrice({ price, szDecimals }),\n );\n if (new Set(prices).size !== prices.length) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);\n }\n return prices;\n}\n\n/**\n * Size a Hyperliquid scale ladder.\n *\n * An exact `size` must sit on the size grid. It is split across the rungs,\n * and the sizing fails unless the rungs add up to exactly `size`: the split\n * runs on a float, which cannot hold every step of a very large size.\n *\n * A `usdAmount` is a target the ladder meets, as Mobile's Pro order form sizes\n * it. The first guess is the amount over the skew-weighted average price,\n * rounded up to the size grid. When that total splits:\n * - it is the result if its rungs reach the target;\n * - otherwise the result is the smallest larger total that reaches it, found\n * by a doubling then binary search. A candidate that cannot be split counts\n * as falling short.\n *\n * When the first guess cannot be split (a skewed rung rounds to zero), the\n * result is the smallest smaller total that splits and reaches the target,\n * scanning up from the least total that could reach it, within the 10,000\n * size steps below the first guess. Larger totals are not tried, so the\n * ladder never grows past the first guess; with no such total the sizing\n * fails, as Mobile's does. A first guess beyond the safe-integer range of size\n * steps fails at once.\n *\n * The notional can exceed `usdAmount`, unlike `sizeScaleLadder`, which keeps\n * a budget as a ceiling. Rung minimums are not checked here; compare each\n * rung's notional with the venue minimum (`validateScaleOrder`).\n *\n * @param params - Sizing parameters.\n * @param params.prices - Rung prices from {@link normalizeHyperLiquidScalePriceLadder}.\n * @param params.sizeDecimals - The market's size decimals.\n * @param params.skew - Rung-size weight of the last rung relative to the\n * first. Defaults to 1 (even).\n * @param params.size - Exact total size in base units, on the size grid.\n * @param params.usdAmount - Target order value in USD.\n * @returns The rung sizes, total size and total notional.\n * @throws `ORDER_SCALE_SIZE_CONSERVATION_FAILED` for an exact size off the\n * size grid or one the split cannot preserve; `ORDER_SCALE_SIZE_TOO_SMALL` when no total under these rules\n * reaches the target;\n * and the `splitScaleSizes` errors for an exact size that cannot be split.\n */\nexport function sizeHyperLiquidScaleLadder(\n params: {\n prices: readonly string[];\n sizeDecimals: number;\n skew?: number;\n } & (\n | { size: string; usdAmount?: never }\n | { usdAmount: string; size?: never }\n ),\n): ScaleLadderSizing {\n const { prices, sizeDecimals, skew = 1 } = params;\n const count = prices.length;\n const unit = new BigNumber(10).pow(sizeDecimals);\n const toSize = (units: BigNumber): string =>\n units.dividedBy(unit).toFixed(sizeDecimals);\n\n const split = (totalSize: string): string[] =>\n splitScaleSizes({\n totalSize: Number(totalSize),\n count,\n szDecimals: sizeDecimals,\n skew,\n });\n // A total whose rungs cannot all get a size step has no ladder.\n const trySplit = (totalSize: string): string[] | undefined => {\n try {\n return split(totalSize);\n } catch (error) {\n if (\n error instanceof Error &&\n error.message === PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL\n ) {\n return undefined;\n }\n throw error;\n }\n };\n const value = (sizes: readonly string[]): BigNumber =>\n sizes.reduce(\n (total, size, index) =>\n total.plus(new BigNumber(size).times(prices[index])),\n new BigNumber(0),\n );\n const result = (sizes: string[]): ScaleLadderSizing => ({\n sizes,\n totalSize: BigNumber.sum(...sizes).toFixed(),\n totalNotional: value(sizes).toFixed(),\n });\n\n if (params.usdAmount === undefined) {\n const total = new BigNumber(params.size);\n if (!total.times(unit).isInteger()) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_CONSERVATION_FAILED);\n }\n // The split works on a float, which can drop a grid step from a large\n // size: the rungs must still add up to exactly what was asked for.\n const sizes = split(params.size);\n if (!BigNumber.sum(...sizes).eq(total)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_CONSERVATION_FAILED);\n }\n return result(sizes);\n }\n\n const target = new BigNumber(params.usdAmount);\n const reaches = (sizes: string[] | undefined): sizes is string[] =>\n sizes !== undefined && value(sizes).gte(target);\n const weights = prices.map(\n (_price, index) => 1 + ((skew - 1) * index) / (count - 1),\n );\n const weightTotal = BigNumber.sum(...weights);\n const weightedAveragePrice = prices\n .reduce(\n (total, price, index) =>\n total.plus(new BigNumber(price).times(weights[index])),\n new BigNumber(0),\n )\n .dividedBy(weightTotal);\n const initialSize = target\n .dividedBy(weightedAveragePrice)\n .decimalPlaces(sizeDecimals, BigNumber.ROUND_CEIL)\n .toFixed(sizeDecimals);\n const initialUnits = new BigNumber(initialSize)\n .times(unit)\n .integerValue(BigNumber.ROUND_HALF_UP);\n // No total at or past the safe-integer range can be split.\n if (initialUnits.gt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);\n }\n const initialSizes = trySplit(initialSize);\n\n if (initialSizes === undefined) {\n // Below this many units even every rung at the top price falls short.\n const highestPrice = BigNumber.max(...prices);\n const leastUnits = BigNumber.max(\n count,\n target\n .dividedBy(highestPrice)\n .times(unit)\n .integerValue(BigNumber.ROUND_CEIL),\n initialUnits.minus(SPLIT_FALLBACK_MAX_CANDIDATES),\n );\n for (\n let units = leastUnits;\n units.lt(initialUnits);\n units = units.plus(1)\n ) {\n const sizes = trySplit(toSize(units));\n if (reaches(sizes)) {\n return result(sizes);\n }\n }\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);\n }\n if (reaches(initialSizes)) {\n return result(initialSizes);\n }\n\n let lowerUnits = initialUnits;\n let upper: { units: BigNumber; sizes: string[] } | undefined;\n\n // Bracket a total that reaches the target in doubling steps, so a steep\n // skew does not walk one size step at a time.\n let step = new BigNumber(1);\n for (let attempt = 0; attempt < SIZE_SEARCH_MAX_STEPS; attempt += 1) {\n const units = initialUnits.plus(step);\n if (units.gt(Number.MAX_SAFE_INTEGER)) {\n break;\n }\n const sizes = trySplit(toSize(units));\n if (reaches(sizes)) {\n upper = { units, sizes };\n break;\n }\n lowerUnits = units;\n step = step.times(2);\n }\n if (upper === undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);\n }\n\n // Narrow the bracket to the smallest total that reaches the target.\n for (\n let attempt = 0;\n attempt < SIZE_SEARCH_MAX_STEPS && upper.units.minus(lowerUnits).gt(1);\n attempt += 1\n ) {\n const units = lowerUnits\n .plus(upper.units)\n .dividedBy(2)\n .integerValue(BigNumber.ROUND_FLOOR);\n const sizes = trySplit(toSize(units));\n if (reaches(sizes)) {\n upper = { units, sizes };\n } else {\n lowerUnits = units;\n }\n }\n return result(upper.sizes);\n}\n"]}
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -8,9 +8,11 @@ export * from './accountUtils.js';
|
|
|
8
8
|
export * from './advancedOrderLists.js';
|
|
9
9
|
export * from './advancedOrders.js';
|
|
10
10
|
export { getBatchOperationStatus } from './batchOperationStatus.js';
|
|
11
|
-
export { estimateCloseReceive, calculateNetClosedPnl, } from './closeCalculations.js';
|
|
12
|
-
export type { CloseReceiveEstimateParams, CloseReceiveEstimate, NetClosedPnlParams, } from './closeCalculations.js';
|
|
11
|
+
export { estimateCloseReceive, calculateNetClosedPnl, calculateCloseSize, } from './closeCalculations.js';
|
|
12
|
+
export type { CloseSize, CloseSizeParams, CloseReceiveEstimateParams, CloseReceiveEstimate, NetClosedPnlParams, } from './closeCalculations.js';
|
|
13
13
|
export * from './errorUtils.js';
|
|
14
|
+
export { calculateFeeNotionalUsd, calculateUndiscountedFeeAmount, getUndiscountedFeeRate, } from './feeAmounts.js';
|
|
15
|
+
export type { FeeNotionalParams } from './feeAmounts.js';
|
|
14
16
|
export { adaptOrderToSDK, adaptPositionFromSDK, adaptOrderFromSDK, adaptPositionTriggerOrderFromSDK, adaptTpslLinkageToGrouping, adaptTriggerOrderTypeFromSDK, adaptMarketFromSDK, adaptAccountStateFromSDK, buildAssetMapping, formatHyperLiquidPrice, formatHyperLiquidSize, calculateHip3AssetId, parseAssetName, adaptHyperLiquidLedgerUpdateToUserHistoryItem, } from './hyperLiquidAdapter.js';
|
|
15
17
|
export * from './hyperLiquidOrderBookProcessor.js';
|
|
16
18
|
export * from './hyperLiquidPositionPreview.js';
|
|
@@ -21,13 +23,20 @@ export * from './idUtils.js';
|
|
|
21
23
|
export * from './marketDataTransform.js';
|
|
22
24
|
export * from './marketSearch.js';
|
|
23
25
|
export * from './marketUtils.js';
|
|
24
|
-
export { aggregateOrderBookLevels, groupOrderBook, } from './orderBookGrouping.js';
|
|
25
|
-
export type { GroupedOrderBook } from './orderBookGrouping.js';
|
|
26
|
+
export { aggregateOrderBookLevels, calculateOrderBookAggregationParams, calculateOrderBookGroupingOptions, calculateOrderBookSpread, groupOrderBook, selectDefaultOrderBookGrouping, } from './orderBookGrouping.js';
|
|
27
|
+
export type { GroupedOrderBook, OrderBookAggregationParams, OrderBookSpread, } from './orderBookGrouping.js';
|
|
28
|
+
export { estimateOrderBookSlippage } from './orderBookSlippage.js';
|
|
29
|
+
export type { OrderBookSlippageEstimate, OrderBookSlippageParams, } from './orderBookSlippage.js';
|
|
26
30
|
export * from './orderCalculations.js';
|
|
31
|
+
export { normalizeHyperLiquidScalePriceLadder, sizeHyperLiquidScaleLadder, } from './hyperLiquidScaleOrders.js';
|
|
32
|
+
export { getFillAggregationKey, getOrderFillKey } from './orderFills.js';
|
|
27
33
|
export * from './orderTypes.js';
|
|
28
34
|
export { getPerpsErrorCopy, PERPS_ERROR_COPY, PERPS_ORDER_TYPE_LABELS, } from './perpsClientCopy.js';
|
|
29
35
|
export type { PerpsErrorCopy, PerpsOrderTypeLabel } from './perpsClientCopy.js';
|
|
30
36
|
export * from './perpsDiskPersistence.js';
|
|
37
|
+
export { getPositionDirection, recomputePositionAtPrice, } from './positionCalculations.js';
|
|
38
|
+
export { getPriceDeviationBand, isPriceOutsideDeviationBand, } from './priceDeviation.js';
|
|
39
|
+
export { roundPerpsPrice } from './pricePrecision.js';
|
|
31
40
|
export * from './rewardsUtils.js';
|
|
32
41
|
export * from './significantFigures.js';
|
|
33
42
|
export * from './sortMarkets.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EACL,oBAAoB,EACpB,qBAAqB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,SAAS,EACT,eAAe,EACf,0BAA0B,EAC1B,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,OAAO,EACL,uBAAuB,EACvB,8BAA8B,EAC9B,sBAAsB,GACvB,MAAM,iBAAiB,CAAC;AACzB,YAAY,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEzD,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,gCAAgC,EAChC,0BAA0B,EAC1B,4BAA4B,EAC5B,kBAAkB,EAClB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,cAAc,EACd,6CAA6C,GAC9C,MAAM,yBAAyB,CAAC;AACjC,cAAc,oCAAoC,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kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC;AAG1B,eAAO,MAAM,cAAc,QAAO,KAAK,GAAG,MAGzC,CAAC;AACF,cAAc,sBAAsB,CAAC"}
|
package/dist/utils/index.js
CHANGED
|
@@ -8,8 +8,9 @@ export * from './accountUtils.js';
|
|
|
8
8
|
export * from './advancedOrderLists.js';
|
|
9
9
|
export * from './advancedOrders.js';
|
|
10
10
|
export { getBatchOperationStatus } from './batchOperationStatus.js';
|
|
11
|
-
export { estimateCloseReceive, calculateNetClosedPnl, } from './closeCalculations.js';
|
|
11
|
+
export { estimateCloseReceive, calculateNetClosedPnl, calculateCloseSize, } from './closeCalculations.js';
|
|
12
12
|
export * from './errorUtils.js';
|
|
13
|
+
export { calculateFeeNotionalUsd, calculateUndiscountedFeeAmount, getUndiscountedFeeRate, } from './feeAmounts.js';
|
|
13
14
|
// hyperLiquidAdapter: selective export to avoid calculatePositionSize clash with orderCalculations
|
|
14
15
|
export { adaptOrderToSDK, adaptPositionFromSDK, adaptOrderFromSDK, adaptPositionTriggerOrderFromSDK, adaptTpslLinkageToGrouping, adaptTriggerOrderTypeFromSDK, adaptMarketFromSDK, adaptAccountStateFromSDK, buildAssetMapping, formatHyperLiquidPrice, formatHyperLiquidSize, calculateHip3AssetId, parseAssetName, adaptHyperLiquidLedgerUpdateToUserHistoryItem, } from './hyperLiquidAdapter.js';
|
|
15
16
|
export * from './hyperLiquidOrderBookProcessor.js';
|
|
@@ -20,11 +21,17 @@ export * from './idUtils.js';
|
|
|
20
21
|
export * from './marketDataTransform.js';
|
|
21
22
|
export * from './marketSearch.js';
|
|
22
23
|
export * from './marketUtils.js';
|
|
23
|
-
export { aggregateOrderBookLevels, groupOrderBook, } from './orderBookGrouping.js';
|
|
24
|
+
export { aggregateOrderBookLevels, calculateOrderBookAggregationParams, calculateOrderBookGroupingOptions, calculateOrderBookSpread, groupOrderBook, selectDefaultOrderBookGrouping, } from './orderBookGrouping.js';
|
|
25
|
+
export { estimateOrderBookSlippage } from './orderBookSlippage.js';
|
|
24
26
|
export * from './orderCalculations.js';
|
|
27
|
+
export { normalizeHyperLiquidScalePriceLadder, sizeHyperLiquidScaleLadder, } from './hyperLiquidScaleOrders.js';
|
|
28
|
+
export { getFillAggregationKey, getOrderFillKey } from './orderFills.js';
|
|
25
29
|
export * from './orderTypes.js';
|
|
26
30
|
export { getPerpsErrorCopy, PERPS_ERROR_COPY, PERPS_ORDER_TYPE_LABELS, } from './perpsClientCopy.js';
|
|
27
31
|
export * from './perpsDiskPersistence.js';
|
|
32
|
+
export { getPositionDirection, recomputePositionAtPrice, } from './positionCalculations.js';
|
|
33
|
+
export { getPriceDeviationBand, isPriceOutsideDeviationBand, } from './priceDeviation.js';
|
|
34
|
+
export { roundPerpsPrice } from './pricePrecision.js';
|
|
28
35
|
export * from './rewardsUtils.js';
|
|
29
36
|
export * from './significantFigures.js';
|
|
30
37
|
export * from './sortMarkets.js';
|
package/dist/utils/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EACL,oBAAoB,EACpB,qBAAqB,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B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2B,CAAC;AACnC,OAAO,EACL,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC;AAE1B,qFAAqF;AACrF,MAAM,CAAC,MAAM,cAAc,GAAG,GAAmB,EAAE;IACjD,MAAM,GAAG,GAAG,UAAU,CAAC,OAAO,EAAE,GAAG,EAAE,QAAQ,IAAI,YAAY,CAAC;IAC9D,OAAO,GAAG,KAAK,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC;AAC/C,CAAC,CAAC;AACF,cAAc,sBAAsB,CAAC","sourcesContent":["/**\n * Barrel re-export for all portable utilities in controllers/utils/\n *\n * Note: hyperLiquidAdapter and orderCalculations both export calculatePositionSize.\n * We use selective exports to avoid the name collision.\n */\nexport * from './accountUtils.js';\nexport * from './advancedOrderLists.js';\nexport * from './advancedOrders.js';\nexport { getBatchOperationStatus } from './batchOperationStatus.js';\nexport {\n estimateCloseReceive,\n calculateNetClosedPnl,\n calculateCloseSize,\n} from './closeCalculations.js';\nexport type {\n CloseSize,\n CloseSizeParams,\n CloseReceiveEstimateParams,\n CloseReceiveEstimate,\n NetClosedPnlParams,\n} from './closeCalculations.js';\nexport * from './errorUtils.js';\nexport {\n calculateFeeNotionalUsd,\n calculateUndiscountedFeeAmount,\n getUndiscountedFeeRate,\n} from './feeAmounts.js';\nexport type { FeeNotionalParams } from './feeAmounts.js';\n// hyperLiquidAdapter: selective export to avoid calculatePositionSize clash with orderCalculations\nexport {\n adaptOrderToSDK,\n adaptPositionFromSDK,\n adaptOrderFromSDK,\n adaptPositionTriggerOrderFromSDK,\n adaptTpslLinkageToGrouping,\n adaptTriggerOrderTypeFromSDK,\n adaptMarketFromSDK,\n adaptAccountStateFromSDK,\n buildAssetMapping,\n formatHyperLiquidPrice,\n formatHyperLiquidSize,\n calculateHip3AssetId,\n parseAssetName,\n adaptHyperLiquidLedgerUpdateToUserHistoryItem,\n} from './hyperLiquidAdapter.js';\nexport * from './hyperLiquidOrderBookProcessor.js';\nexport * from './hyperLiquidPositionPreview.js';\nexport * from './hyperLiquidValidation.js';\nexport {\n calculateMaxRemovableMargin,\n estimateLiquidationPriceAfterMarginChange,\n} from './marginAdjustment.js';\nexport type {\n MaxRemovableMarginParams,\n LiquidationPriceAfterMarginChangeParams,\n} from './marginAdjustment.js';\nexport * from './idUtils.js';\nexport * from './marketDataTransform.js';\nexport * from './marketSearch.js';\nexport * from './marketUtils.js';\nexport {\n aggregateOrderBookLevels,\n calculateOrderBookAggregationParams,\n calculateOrderBookGroupingOptions,\n calculateOrderBookSpread,\n groupOrderBook,\n selectDefaultOrderBookGrouping,\n} from './orderBookGrouping.js';\nexport type {\n GroupedOrderBook,\n OrderBookAggregationParams,\n OrderBookSpread,\n} from './orderBookGrouping.js';\nexport { estimateOrderBookSlippage } from './orderBookSlippage.js';\nexport type {\n OrderBookSlippageEstimate,\n OrderBookSlippageParams,\n} from './orderBookSlippage.js';\nexport * from './orderCalculations.js';\nexport {\n normalizeHyperLiquidScalePriceLadder,\n sizeHyperLiquidScaleLadder,\n} from './hyperLiquidScaleOrders.js';\nexport { getFillAggregationKey, getOrderFillKey } from './orderFills.js';\nexport * from './orderTypes.js';\nexport {\n getPerpsErrorCopy,\n PERPS_ERROR_COPY,\n PERPS_ORDER_TYPE_LABELS,\n} from './perpsClientCopy.js';\nexport type { PerpsErrorCopy, PerpsOrderTypeLabel } from './perpsClientCopy.js';\nexport * from './perpsDiskPersistence.js';\nexport {\n getPositionDirection,\n recomputePositionAtPrice,\n} from './positionCalculations.js';\nexport {\n getPriceDeviationBand,\n isPriceOutsideDeviationBand,\n} from './priceDeviation.js';\nexport { roundPerpsPrice } from './pricePrecision.js';\nexport * from './rewardsUtils.js';\nexport * from './significantFigures.js';\nexport * from './sortMarkets.js';\nexport * from './standaloneInfoClient.js';\nexport * from './stringParseUtils.js';\nexport * from './subscriptionFeeWaiver.js';\nexport * from './tpslCalculations.js';\nexport * from './transferData.js';\nexport * from './wait.js';\n\n// Inline from former utils.ts (getEnvironment was previously at perps/utils.ts root)\nexport const getEnvironment = (): 'DEV' | 'PROD' => {\n const env = globalThis.process?.env?.NODE_ENV ?? 'production';\n return env === 'production' ? 'PROD' : 'DEV';\n};\nexport * from './perpsFormatters.js';\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { OrderBookData, OrderBookLevel } from '../types/index.js';
|
|
1
|
+
import type { OrderBookData, OrderBookLevel, SubscribeOrderBookParams } from '../types/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* Group order-book levels into price buckets of `grouping` width. Bids round
|
|
4
4
|
* down to their bucket and asks round up, so a bucket never claims a better
|
|
@@ -35,4 +35,65 @@ export type GroupedOrderBook = {
|
|
|
35
35
|
* @returns Trimmed sides plus the depth-bar denominators.
|
|
36
36
|
*/
|
|
37
37
|
export declare function groupOrderBook(orderBook: Pick<OrderBookData, 'bids' | 'asks'>, grouping: number | string | null, maxLevels: number): GroupedOrderBook;
|
|
38
|
+
/**
|
|
39
|
+
* Grouping widths offered for a book at `midPrice`: a decade four below the
|
|
40
|
+
* price's own, times 1, 2, 5, 10, 100 and 1000. Each width is rounded to
|
|
41
|
+
* `DECIMAL_PRECISION_CONFIG.MaxPriceDecimals` decimals and duplicates are
|
|
42
|
+
* dropped, so float noise never shows as a separate option and no width is
|
|
43
|
+
* finer than the smallest price step a market can quote.
|
|
44
|
+
*
|
|
45
|
+
* @param midPrice - Mid price of the book.
|
|
46
|
+
* @returns Grouping widths, ascending; `ORDER_BOOK_GROUPING_CONFIG.FallbackOptions`
|
|
47
|
+
* when the mid price is not a positive number.
|
|
48
|
+
*/
|
|
49
|
+
export declare function calculateOrderBookGroupingOptions(midPrice: number): number[];
|
|
50
|
+
/**
|
|
51
|
+
* The grouping width a book opens at.
|
|
52
|
+
*
|
|
53
|
+
* @param options - Widths from {@link calculateOrderBookGroupingOptions}.
|
|
54
|
+
* @returns The option at `ORDER_BOOK_GROUPING_CONFIG.DefaultOptionIndex`, else
|
|
55
|
+
* the middle option, or undefined for an empty list.
|
|
56
|
+
*/
|
|
57
|
+
export declare function selectDefaultOrderBookGrouping(options: readonly number[]): number | undefined;
|
|
58
|
+
/** Book-stream aggregation for a grouping width (`SubscribeOrderBookParams`). */
|
|
59
|
+
export type OrderBookAggregationParams = {
|
|
60
|
+
nSigFigs: NonNullable<SubscribeOrderBookParams['nSigFigs']>;
|
|
61
|
+
mantissa?: SubscribeOrderBookParams['mantissa'];
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* The `nSigFigs` and `mantissa` to subscribe a book at so the venue already
|
|
65
|
+
* aggregates it at `grouping`. Widths finer than five significant figures of
|
|
66
|
+
* the price use five, with a mantissa of 2 or 5 for widths starting with those
|
|
67
|
+
* digits. These are Hyperliquid's book-stream parameters; on a venue that
|
|
68
|
+
* streams raw levels, group client-side with {@link groupOrderBook} instead.
|
|
69
|
+
*
|
|
70
|
+
* @param grouping - Grouping width in quote units.
|
|
71
|
+
* @param price - Reference price, usually the mid.
|
|
72
|
+
* @returns The aggregation; five significant figures when either input is not
|
|
73
|
+
* a positive number.
|
|
74
|
+
*/
|
|
75
|
+
export declare function calculateOrderBookAggregationParams(grouping: number, price: number): OrderBookAggregationParams;
|
|
76
|
+
/** Top-of-book spread from {@link calculateOrderBookSpread}. */
|
|
77
|
+
export type OrderBookSpread = {
|
|
78
|
+
/** Best ask minus best bid, in quote units. */
|
|
79
|
+
spread: number;
|
|
80
|
+
/** Midpoint of the best bid and ask. */
|
|
81
|
+
midPrice: number;
|
|
82
|
+
/** Spread as a percent of the mid price (0.2 = 0.2%). */
|
|
83
|
+
spreadPercentage: number;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Spread, mid price and spread percent from the best bid and ask, in exact
|
|
87
|
+
* decimal arithmetic.
|
|
88
|
+
*
|
|
89
|
+
* @param params - Top of book.
|
|
90
|
+
* @param params.bestBid - Best bid price.
|
|
91
|
+
* @param params.bestAsk - Best ask price.
|
|
92
|
+
* @returns The spread, or undefined when either side is missing or not a
|
|
93
|
+
* positive number.
|
|
94
|
+
*/
|
|
95
|
+
export declare function calculateOrderBookSpread(params: {
|
|
96
|
+
bestBid: number | string | undefined;
|
|
97
|
+
bestAsk: number | string | undefined;
|
|
98
|
+
}): OrderBookSpread | undefined;
|
|
38
99
|
//# sourceMappingURL=orderBookGrouping.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orderBookGrouping.d.ts","sourceRoot":"","sources":["../../src/utils/orderBookGrouping.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"orderBookGrouping.d.ts","sourceRoot":"","sources":["../../src/utils/orderBookGrouping.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,aAAa,EACb,cAAc,EACd,wBAAwB,EACzB,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,SAAS,cAAc,EAAE,EACjC,QAAQ,EAAE,MAAM,GAAG,MAAM,EACzB,IAAI,EAAE,KAAK,GAAG,KAAK,GAClB,cAAc,EAAE,CA6DlB;AAED,2CAA2C;AAC3C,MAAM,MAAM,gBAAgB,GAAG;IAC7B,IAAI,EAAE,cAAc,EAAE,CAAC;IACvB,IAAI,EAAE,cAAc,EAAE,CAAC;IACvB,yEAAyE;IACzE,QAAQ,EAAE,MAAM,CAAC;IACjB,2DAA2D;IAC3D,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF;;;;;;;;;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OSE_POSITION_CONFIG, DECIMAL_PRECISION_CONFIG, ORDER_BOOK_GROUPING_CONFIG, } from '../constants/perpsConfig.js';
|
|
3
3
|
/**
|
|
4
4
|
* Group order-book levels into price buckets of `grouping` width. Bids round
|
|
5
5
|
* down to their bucket and asks round up, so a bucket never claims a better
|
|
@@ -98,4 +98,99 @@ export function groupOrderBook(orderBook, grouping, maxLevels) {
|
|
|
98
98
|
}
|
|
99
99
|
return { bids, asks, maxTotal, maxSize };
|
|
100
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* Grouping widths offered for a book at `midPrice`: a decade four below the
|
|
103
|
+
* price's own, times 1, 2, 5, 10, 100 and 1000. Each width is rounded to
|
|
104
|
+
* `DECIMAL_PRECISION_CONFIG.MaxPriceDecimals` decimals and duplicates are
|
|
105
|
+
* dropped, so float noise never shows as a separate option and no width is
|
|
106
|
+
* finer than the smallest price step a market can quote.
|
|
107
|
+
*
|
|
108
|
+
* @param midPrice - Mid price of the book.
|
|
109
|
+
* @returns Grouping widths, ascending; `ORDER_BOOK_GROUPING_CONFIG.FallbackOptions`
|
|
110
|
+
* when the mid price is not a positive number.
|
|
111
|
+
*/
|
|
112
|
+
export function calculateOrderBookGroupingOptions(midPrice) {
|
|
113
|
+
if (!Number.isFinite(midPrice) || midPrice <= 0) {
|
|
114
|
+
return [...ORDER_BOOK_GROUPING_CONFIG.FallbackOptions];
|
|
115
|
+
}
|
|
116
|
+
const base = 10 **
|
|
117
|
+
(Math.floor(Math.log10(midPrice)) -
|
|
118
|
+
ORDER_BOOK_GROUPING_CONFIG.DecadeOffset);
|
|
119
|
+
const options = ORDER_BOOK_GROUPING_CONFIG.Multipliers.map((multiplier) => Number((base * multiplier).toFixed(DECIMAL_PRECISION_CONFIG.MaxPriceDecimals))).filter((option) => option > 0);
|
|
120
|
+
const unique = Array.from(new Set(options));
|
|
121
|
+
return unique.length > 0
|
|
122
|
+
? unique
|
|
123
|
+
: [10 ** -DECIMAL_PRECISION_CONFIG.MaxPriceDecimals];
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The grouping width a book opens at.
|
|
127
|
+
*
|
|
128
|
+
* @param options - Widths from {@link calculateOrderBookGroupingOptions}.
|
|
129
|
+
* @returns The option at `ORDER_BOOK_GROUPING_CONFIG.DefaultOptionIndex`, else
|
|
130
|
+
* the middle option, or undefined for an empty list.
|
|
131
|
+
*/
|
|
132
|
+
export function selectDefaultOrderBookGrouping(options) {
|
|
133
|
+
return (options[ORDER_BOOK_GROUPING_CONFIG.DefaultOptionIndex] ??
|
|
134
|
+
options[Math.floor(options.length / 2)]);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* The `nSigFigs` and `mantissa` to subscribe a book at so the venue already
|
|
138
|
+
* aggregates it at `grouping`. Widths finer than five significant figures of
|
|
139
|
+
* the price use five, with a mantissa of 2 or 5 for widths starting with those
|
|
140
|
+
* digits. These are Hyperliquid's book-stream parameters; on a venue that
|
|
141
|
+
* streams raw levels, group client-side with {@link groupOrderBook} instead.
|
|
142
|
+
*
|
|
143
|
+
* @param grouping - Grouping width in quote units.
|
|
144
|
+
* @param price - Reference price, usually the mid.
|
|
145
|
+
* @returns The aggregation; five significant figures when either input is not
|
|
146
|
+
* a positive number.
|
|
147
|
+
*/
|
|
148
|
+
export function calculateOrderBookAggregationParams(grouping, price) {
|
|
149
|
+
const { MinSignificantFigures, MaxSignificantFigures } = ORDER_BOOK_GROUPING_CONFIG;
|
|
150
|
+
if (!Number.isFinite(price) ||
|
|
151
|
+
!Number.isFinite(grouping) ||
|
|
152
|
+
price <= 0 ||
|
|
153
|
+
grouping <= 0) {
|
|
154
|
+
return { nSigFigs: MaxSignificantFigures };
|
|
155
|
+
}
|
|
156
|
+
const groupingMagnitude = Math.floor(Math.log10(grouping));
|
|
157
|
+
const significantFigures = Math.floor(Math.log10(price)) - groupingMagnitude + 1;
|
|
158
|
+
if (significantFigures >= MaxSignificantFigures) {
|
|
159
|
+
const firstDigit = Math.floor(grouping / 10 ** groupingMagnitude);
|
|
160
|
+
if (firstDigit <= 1) {
|
|
161
|
+
return { nSigFigs: MaxSignificantFigures };
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
nSigFigs: MaxSignificantFigures,
|
|
165
|
+
mantissa: firstDigit <= 2 ? 2 : 5,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
nSigFigs: Math.max(MinSignificantFigures, significantFigures),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Spread, mid price and spread percent from the best bid and ask, in exact
|
|
174
|
+
* decimal arithmetic.
|
|
175
|
+
*
|
|
176
|
+
* @param params - Top of book.
|
|
177
|
+
* @param params.bestBid - Best bid price.
|
|
178
|
+
* @param params.bestAsk - Best ask price.
|
|
179
|
+
* @returns The spread, or undefined when either side is missing or not a
|
|
180
|
+
* positive number.
|
|
181
|
+
*/
|
|
182
|
+
export function calculateOrderBookSpread(params) {
|
|
183
|
+
const bid = new BigNumber(params.bestBid ?? Number.NaN);
|
|
184
|
+
const ask = new BigNumber(params.bestAsk ?? Number.NaN);
|
|
185
|
+
if (!bid.isFinite() || !ask.isFinite() || bid.lte(0) || ask.lte(0)) {
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
const spread = ask.minus(bid);
|
|
189
|
+
const midPrice = ask.plus(bid).dividedBy(2);
|
|
190
|
+
return {
|
|
191
|
+
spread: spread.toNumber(),
|
|
192
|
+
midPrice: midPrice.toNumber(),
|
|
193
|
+
spreadPercentage: spread.dividedBy(midPrice).multipliedBy(100).toNumber(),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
101
196
|
//# sourceMappingURL=orderBookGrouping.js.map
|