@metamask-previews/perps-controller 25.0.0-preview-d8b2a69a9 → 25.0.0-preview-2a2b320ba
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 +62 -0
- package/dist/PerpsController-method-action-types.d.ts +17 -7
- package/dist/PerpsController-method-action-types.d.ts.map +1 -1
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +20 -10
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +160 -97
- package/dist/PerpsController.js.map +1 -1
- 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/lighterConfig.js +2 -2
- package/dist/constants/lighterConfig.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 +16 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -6
- package/dist/index.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +14 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +46 -6
- package/dist/providers/AggregatedPerpsProvider.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/services/MarketDataService.d.ts +5 -2
- package/dist/services/MarketDataService.d.ts.map +1 -1
- package/dist/services/MarketDataService.js +211 -55
- package/dist/services/MarketDataService.js.map +1 -1
- package/dist/services/ServiceContext.d.ts +12 -7
- package/dist/services/ServiceContext.d.ts.map +1 -1
- package/dist/services/ServiceContext.js.map +1 -1
- package/dist/services/TerminalMarketService.d.ts.map +1 -1
- package/dist/services/TerminalMarketService.js +64 -22
- package/dist/services/TerminalMarketService.js.map +1 -1
- package/dist/types/index.d.ts +42 -4
- 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/marketUtils.d.ts +60 -1
- package/dist/utils/marketUtils.d.ts.map +1 -1
- package/dist/utils/marketUtils.js +151 -3
- package/dist/utils/marketUtils.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/architecture.md +9 -1
- package/docs/client-contract.md +31 -8
- package/docs/contracts/events.md +33 -31
- package/docs/contracts/feature-flags.md +5 -5
- package/docs/venues/lighter/capabilities.md +5 -0
- package/docs/venues/lighter/signer-provenance.md +52 -0
- package/package.json +1 -1
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { BigNumber } from 'bignumber.js';
|
|
2
|
+
import { BASIS_POINTS_DIVISOR } from '../constants/hyperLiquidConfig.js';
|
|
3
|
+
function unknownEstimate() {
|
|
4
|
+
return {
|
|
5
|
+
estimatedSlippageBps: undefined,
|
|
6
|
+
worstSlippageBps: undefined,
|
|
7
|
+
canFill: undefined,
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Slippage a market order would take by sweeping the visible book: the
|
|
12
|
+
* volume-weighted fill price and the last level reached, each measured from
|
|
13
|
+
* the reference price in basis points against the order's side and floored at
|
|
14
|
+
* zero.
|
|
15
|
+
*
|
|
16
|
+
* @param params - See {@link OrderBookSlippageParams}.
|
|
17
|
+
* @returns The estimate. `canFill` is false, with both slippages undefined,
|
|
18
|
+
* when the visible levels cannot hold the order; every field is undefined
|
|
19
|
+
* when the size or reference price is missing or not a positive number.
|
|
20
|
+
*/
|
|
21
|
+
export function estimateOrderBookSlippage(params) {
|
|
22
|
+
const { orderBook, isBuy } = params;
|
|
23
|
+
const reference = new BigNumber(params.referencePrice ?? orderBook.midPrice);
|
|
24
|
+
if (!reference.isFinite() || reference.lte(0)) {
|
|
25
|
+
return unknownEstimate();
|
|
26
|
+
}
|
|
27
|
+
const target = params.size === undefined
|
|
28
|
+
? new BigNumber(params.sizeUsd ?? Number.NaN).dividedBy(reference)
|
|
29
|
+
: new BigNumber(params.size).abs();
|
|
30
|
+
if (!target.isFinite() || target.lte(0)) {
|
|
31
|
+
return unknownEstimate();
|
|
32
|
+
}
|
|
33
|
+
// Exact decimals: binary floats leave 0.3 + 0.6 just short of 0.9.
|
|
34
|
+
let filled = new BigNumber(0);
|
|
35
|
+
let weightedPriceSum = new BigNumber(0);
|
|
36
|
+
let worstPrice;
|
|
37
|
+
for (const level of isBuy ? orderBook.asks : orderBook.bids) {
|
|
38
|
+
const price = new BigNumber(level.price);
|
|
39
|
+
const size = new BigNumber(level.size);
|
|
40
|
+
if (!price.isFinite() || !size.isFinite() || price.lte(0) || size.lte(0)) {
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
worstPrice = price;
|
|
44
|
+
const remaining = target.minus(filled);
|
|
45
|
+
if (remaining.lte(size)) {
|
|
46
|
+
weightedPriceSum = weightedPriceSum.plus(remaining.multipliedBy(price));
|
|
47
|
+
filled = target;
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
weightedPriceSum = weightedPriceSum.plus(size.multipliedBy(price));
|
|
51
|
+
filled = filled.plus(size);
|
|
52
|
+
}
|
|
53
|
+
if (worstPrice === undefined || filled.lt(target)) {
|
|
54
|
+
return {
|
|
55
|
+
estimatedSlippageBps: undefined,
|
|
56
|
+
worstSlippageBps: undefined,
|
|
57
|
+
canFill: false,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
const sign = isBuy ? 1 : -1;
|
|
61
|
+
const toBps = (price) => Math.max(0, price
|
|
62
|
+
.minus(reference)
|
|
63
|
+
.dividedBy(reference)
|
|
64
|
+
.multipliedBy(BASIS_POINTS_DIVISOR * sign)
|
|
65
|
+
.toNumber());
|
|
66
|
+
return {
|
|
67
|
+
estimatedSlippageBps: toBps(weightedPriceSum.dividedBy(filled)),
|
|
68
|
+
worstSlippageBps: toBps(worstPrice),
|
|
69
|
+
canFill: true,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=orderBookSlippage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orderBookSlippage.js","sourceRoot":"","sources":["../../src/utils/orderBookSlippage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AA8BzE,SAAS,eAAe;IACtB,OAAO;QACL,oBAAoB,EAAE,SAAS;QAC/B,gBAAgB,EAAE,SAAS;QAC3B,OAAO,EAAE,SAAS;KACnB,CAAC;AACJ,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,yBAAyB,CACvC,MAA+B;IAE/B,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,MAAM,CAAC;IACpC,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,MAAM,CAAC,cAAc,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC;IAC7E,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,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AAG,CAAC,IAAI,CAAC,EAAE,CAAC;YACxB,gBAAgB,GAAG,gBAAgB,CAAC,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;YACxE,MAAM,GAAG,MAAM,CAAC;YAChB,MAAM;QACR,CAAC;QACD,gBAAgB,GAAG,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;QACnE,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC;IAED,IAAI,UAAU,KAAK,SAAS,IAAI,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC;QAClD,OAAO;YACL,oBAAoB,EAAE,SAAS;YAC/B,gBAAgB,EAAE,SAAS;YAC3B,OAAO,EAAE,KAAK;SACf,CAAC;IACJ,CAAC;IAED,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5B,MAAM,KAAK,GAAG,CAAC,KAAgB,EAAU,EAAE,CACzC,IAAI,CAAC,GAAG,CACN,CAAC,EACD,KAAK;SACF,KAAK,CAAC,SAAS,CAAC;SAChB,SAAS,CAAC,SAAS,CAAC;SACpB,YAAY,CAAC,oBAAoB,GAAG,IAAI,CAAC;SACzC,QAAQ,EAAE,CACd,CAAC;IACJ,OAAO;QACL,oBAAoB,EAAE,KAAK,CAAC,gBAAgB,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QAC/D,gBAAgB,EAAE,KAAK,CAAC,UAAU,CAAC;QACnC,OAAO,EAAE,IAAI;KACd,CAAC;AACJ,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\nimport { BASIS_POINTS_DIVISOR } from '../constants/hyperLiquidConfig.js';\nimport type { OrderBookData } from '../types/index.js';\n\n/** Inputs to {@link estimateOrderBookSlippage}. */\nexport type OrderBookSlippageParams = {\n /** Book to sweep, as delivered by `subscribeToOrderBook`. */\n orderBook: Pick<OrderBookData, 'bids' | 'asks' | 'midPrice'>;\n /** A buy sweeps the asks, a sell the bids. */\n isBuy: boolean;\n /** Order size in base units. Takes precedence over `sizeUsd`. */\n size?: number | string;\n /** Order value in USD, converted to a size at the reference price. */\n sizeUsd?: number;\n /** Price slippage is measured from. Defaults to the book's mid price. */\n referencePrice?: number | string;\n};\n\n/** Result of {@link estimateOrderBookSlippage}. Undefined fields are unknown. */\nexport type OrderBookSlippageEstimate = {\n /** Average fill price's distance from the reference price, in basis points. */\n estimatedSlippageBps: number | undefined;\n /** Last level the order reaches, as distance from the reference, in basis points. */\n worstSlippageBps: number | undefined;\n /**\n * Whether the visible book holds the whole order. Depth only: to check a\n * max-slippage cap, compare `worstSlippageBps` with it.\n */\n canFill: boolean | undefined;\n};\n\nfunction unknownEstimate(): OrderBookSlippageEstimate {\n return {\n estimatedSlippageBps: undefined,\n worstSlippageBps: undefined,\n canFill: undefined,\n };\n}\n\n/**\n * Slippage a market order would take by sweeping the visible book: the\n * volume-weighted fill price and the last level reached, each measured from\n * the reference price in basis points against the order's side and floored at\n * zero.\n *\n * @param params - See {@link OrderBookSlippageParams}.\n * @returns The estimate. `canFill` is false, with both slippages undefined,\n * when the visible levels cannot hold the order; every field is undefined\n * when the size or reference price is missing or not a positive number.\n */\nexport function estimateOrderBookSlippage(\n params: OrderBookSlippageParams,\n): OrderBookSlippageEstimate {\n const { orderBook, isBuy } = params;\n const reference = new BigNumber(params.referencePrice ?? orderBook.midPrice);\n if (!reference.isFinite() || reference.lte(0)) {\n return unknownEstimate();\n }\n const target =\n params.size === undefined\n ? new BigNumber(params.sizeUsd ?? Number.NaN).dividedBy(reference)\n : new BigNumber(params.size).abs();\n if (!target.isFinite() || target.lte(0)) {\n return unknownEstimate();\n }\n\n // Exact decimals: binary floats leave 0.3 + 0.6 just short of 0.9.\n let filled = new BigNumber(0);\n let weightedPriceSum = new BigNumber(0);\n let worstPrice: BigNumber | undefined;\n for (const level of isBuy ? orderBook.asks : orderBook.bids) {\n const price = new BigNumber(level.price);\n const size = new BigNumber(level.size);\n if (!price.isFinite() || !size.isFinite() || price.lte(0) || size.lte(0)) {\n continue;\n }\n worstPrice = price;\n const remaining = target.minus(filled);\n if (remaining.lte(size)) {\n weightedPriceSum = weightedPriceSum.plus(remaining.multipliedBy(price));\n filled = target;\n break;\n }\n weightedPriceSum = weightedPriceSum.plus(size.multipliedBy(price));\n filled = filled.plus(size);\n }\n\n if (worstPrice === undefined || filled.lt(target)) {\n return {\n estimatedSlippageBps: undefined,\n worstSlippageBps: undefined,\n canFill: false,\n };\n }\n\n const sign = isBuy ? 1 : -1;\n const toBps = (price: BigNumber): number =>\n Math.max(\n 0,\n price\n .minus(reference)\n .dividedBy(reference)\n .multipliedBy(BASIS_POINTS_DIVISOR * sign)\n .toNumber(),\n );\n return {\n estimatedSlippageBps: toBps(weightedPriceSum.dividedBy(filled)),\n worstSlippageBps: toBps(worstPrice),\n canFill: true,\n };\n}\n"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { OrderFill } from '../types/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Identity of one fill for deduplicating REST history against live fills.
|
|
4
|
+
* Uses the venue's execution id when the fill has one; otherwise falls back
|
|
5
|
+
* to the fill's content (`orderId-timestamp-size-price`), which is what
|
|
6
|
+
* clients matched on before. Either is prefixed with `providerId` when set.
|
|
7
|
+
*
|
|
8
|
+
* @param fill - The fill.
|
|
9
|
+
* @returns A key equal for the same execution on every transport.
|
|
10
|
+
*/
|
|
11
|
+
export declare function getOrderFillKey(fill: Pick<OrderFill, 'orderId' | 'fillId' | 'timestamp' | 'size' | 'price' | 'providerId'>): string;
|
|
12
|
+
/**
|
|
13
|
+
* Key that seeds which fills are shown as one trade. Fills that reduce a
|
|
14
|
+
* position (`Close X`, `Sell`, `Auto-Deleveraging`) group by market,
|
|
15
|
+
* direction and second, since one close can fill as several orders; others
|
|
16
|
+
* group by market, direction and order id.
|
|
17
|
+
*
|
|
18
|
+
* @param fill - The fill.
|
|
19
|
+
* @returns `symbol-direction-second-<s>` or `symbol-direction-order-<id>`
|
|
20
|
+
* (`solo-<timestamp>` without an order id), prefixed with `providerId:` when
|
|
21
|
+
* set, or undefined when the direction is not grouped.
|
|
22
|
+
*/
|
|
23
|
+
export declare function getFillAggregationKey(fill: Pick<OrderFill, 'symbol' | 'direction' | 'timestamp' | 'orderId' | 'providerId'>): string | undefined;
|
|
24
|
+
//# sourceMappingURL=orderFills.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orderFills.d.ts","sourceRoot":"","sources":["../../src/utils/orderFills.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAiBnD;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,IAAI,CACR,SAAS,EACT,SAAS,GAAG,QAAQ,GAAG,WAAW,GAAG,MAAM,GAAG,OAAO,GAAG,YAAY,CACrE,GACA,MAAM,CAMR;AA2BD;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,IAAI,CACR,SAAS,EACT,QAAQ,GAAG,WAAW,GAAG,WAAW,GAAG,SAAS,GAAG,YAAY,CAChE,GACA,MAAM,GAAG,SAAS,CAgBpB"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prefix a key with the fill's provider, so fills from two venues in one
|
|
3
|
+
* aggregated list never share a key.
|
|
4
|
+
*
|
|
5
|
+
* @param providerId - `OrderFill.providerId`, set under aggregation.
|
|
6
|
+
* @param key - The provider-local key.
|
|
7
|
+
* @returns `providerId:key`, or `key` without a provider.
|
|
8
|
+
*/
|
|
9
|
+
function scopeToProvider(providerId, key) {
|
|
10
|
+
return providerId === undefined ? key : `${providerId}:${key}`;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Identity of one fill for deduplicating REST history against live fills.
|
|
14
|
+
* Uses the venue's execution id when the fill has one; otherwise falls back
|
|
15
|
+
* to the fill's content (`orderId-timestamp-size-price`), which is what
|
|
16
|
+
* clients matched on before. Either is prefixed with `providerId` when set.
|
|
17
|
+
*
|
|
18
|
+
* @param fill - The fill.
|
|
19
|
+
* @returns A key equal for the same execution on every transport.
|
|
20
|
+
*/
|
|
21
|
+
export function getOrderFillKey(fill) {
|
|
22
|
+
return scopeToProvider(fill.providerId, fill.fillId ??
|
|
23
|
+
`${fill.orderId}-${fill.timestamp}-${fill.size}-${fill.price}`);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The direction category fills are grouped under: `Open X` or `Close X`, a
|
|
27
|
+
* flip (`Long > Short`) as reported, `Buy`, `Sell` or `Auto-Deleveraging`.
|
|
28
|
+
*
|
|
29
|
+
* @param direction - `OrderFill.direction`.
|
|
30
|
+
* @returns The category, or undefined for a direction that is not grouped.
|
|
31
|
+
*/
|
|
32
|
+
function getFillAggregationDirection(direction) {
|
|
33
|
+
const [first, second] = direction.split(' ');
|
|
34
|
+
if (first === 'Open' || first === 'Close') {
|
|
35
|
+
return `${first} ${second}`;
|
|
36
|
+
}
|
|
37
|
+
if (second === '>') {
|
|
38
|
+
return direction;
|
|
39
|
+
}
|
|
40
|
+
if (direction === 'Buy' ||
|
|
41
|
+
direction === 'Sell' ||
|
|
42
|
+
direction === 'Auto-Deleveraging') {
|
|
43
|
+
return direction;
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Key that seeds which fills are shown as one trade. Fills that reduce a
|
|
49
|
+
* position (`Close X`, `Sell`, `Auto-Deleveraging`) group by market,
|
|
50
|
+
* direction and second, since one close can fill as several orders; others
|
|
51
|
+
* group by market, direction and order id.
|
|
52
|
+
*
|
|
53
|
+
* @param fill - The fill.
|
|
54
|
+
* @returns `symbol-direction-second-<s>` or `symbol-direction-order-<id>`
|
|
55
|
+
* (`solo-<timestamp>` without an order id), prefixed with `providerId:` when
|
|
56
|
+
* set, or undefined when the direction is not grouped.
|
|
57
|
+
*/
|
|
58
|
+
export function getFillAggregationKey(fill) {
|
|
59
|
+
const direction = getFillAggregationDirection(fill.direction);
|
|
60
|
+
if (direction === undefined) {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
const bucket = scopeToProvider(fill.providerId, `${fill.symbol}-${direction}`);
|
|
64
|
+
const reducesPosition = direction.startsWith('Close ') ||
|
|
65
|
+
direction === 'Sell' ||
|
|
66
|
+
direction === 'Auto-Deleveraging';
|
|
67
|
+
return reducesPosition
|
|
68
|
+
? `${bucket}-second-${Math.floor(fill.timestamp / 1000)}`
|
|
69
|
+
: `${bucket}-order-${fill.orderId || `solo-${fill.timestamp}`}`;
|
|
70
|
+
}
|
|
71
|
+
//# sourceMappingURL=orderFills.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orderFills.js","sourceRoot":"","sources":["../../src/utils/orderFills.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,SAAS,eAAe,CACtB,UAAmC,EACnC,GAAW;IAEX,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,UAAU,IAAI,GAAG,EAAE,CAAC;AACjE,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAC7B,IAGC;IAED,OAAO,eAAe,CACpB,IAAI,CAAC,UAAU,EACf,IAAI,CAAC,MAAM;QACT,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CACjE,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,SAAS,2BAA2B,CAAC,SAAiB;IACpD,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7C,IAAI,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,OAAO,EAAE,CAAC;QAC1C,OAAO,GAAG,KAAK,IAAI,MAAM,EAAE,CAAC;IAC9B,CAAC;IACD,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;QACnB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IACE,SAAS,KAAK,KAAK;QACnB,SAAS,KAAK,MAAM;QACpB,SAAS,KAAK,mBAAmB,EACjC,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,qBAAqB,CACnC,IAGC;IAED,MAAM,SAAS,GAAG,2BAA2B,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC9D,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;QAC5B,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,MAAM,GAAG,eAAe,CAC5B,IAAI,CAAC,UAAU,EACf,GAAG,IAAI,CAAC,MAAM,IAAI,SAAS,EAAE,CAC9B,CAAC;IACF,MAAM,eAAe,GACnB,SAAS,CAAC,UAAU,CAAC,QAAQ,CAAC;QAC9B,SAAS,KAAK,MAAM;QACpB,SAAS,KAAK,mBAAmB,CAAC;IACpC,OAAO,eAAe;QACpB,CAAC,CAAC,GAAG,MAAM,WAAW,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,EAAE;QACzD,CAAC,CAAC,GAAG,MAAM,UAAU,IAAI,CAAC,OAAO,IAAI,QAAQ,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;AACpE,CAAC","sourcesContent":["import type { OrderFill } from '../types/index.js';\n\n/**\n * Prefix a key with the fill's provider, so fills from two venues in one\n * aggregated list never share a key.\n *\n * @param providerId - `OrderFill.providerId`, set under aggregation.\n * @param key - The provider-local key.\n * @returns `providerId:key`, or `key` without a provider.\n */\nfunction scopeToProvider(\n providerId: OrderFill['providerId'],\n key: string,\n): string {\n return providerId === undefined ? key : `${providerId}:${key}`;\n}\n\n/**\n * Identity of one fill for deduplicating REST history against live fills.\n * Uses the venue's execution id when the fill has one; otherwise falls back\n * to the fill's content (`orderId-timestamp-size-price`), which is what\n * clients matched on before. Either is prefixed with `providerId` when set.\n *\n * @param fill - The fill.\n * @returns A key equal for the same execution on every transport.\n */\nexport function getOrderFillKey(\n fill: Pick<\n OrderFill,\n 'orderId' | 'fillId' | 'timestamp' | 'size' | 'price' | 'providerId'\n >,\n): string {\n return scopeToProvider(\n fill.providerId,\n fill.fillId ??\n `${fill.orderId}-${fill.timestamp}-${fill.size}-${fill.price}`,\n );\n}\n\n/**\n * The direction category fills are grouped under: `Open X` or `Close X`, a\n * flip (`Long > Short`) as reported, `Buy`, `Sell` or `Auto-Deleveraging`.\n *\n * @param direction - `OrderFill.direction`.\n * @returns The category, or undefined for a direction that is not grouped.\n */\nfunction getFillAggregationDirection(direction: string): string | undefined {\n const [first, second] = direction.split(' ');\n if (first === 'Open' || first === 'Close') {\n return `${first} ${second}`;\n }\n if (second === '>') {\n return direction;\n }\n if (\n direction === 'Buy' ||\n direction === 'Sell' ||\n direction === 'Auto-Deleveraging'\n ) {\n return direction;\n }\n return undefined;\n}\n\n/**\n * Key that seeds which fills are shown as one trade. Fills that reduce a\n * position (`Close X`, `Sell`, `Auto-Deleveraging`) group by market,\n * direction and second, since one close can fill as several orders; others\n * group by market, direction and order id.\n *\n * @param fill - The fill.\n * @returns `symbol-direction-second-<s>` or `symbol-direction-order-<id>`\n * (`solo-<timestamp>` without an order id), prefixed with `providerId:` when\n * set, or undefined when the direction is not grouped.\n */\nexport function getFillAggregationKey(\n fill: Pick<\n OrderFill,\n 'symbol' | 'direction' | 'timestamp' | 'orderId' | 'providerId'\n >,\n): string | undefined {\n const direction = getFillAggregationDirection(fill.direction);\n if (direction === undefined) {\n return undefined;\n }\n const bucket = scopeToProvider(\n fill.providerId,\n `${fill.symbol}-${direction}`,\n );\n const reducesPosition =\n direction.startsWith('Close ') ||\n direction === 'Sell' ||\n direction === 'Auto-Deleveraging';\n return reducesPosition\n ? `${bucket}-second-${Math.floor(fill.timestamp / 1000)}`\n : `${bucket}-order-${fill.orderId || `solo-${fill.timestamp}`}`;\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Position } from '../types/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Side of a position from its signed size.
|
|
4
|
+
*
|
|
5
|
+
* @param size - Signed position size (`Position.size`): positive long, negative short.
|
|
6
|
+
* @returns `long` or `short`, or undefined for a zero or unreadable size.
|
|
7
|
+
*/
|
|
8
|
+
export declare function getPositionDirection(size: number | string): 'long' | 'short' | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* A position revalued at a live price, such as the latest mark: unrealized
|
|
11
|
+
* PnL `(price - entry) * size`, value `|size| * price` and return on equity
|
|
12
|
+
* as a decimal (0.1 = 10%), as Mobile computes between account updates.
|
|
13
|
+
* Return on equity keeps the venue's figure while leverage is unreported.
|
|
14
|
+
* Margin and liquidation price keep the venue's last figures.
|
|
15
|
+
*
|
|
16
|
+
* @param position - The position.
|
|
17
|
+
* @param price - Live price of its market.
|
|
18
|
+
* @returns A copy with the three figures recomputed, or the same position
|
|
19
|
+
* when the price, entry price or size is missing, zero or not a number.
|
|
20
|
+
*/
|
|
21
|
+
export declare function recomputePositionAtPrice<PositionLike extends Pick<Position, 'size' | 'entryPrice' | 'leverage' | 'unrealizedPnl' | 'positionValue' | 'returnOnEquity'>>(position: PositionLike, price: number | string): PositionLike;
|
|
22
|
+
//# sourceMappingURL=positionCalculations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"positionCalculations.d.ts","sourceRoot":"","sources":["../../src/utils/positionCalculations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAGlD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,MAAM,GAAG,MAAM,GACpB,MAAM,GAAG,OAAO,GAAG,SAAS,CAM9B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,SAAS,IAAI,CACvB,QAAQ,EACN,MAAM,GACN,YAAY,GACZ,UAAU,GACV,eAAe,GACf,eAAe,GACf,gBAAgB,CACnB,EACD,QAAQ,EAAE,YAAY,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,YAAY,CA4B9D"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { calculateSignedRoEForPrice } from './tpslCalculations.js';
|
|
2
|
+
/**
|
|
3
|
+
* Side of a position from its signed size.
|
|
4
|
+
*
|
|
5
|
+
* @param size - Signed position size (`Position.size`): positive long, negative short.
|
|
6
|
+
* @returns `long` or `short`, or undefined for a zero or unreadable size.
|
|
7
|
+
*/
|
|
8
|
+
export function getPositionDirection(size) {
|
|
9
|
+
const signedSize = Number.parseFloat(String(size));
|
|
10
|
+
if (!Number.isFinite(signedSize) || signedSize === 0) {
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
return signedSize > 0 ? 'long' : 'short';
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A position revalued at a live price, such as the latest mark: unrealized
|
|
17
|
+
* PnL `(price - entry) * size`, value `|size| * price` and return on equity
|
|
18
|
+
* as a decimal (0.1 = 10%), as Mobile computes between account updates.
|
|
19
|
+
* Return on equity keeps the venue's figure while leverage is unreported.
|
|
20
|
+
* Margin and liquidation price keep the venue's last figures.
|
|
21
|
+
*
|
|
22
|
+
* @param position - The position.
|
|
23
|
+
* @param price - Live price of its market.
|
|
24
|
+
* @returns A copy with the three figures recomputed, or the same position
|
|
25
|
+
* when the price, entry price or size is missing, zero or not a number.
|
|
26
|
+
*/
|
|
27
|
+
export function recomputePositionAtPrice(position, price) {
|
|
28
|
+
const currentPrice = Number.parseFloat(String(price));
|
|
29
|
+
const entryPrice = Number.parseFloat(position.entryPrice);
|
|
30
|
+
const size = Number.parseFloat(position.size);
|
|
31
|
+
const direction = getPositionDirection(size);
|
|
32
|
+
if (!Number.isFinite(currentPrice) ||
|
|
33
|
+
currentPrice <= 0 ||
|
|
34
|
+
!Number.isFinite(entryPrice) ||
|
|
35
|
+
entryPrice <= 0 ||
|
|
36
|
+
direction === undefined) {
|
|
37
|
+
return position;
|
|
38
|
+
}
|
|
39
|
+
const roePercent = calculateSignedRoEForPrice(currentPrice.toString(), {
|
|
40
|
+
currentPrice,
|
|
41
|
+
direction,
|
|
42
|
+
leverage: position.leverage.value,
|
|
43
|
+
entryPrice,
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
...position,
|
|
47
|
+
unrealizedPnl: ((currentPrice - entryPrice) * size).toString(),
|
|
48
|
+
returnOnEquity: roePercent
|
|
49
|
+
? (Number.parseFloat(roePercent) / 100).toString()
|
|
50
|
+
: position.returnOnEquity,
|
|
51
|
+
positionValue: (Math.abs(size) * currentPrice).toString(),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=positionCalculations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"positionCalculations.js","sourceRoot":"","sources":["../../src/utils/positionCalculations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAEnE;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAClC,IAAqB;IAErB,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;IACnD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,UAAU,KAAK,CAAC,EAAE,CAAC;QACrD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;AAC3C,CAAC;AAED;;;;;;;;;;;G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/**\n * Side of a position from its signed size.\n *\n * @param size - Signed position size (`Position.size`): positive long, negative short.\n * @returns `long` or `short`, or undefined for a zero or unreadable size.\n */\nexport function getPositionDirection(\n size: number | string,\n): 'long' | 'short' | undefined {\n const signedSize = Number.parseFloat(String(size));\n if (!Number.isFinite(signedSize) || signedSize === 0) {\n return undefined;\n }\n return signedSize > 0 ? 'long' : 'short';\n}\n\n/**\n * A position revalued at a live price, such as the latest mark: unrealized\n * PnL `(price - entry) * size`, value `|size| * price` and return on equity\n * as a decimal (0.1 = 10%), as Mobile computes between account updates.\n * Return on equity keeps the venue's figure while leverage is unreported.\n * Margin and liquidation price keep the venue's last figures.\n *\n * @param position - The position.\n * @param price - Live price of its market.\n * @returns A copy with the three figures recomputed, or the same position\n * when the price, entry price or size is missing, zero or not a number.\n */\nexport function recomputePositionAtPrice<\n PositionLike extends Pick<\n Position,\n | 'size'\n | 'entryPrice'\n | 'leverage'\n | 'unrealizedPnl'\n | 'positionValue'\n | 'returnOnEquity'\n >,\n>(position: PositionLike, price: number | string): PositionLike {\n const currentPrice = Number.parseFloat(String(price));\n const entryPrice = Number.parseFloat(position.entryPrice);\n const size = Number.parseFloat(position.size);\n const direction = getPositionDirection(size);\n if (\n !Number.isFinite(currentPrice) ||\n currentPrice <= 0 ||\n !Number.isFinite(entryPrice) ||\n entryPrice <= 0 ||\n direction === undefined\n ) {\n return position;\n }\n const roePercent = calculateSignedRoEForPrice(currentPrice.toString(), {\n currentPrice,\n direction,\n leverage: position.leverage.value,\n entryPrice,\n });\n return {\n ...position,\n unrealizedPnl: ((currentPrice - entryPrice) * size).toString(),\n returnOnEquity: roePercent\n ? (Number.parseFloat(roePercent) / 100).toString()\n : position.returnOnEquity,\n positionValue: (Math.abs(size) * currentPrice).toString(),\n };\n}\n"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prices a venue accepts around a reference price under a deviation limit
|
|
3
|
+
* such as `PerpsOrderLimits.maxOraclePriceDeviation`: from `1 - maxDeviation`
|
|
4
|
+
* times the reference up to the reference divided by it.
|
|
5
|
+
*
|
|
6
|
+
* @param referencePrice - Oracle price, or the mark price when the oracle is unknown.
|
|
7
|
+
* @param maxDeviation - Deviation limit as a fraction, above 0 and below 1.
|
|
8
|
+
* @returns The inclusive band, or undefined when either input is unusable.
|
|
9
|
+
*/
|
|
10
|
+
export declare function getPriceDeviationBand(referencePrice: number, maxDeviation: number): {
|
|
11
|
+
min: number;
|
|
12
|
+
max: number;
|
|
13
|
+
} | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* Whether a price is outside the inclusive band {@link getPriceDeviationBand}
|
|
16
|
+
* returns: below `1 - maxDeviation` times the reference, or above the
|
|
17
|
+
* reference divided by it.
|
|
18
|
+
*
|
|
19
|
+
* @param price - Order price.
|
|
20
|
+
* @param referencePrice - Oracle price, or the mark price when the oracle is unknown.
|
|
21
|
+
* @param maxDeviation - Deviation limit as a fraction, such as
|
|
22
|
+
* `PerpsOrderLimits.maxOraclePriceDeviation`.
|
|
23
|
+
* @returns True when the price is outside the band; false when it is inside,
|
|
24
|
+
* on a bound, or an input is missing, so unknown input never blocks an order.
|
|
25
|
+
*/
|
|
26
|
+
export declare function isPriceOutsideDeviationBand(price: number, referencePrice: number, maxDeviation: number): boolean;
|
|
27
|
+
//# sourceMappingURL=priceDeviation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"priceDeviation.d.ts","sourceRoot":"","sources":["../../src/utils/priceDeviation.ts"],"names":[],"mappings":"AA8BA;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,GACnB;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAG1C;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,MAAM,EACb,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,GACnB,OAAO,CAQT"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { BigNumber } from 'bignumber.js';
|
|
2
|
+
/**
|
|
3
|
+
* Band bounds in exact decimals, so `1 - 0.95` is exactly 0.05.
|
|
4
|
+
*
|
|
5
|
+
* @param referencePrice - Reference price.
|
|
6
|
+
* @param maxDeviation - Deviation limit as a fraction.
|
|
7
|
+
* @returns The bounds, or undefined when either input is unusable.
|
|
8
|
+
*/
|
|
9
|
+
function deviationBounds(referencePrice, maxDeviation) {
|
|
10
|
+
if (!Number.isFinite(referencePrice) ||
|
|
11
|
+
referencePrice <= 0 ||
|
|
12
|
+
!Number.isFinite(maxDeviation) ||
|
|
13
|
+
maxDeviation <= 0 ||
|
|
14
|
+
maxDeviation >= 1) {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
const reference = new BigNumber(referencePrice);
|
|
18
|
+
const ratio = new BigNumber(1).minus(maxDeviation);
|
|
19
|
+
return {
|
|
20
|
+
min: reference.multipliedBy(ratio),
|
|
21
|
+
max: reference.dividedBy(ratio),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Prices a venue accepts around a reference price under a deviation limit
|
|
26
|
+
* such as `PerpsOrderLimits.maxOraclePriceDeviation`: from `1 - maxDeviation`
|
|
27
|
+
* times the reference up to the reference divided by it.
|
|
28
|
+
*
|
|
29
|
+
* @param referencePrice - Oracle price, or the mark price when the oracle is unknown.
|
|
30
|
+
* @param maxDeviation - Deviation limit as a fraction, above 0 and below 1.
|
|
31
|
+
* @returns The inclusive band, or undefined when either input is unusable.
|
|
32
|
+
*/
|
|
33
|
+
export function getPriceDeviationBand(referencePrice, maxDeviation) {
|
|
34
|
+
const bounds = deviationBounds(referencePrice, maxDeviation);
|
|
35
|
+
return bounds && { min: bounds.min.toNumber(), max: bounds.max.toNumber() };
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Whether a price is outside the inclusive band {@link getPriceDeviationBand}
|
|
39
|
+
* returns: below `1 - maxDeviation` times the reference, or above the
|
|
40
|
+
* reference divided by it.
|
|
41
|
+
*
|
|
42
|
+
* @param price - Order price.
|
|
43
|
+
* @param referencePrice - Oracle price, or the mark price when the oracle is unknown.
|
|
44
|
+
* @param maxDeviation - Deviation limit as a fraction, such as
|
|
45
|
+
* `PerpsOrderLimits.maxOraclePriceDeviation`.
|
|
46
|
+
* @returns True when the price is outside the band; false when it is inside,
|
|
47
|
+
* on a bound, or an input is missing, so unknown input never blocks an order.
|
|
48
|
+
*/
|
|
49
|
+
export function isPriceOutsideDeviationBand(price, referencePrice, maxDeviation) {
|
|
50
|
+
// Compare with the numbers getPriceDeviationBand returns, so a price on a
|
|
51
|
+
// bound it reports is always inside.
|
|
52
|
+
const band = getPriceDeviationBand(referencePrice, maxDeviation);
|
|
53
|
+
if (band === undefined || !Number.isFinite(price) || price <= 0) {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
return price < band.min || price > band.max;
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=priceDeviation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"priceDeviation.js","sourceRoot":"","sources":["../../src/utils/priceDeviation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;;;GAMG;AACH,SAAS,eAAe,CACtB,cAAsB,EACtB,YAAoB;IAEpB,IACE,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC;QAChC,cAAc,IAAI,CAAC;QACnB,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC;QAC9B,YAAY,IAAI,CAAC;QACjB,YAAY,IAAI,CAAC,EACjB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,cAAc,CAAC,CAAC;IAChD,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACnD,OAAO;QACL,GAAG,EAAE,SAAS,CAAC,YAAY,CAAC,KAAK,CAAC;QAClC,GAAG,EAAE,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC;KAChC,CAAC;AACJ,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,qBAAqB,CACnC,cAAsB,EACtB,YAAoB;IAEpB,MAAM,MAAM,GAAG,eAAe,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IAC7D,OAAO,MAAM,IAAI,EAAE,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC;AAC9E,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,2BAA2B,CACzC,KAAa,EACb,cAAsB,EACtB,YAAoB;IAEpB,0EAA0E;IAC1E,qCAAqC;IACrC,MAAM,IAAI,GAAG,qBAAqB,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACjE,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QAChE,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,KAAK,GAAG,IAAI,CAAC,GAAG,IAAI,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC;AAC9C,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\n/**\n * Band bounds in exact decimals, so `1 - 0.95` is exactly 0.05.\n *\n * @param referencePrice - Reference price.\n * @param maxDeviation - Deviation limit as a fraction.\n * @returns The bounds, or undefined when either input is unusable.\n */\nfunction deviationBounds(\n referencePrice: number,\n maxDeviation: number,\n): { min: BigNumber; max: BigNumber } | undefined {\n if (\n !Number.isFinite(referencePrice) ||\n referencePrice <= 0 ||\n !Number.isFinite(maxDeviation) ||\n maxDeviation <= 0 ||\n maxDeviation >= 1\n ) {\n return undefined;\n }\n const reference = new BigNumber(referencePrice);\n const ratio = new BigNumber(1).minus(maxDeviation);\n return {\n min: reference.multipliedBy(ratio),\n max: reference.dividedBy(ratio),\n };\n}\n\n/**\n * Prices a venue accepts around a reference price under a deviation limit\n * such as `PerpsOrderLimits.maxOraclePriceDeviation`: from `1 - maxDeviation`\n * times the reference up to the reference divided by it.\n *\n * @param referencePrice - Oracle price, or the mark price when the oracle is unknown.\n * @param maxDeviation - Deviation limit as a fraction, above 0 and below 1.\n * @returns The inclusive band, or undefined when either input is unusable.\n */\nexport function getPriceDeviationBand(\n referencePrice: number,\n maxDeviation: number,\n): { min: number; max: number } | undefined {\n const bounds = deviationBounds(referencePrice, maxDeviation);\n return bounds && { min: bounds.min.toNumber(), max: bounds.max.toNumber() };\n}\n\n/**\n * Whether a price is outside the inclusive band {@link getPriceDeviationBand}\n * returns: below `1 - maxDeviation` times the reference, or above the\n * reference divided by it.\n *\n * @param price - Order price.\n * @param referencePrice - Oracle price, or the mark price when the oracle is unknown.\n * @param maxDeviation - Deviation limit as a fraction, such as\n * `PerpsOrderLimits.maxOraclePriceDeviation`.\n * @returns True when the price is outside the band; false when it is inside,\n * on a bound, or an input is missing, so unknown input never blocks an order.\n */\nexport function isPriceOutsideDeviationBand(\n price: number,\n referencePrice: number,\n maxDeviation: number,\n): boolean {\n // Compare with the numbers getPriceDeviationBand returns, so a price on a\n // bound it reports is always inside.\n const band = getPriceDeviationBand(referencePrice, maxDeviation);\n if (band === undefined || !Number.isFinite(price) || price <= 0) {\n return false;\n }\n return price < band.min || price > band.max;\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { PerpsPricePrecision } from '../types/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Round a price onto the grid a market accepts, as reported in
|
|
4
|
+
* `PerpsOrderCapabilities.pricePrecision`. A `significant_figures` grid
|
|
5
|
+
* (Hyperliquid) keeps integers as they are, otherwise caps the decimals and
|
|
6
|
+
* then the significant figures, giving the same string as
|
|
7
|
+
* `formatHyperLiquidPrice`. A `fixed_decimals` grid (Lighter) rounds half up
|
|
8
|
+
* to the nearest multiple of its tick.
|
|
9
|
+
*
|
|
10
|
+
* @param params - Rounding parameters.
|
|
11
|
+
* @param params.price - Price in quote units.
|
|
12
|
+
* @param params.pricePrecision - The market's price grid.
|
|
13
|
+
* @returns The rounded price, or undefined when the price is not a positive
|
|
14
|
+
* number, rounds to zero, or the tick is unusable.
|
|
15
|
+
*/
|
|
16
|
+
export declare function roundPerpsPrice(params: {
|
|
17
|
+
price: number | string;
|
|
18
|
+
pricePrecision: PerpsPricePrecision;
|
|
19
|
+
}): string | undefined;
|
|
20
|
+
//# sourceMappingURL=pricePrecision.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pricePrecision.d.ts","sourceRoot":"","sources":["../../src/utils/pricePrecision.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAM7D;;;;;;;;;;;;;GAaG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE;IACtC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,cAAc,EAAE,mBAAmB,CAAC;CACrC,GAAG,MAAM,GAAG,SAAS,CA2CrB"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { BigNumber } from 'bignumber.js';
|
|
2
|
+
import { countSignificantFigures, roundToSignificantFigures, } from './significantFigures.js';
|
|
3
|
+
/**
|
|
4
|
+
* Round a price onto the grid a market accepts, as reported in
|
|
5
|
+
* `PerpsOrderCapabilities.pricePrecision`. A `significant_figures` grid
|
|
6
|
+
* (Hyperliquid) keeps integers as they are, otherwise caps the decimals and
|
|
7
|
+
* then the significant figures, giving the same string as
|
|
8
|
+
* `formatHyperLiquidPrice`. A `fixed_decimals` grid (Lighter) rounds half up
|
|
9
|
+
* to the nearest multiple of its tick.
|
|
10
|
+
*
|
|
11
|
+
* @param params - Rounding parameters.
|
|
12
|
+
* @param params.price - Price in quote units.
|
|
13
|
+
* @param params.pricePrecision - The market's price grid.
|
|
14
|
+
* @returns The rounded price, or undefined when the price is not a positive
|
|
15
|
+
* number, rounds to zero, or the tick is unusable.
|
|
16
|
+
*/
|
|
17
|
+
export function roundPerpsPrice(params) {
|
|
18
|
+
const { price, pricePrecision } = params;
|
|
19
|
+
const priceNum = Number.parseFloat(String(price));
|
|
20
|
+
if (!Number.isFinite(priceNum) || priceNum <= 0) {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
let rounded;
|
|
24
|
+
if (pricePrecision.type === 'fixed_decimals') {
|
|
25
|
+
const tick = new BigNumber(pricePrecision.tickSize);
|
|
26
|
+
if (!tick.isFinite() || tick.lte(0)) {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
// Read the caller's decimal string, not its float: 1.004999999999999999
|
|
30
|
+
// would otherwise become 1.005 and round up.
|
|
31
|
+
const exact = new BigNumber(String(price).trim());
|
|
32
|
+
if (!exact.isFinite() || exact.lte(0)) {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
// Exact remainder, not a quotient: division rounds to 20 decimals and
|
|
36
|
+
// could turn a value just under a half tick into exactly half.
|
|
37
|
+
const remainder = exact.modulo(tick);
|
|
38
|
+
const down = exact.minus(remainder);
|
|
39
|
+
rounded = (remainder.multipliedBy(2).gte(tick) ? down.plus(tick) : down).toFixed();
|
|
40
|
+
}
|
|
41
|
+
else if (Number.isInteger(priceNum)) {
|
|
42
|
+
rounded = priceNum.toString();
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
rounded = Number.parseFloat(priceNum.toFixed(pricePrecision.maxDecimals)).toString();
|
|
46
|
+
if (countSignificantFigures(rounded) > pricePrecision.maxSignificantFigures) {
|
|
47
|
+
rounded = roundToSignificantFigures(rounded, pricePrecision.maxSignificantFigures);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return Number.parseFloat(rounded) > 0 ? rounded : undefined;
|
|
51
|
+
}
|
|
52
|
+
//# sourceMappingURL=pricePrecision.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pricePrecision.js","sourceRoot":"","sources":["../../src/utils/pricePrecision.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAGzC,OAAO,EACL,uBAAuB,EACvB,yBAAyB,GAC1B,MAAM,yBAAyB,CAAC;AAEjC;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,eAAe,CAAC,MAG/B;IACC,MAAM,EAAE,KAAK,EAAE,cAAc,EAAE,GAAG,MAAM,CAAC;IACzC,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAClD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,QAAQ,IAAI,CAAC,EAAE,CAAC;QAChD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,OAAe,CAAC;IACpB,IAAI,cAAc,CAAC,IAAI,KAAK,gBAAgB,EAAE,CAAC;QAC7C,MAAM,IAAI,GAAG,IAAI,SAAS,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;QACpD,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;YACpC,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,wEAAwE;QACxE,6CAA6C;QAC7C,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;YACtC,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,sEAAsE;QACtE,+DAA+D;QAC/D,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QACpC,OAAO,GAAG,CACR,SAAS,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAC7D,CAAC,OAAO,EAAE,CAAC;IACd,CAAC;SAAM,IAAI,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC;QACtC,OAAO,GAAG,QAAQ,CAAC,QAAQ,EAAE,CAAC;IAChC,CAAC;SAAM,CAAC;QACN,OAAO,GAAG,MAAM,CAAC,UAAU,CACzB,QAAQ,CAAC,OAAO,CAAC,cAAc,CAAC,WAAW,CAAC,CAC7C,CAAC,QAAQ,EAAE,CAAC;QACb,IACE,uBAAuB,CAAC,OAAO,CAAC,GAAG,cAAc,CAAC,qBAAqB,EACvE,CAAC;YACD,OAAO,GAAG,yBAAyB,CACjC,OAAO,EACP,cAAc,CAAC,qBAAqB,CACrC,CAAC;QACJ,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9D,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\nimport type { PerpsPricePrecision } from '../types/index.js';\nimport {\n countSignificantFigures,\n roundToSignificantFigures,\n} from './significantFigures.js';\n\n/**\n * Round a price onto the grid a market accepts, as reported in\n * `PerpsOrderCapabilities.pricePrecision`. A `significant_figures` grid\n * (Hyperliquid) keeps integers as they are, otherwise caps the decimals and\n * then the significant figures, giving the same string as\n * `formatHyperLiquidPrice`. A `fixed_decimals` grid (Lighter) rounds half up\n * to the nearest multiple of its tick.\n *\n * @param params - Rounding parameters.\n * @param params.price - Price in quote units.\n * @param params.pricePrecision - The market's price grid.\n * @returns The rounded price, or undefined when the price is not a positive\n * number, rounds to zero, or the tick is unusable.\n */\nexport function roundPerpsPrice(params: {\n price: number | string;\n pricePrecision: PerpsPricePrecision;\n}): string | undefined {\n const { price, pricePrecision } = params;\n const priceNum = Number.parseFloat(String(price));\n if (!Number.isFinite(priceNum) || priceNum <= 0) {\n return undefined;\n }\n\n let rounded: string;\n if (pricePrecision.type === 'fixed_decimals') {\n const tick = new BigNumber(pricePrecision.tickSize);\n if (!tick.isFinite() || tick.lte(0)) {\n return undefined;\n }\n // Read the caller's decimal string, not its float: 1.004999999999999999\n // would otherwise become 1.005 and round up.\n const exact = new BigNumber(String(price).trim());\n if (!exact.isFinite() || exact.lte(0)) {\n return undefined;\n }\n // Exact remainder, not a quotient: division rounds to 20 decimals and\n // could turn a value just under a half tick into exactly half.\n const remainder = exact.modulo(tick);\n const down = exact.minus(remainder);\n rounded = (\n remainder.multipliedBy(2).gte(tick) ? down.plus(tick) : down\n ).toFixed();\n } else if (Number.isInteger(priceNum)) {\n rounded = priceNum.toString();\n } else {\n rounded = Number.parseFloat(\n priceNum.toFixed(pricePrecision.maxDecimals),\n ).toString();\n if (\n countSignificantFigures(rounded) > pricePrecision.maxSignificantFigures\n ) {\n rounded = roundToSignificantFigures(\n rounded,\n pricePrecision.maxSignificantFigures,\n );\n }\n }\n\n return Number.parseFloat(rounded) > 0 ? rounded : undefined;\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { OrderDirection } from '../types/index.js';
|
|
2
|
+
import type { TriggerOrderType } from '../types/perps-types.js';
|
|
2
3
|
/**
|
|
3
4
|
* Price context for the TP/SL calculations and checks.
|
|
4
5
|
*/
|
|
@@ -209,4 +210,25 @@ export type ExpectedTriggerPnlParams = {
|
|
|
209
210
|
* @example calculateExpectedTriggerPnl({ triggerPrice: 110, entryPrice: 100, size: -2, closingFee: 0.1 }) => -20.1
|
|
210
211
|
*/
|
|
211
212
|
export declare function calculateExpectedTriggerPnl(params: ExpectedTriggerPnlParams): number;
|
|
213
|
+
/**
|
|
214
|
+
* Whether a trigger price sits on the side its order fires from. A buy stop
|
|
215
|
+
* and a sell take profit fire as the price rises, so they trigger above the
|
|
216
|
+
* reference price; a buy take profit and a sell stop trigger below it. A
|
|
217
|
+
* trigger at the reference price is on neither side.
|
|
218
|
+
*
|
|
219
|
+
* @param params - Trigger parameters.
|
|
220
|
+
* @param params.orderType - Trigger order type.
|
|
221
|
+
* @param params.isBuy - Side of the trigger order itself (a buy closes a short).
|
|
222
|
+
* @param params.triggerPrice - Price at which the order activates.
|
|
223
|
+
* @param params.referencePrice - Current price, or the parent's price for an
|
|
224
|
+
* attached trigger.
|
|
225
|
+
* @returns Whether the trigger is on its side, or undefined when either price
|
|
226
|
+
* is missing or not a positive number.
|
|
227
|
+
*/
|
|
228
|
+
export declare function isTriggerPriceOnValidSide(params: {
|
|
229
|
+
orderType: TriggerOrderType;
|
|
230
|
+
isBuy: boolean;
|
|
231
|
+
triggerPrice: number | string | undefined;
|
|
232
|
+
referencePrice: number | string | undefined;
|
|
233
|
+
}): boolean | undefined;
|
|
212
234
|
//# sourceMappingURL=tpslCalculations.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tpslCalculations.d.ts","sourceRoot":"","sources":["../../src/utils/tpslCalculations.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"tpslCalculations.d.ts","sourceRoot":"","sources":["../../src/utils/tpslCalculations.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAIhE;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,mF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AC;IACf,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IAC1C,cAAc,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;CAC7C,GAAG,OAAO,GAAG,SAAS,CAiBtB"}
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* below it; for a short, the other way round.
|
|
10
10
|
*/
|
|
11
11
|
import { TP_SL_PRECISION_CONFIG } from '../constants/perpsConfig.js';
|
|
12
|
+
import { getTriggerDirection } from './orderTypes.js';
|
|
12
13
|
import { parseFormattedPrice } from './stringParseUtils.js';
|
|
13
14
|
/**
|
|
14
15
|
* Largest stop loss RoE loss, in percent per 1x of leverage: just short of
|
|
@@ -417,4 +418,32 @@ export function calculateExpectedTriggerPnl(params) {
|
|
|
417
418
|
const { triggerPrice, entryPrice, size, closingFee } = params;
|
|
418
419
|
return (triggerPrice - entryPrice) * size - closingFee;
|
|
419
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* Whether a trigger price sits on the side its order fires from. A buy stop
|
|
423
|
+
* and a sell take profit fire as the price rises, so they trigger above the
|
|
424
|
+
* reference price; a buy take profit and a sell stop trigger below it. A
|
|
425
|
+
* trigger at the reference price is on neither side.
|
|
426
|
+
*
|
|
427
|
+
* @param params - Trigger parameters.
|
|
428
|
+
* @param params.orderType - Trigger order type.
|
|
429
|
+
* @param params.isBuy - Side of the trigger order itself (a buy closes a short).
|
|
430
|
+
* @param params.triggerPrice - Price at which the order activates.
|
|
431
|
+
* @param params.referencePrice - Current price, or the parent's price for an
|
|
432
|
+
* attached trigger.
|
|
433
|
+
* @returns Whether the trigger is on its side, or undefined when either price
|
|
434
|
+
* is missing or not a positive number.
|
|
435
|
+
*/
|
|
436
|
+
export function isTriggerPriceOnValidSide(params) {
|
|
437
|
+
const trigger = Number.parseFloat(String(params.triggerPrice));
|
|
438
|
+
const reference = Number.parseFloat(String(params.referencePrice));
|
|
439
|
+
if (!Number.isFinite(trigger) ||
|
|
440
|
+
!Number.isFinite(reference) ||
|
|
441
|
+
trigger <= 0 ||
|
|
442
|
+
reference <= 0) {
|
|
443
|
+
return undefined;
|
|
444
|
+
}
|
|
445
|
+
// A buy trigger closes a short, a sell trigger closes a long.
|
|
446
|
+
const firesAbove = isAboveReference(params.isBuy ? 'short' : 'long', getTriggerDirection(params.orderType) === 'take_profit');
|
|
447
|
+
return firesAbove ? trigger > reference : trigger < reference;
|
|
448
|
+
}
|
|
420
449
|
//# sourceMappingURL=tpslCalculations.js.map
|