@metamask-previews/perps-controller 25.0.0-preview-d8b2a69a9 → 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.
Files changed (86) hide show
  1. package/CHANGELOG.md +40 -2
  2. package/dist/constants/eventNames.d.ts +32 -0
  3. package/dist/constants/eventNames.d.ts.map +1 -1
  4. package/dist/constants/eventNames.js +38 -0
  5. package/dist/constants/eventNames.js.map +1 -1
  6. package/dist/constants/hyperLiquidConfig.d.ts +4 -0
  7. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  8. package/dist/constants/hyperLiquidConfig.js +2 -0
  9. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  10. package/dist/constants/perpsConfig.d.ts +25 -0
  11. package/dist/constants/perpsConfig.d.ts.map +1 -1
  12. package/dist/constants/perpsConfig.js +26 -0
  13. package/dist/constants/perpsConfig.js.map +1 -1
  14. package/dist/index.d.ts +13 -9
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +9 -6
  17. package/dist/index.js.map +1 -1
  18. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  19. package/dist/providers/HyperLiquidProvider.js +39 -70
  20. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  21. package/dist/providers/LighterProvider.d.ts.map +1 -1
  22. package/dist/providers/LighterProvider.js +10 -0
  23. package/dist/providers/LighterProvider.js.map +1 -1
  24. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  25. package/dist/services/HyperLiquidClientService.js +4 -5
  26. package/dist/services/HyperLiquidClientService.js.map +1 -1
  27. package/dist/services/HyperLiquidSubscriptionService.d.ts +1 -13
  28. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  29. package/dist/services/HyperLiquidSubscriptionService.js +50 -296
  30. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  31. package/dist/types/index.d.ts +18 -10
  32. package/dist/types/index.d.ts.map +1 -1
  33. package/dist/types/index.js.map +1 -1
  34. package/dist/utils/accountUtils.d.ts +10 -0
  35. package/dist/utils/accountUtils.d.ts.map +1 -1
  36. package/dist/utils/accountUtils.js +17 -0
  37. package/dist/utils/accountUtils.js.map +1 -1
  38. package/dist/utils/closeCalculations.d.ts +41 -0
  39. package/dist/utils/closeCalculations.d.ts.map +1 -1
  40. package/dist/utils/closeCalculations.js +44 -0
  41. package/dist/utils/closeCalculations.js.map +1 -1
  42. package/dist/utils/feeAmounts.d.ts +55 -0
  43. package/dist/utils/feeAmounts.d.ts.map +1 -0
  44. package/dist/utils/feeAmounts.js +92 -0
  45. package/dist/utils/feeAmounts.js.map +1 -0
  46. package/dist/utils/hyperLiquidScaleOrders.d.ts +73 -0
  47. package/dist/utils/hyperLiquidScaleOrders.d.ts.map +1 -0
  48. package/dist/utils/hyperLiquidScaleOrders.js +195 -0
  49. package/dist/utils/hyperLiquidScaleOrders.js.map +1 -0
  50. package/dist/utils/index.d.ts +13 -4
  51. package/dist/utils/index.d.ts.map +1 -1
  52. package/dist/utils/index.js +9 -2
  53. package/dist/utils/index.js.map +1 -1
  54. package/dist/utils/orderBookGrouping.d.ts +62 -1
  55. package/dist/utils/orderBookGrouping.d.ts.map +1 -1
  56. package/dist/utils/orderBookGrouping.js +96 -1
  57. package/dist/utils/orderBookGrouping.js.map +1 -1
  58. package/dist/utils/orderBookSlippage.d.ts +39 -0
  59. package/dist/utils/orderBookSlippage.d.ts.map +1 -0
  60. package/dist/utils/orderBookSlippage.js +72 -0
  61. package/dist/utils/orderBookSlippage.js.map +1 -0
  62. package/dist/utils/orderFills.d.ts +24 -0
  63. package/dist/utils/orderFills.d.ts.map +1 -0
  64. package/dist/utils/orderFills.js +71 -0
  65. package/dist/utils/orderFills.js.map +1 -0
  66. package/dist/utils/positionCalculations.d.ts +22 -0
  67. package/dist/utils/positionCalculations.d.ts.map +1 -0
  68. package/dist/utils/positionCalculations.js +54 -0
  69. package/dist/utils/positionCalculations.js.map +1 -0
  70. package/dist/utils/priceDeviation.d.ts +27 -0
  71. package/dist/utils/priceDeviation.d.ts.map +1 -0
  72. package/dist/utils/priceDeviation.js +58 -0
  73. package/dist/utils/priceDeviation.js.map +1 -0
  74. package/dist/utils/pricePrecision.d.ts +20 -0
  75. package/dist/utils/pricePrecision.d.ts.map +1 -0
  76. package/dist/utils/pricePrecision.js +52 -0
  77. package/dist/utils/pricePrecision.js.map +1 -0
  78. package/dist/utils/tpslCalculations.d.ts +22 -0
  79. package/dist/utils/tpslCalculations.d.ts.map +1 -1
  80. package/dist/utils/tpslCalculations.js +29 -0
  81. package/dist/utils/tpslCalculations.js.map +1 -1
  82. package/docs/client-contract.md +31 -8
  83. package/docs/contracts/events.md +33 -31
  84. package/docs/venues/hyperliquid/init-flow.md +8 -25
  85. package/docs/venues/lighter/capabilities.md +1 -0
  86. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"orderBookGrouping.js","sourceRoot":"","sources":["../../src/utils/orderBookGrouping.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAGpE;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,wBAAwB,CACtC,MAAiC,EACjC,QAAyB,EACzB,IAAmB;IAEnB,MAAM,IAAI,GAAG,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC;IACrC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3D,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC;IACrB,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,GAAG,EAGpB,CAAC;IAEJ,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,KAAK,CAAC,KAAK,CA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EjB,MAAM,OAAO,GAAG,CACd,MAAiC,EACjC,IAAmB,EACD,EAAE,CACpB,CAAC,QAAQ,KAAK,IAAI;QAChB,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;QACb,CAAC,CAAC,wBAAwB,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,CAAC,CACnD,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;IACxB,MAAM,IAAI,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC5C,MAAM,IAAI,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAE5C,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,KAAK,MAAM,KAAK,IAAI,CAAC,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;QACvC,MAAM,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC7C,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC3C,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,QAAQ,EAAE,CAAC;YAC/C,QAAQ,GAAG,KAAK,CAAC;QACnB,CAAC;QACD,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,GAAG,OAAO,EAAE,CAAC;YAC5C,OAAO,GAAG,IAAI,CAAC;QACjB,CAAC;IACH,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AAC3C,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\nimport { CLOSE_POSITION_CONFIG } from '../constants/perpsConfig.js';\nimport type { OrderBookData, OrderBookLevel } from '../types/index.js';\n\n/**\n * Group order-book levels into price buckets of `grouping` width. Bids round\n * down to their bucket and asks round up, so a bucket never claims a better\n * price than the orders in it. Bucketing uses exact decimal arithmetic: 100.1\n * at a grouping of 0.1 stays in the 100.1 bucket. Sizes and notionals are\n * summed per bucket and the cumulative totals rebuilt from the best price out.\n * A level with an unreadable price or size is skipped; one with an unreadable\n * notional counts `price * size`.\n *\n * @param levels - Levels for one side, in any order.\n * @param grouping - Bucket width in quote units; a non-positive or\n * non-finite value returns the levels unchanged.\n * @param side - `bid` (best first = highest) or `ask` (best first = lowest).\n * @returns Grouped levels, best price first.\n */\nexport function aggregateOrderBookLevels(\n levels: readonly OrderBookLevel[],\n grouping: number | string,\n side: 'bid' | 'ask',\n): OrderBookLevel[] {\n const step = new BigNumber(grouping);\n if (levels.length === 0 || !step.isFinite() || step.lte(0)) {\n return [...levels];\n }\n\n const buckets = new Map<\n string,\n { price: BigNumber; size: BigNumber; notional: BigNumber }\n >();\n\n for (const level of levels) {\n const price = new BigNumber(level.price);\n const size = new BigNumber(level.size);\n if (!price.isFinite() || !size.isFinite()) {\n continue;\n }\n const reportedNotional = new BigNumber(level.notional);\n const notional = reportedNotional.isFinite()\n ? reportedNotional\n : price.multipliedBy(size);\n const gridPrice = price.dividedToIntegerBy(step).multipliedBy(step);\n // Integer division truncates toward zero without rounding away the\n // remainder, even when a price sits just beside an exact grid point.\n let bucketPrice = gridPrice;\n if (side === 'bid' && gridPrice.gt(price)) {\n bucketPrice = gridPrice.minus(step);\n } else if (side === 'ask' && gridPrice.lt(price)) {\n bucketPrice = gridPrice.plus(step);\n }\n const key = bucketPrice.toFixed();\n const bucket = buckets.get(key);\n if (bucket) {\n bucket.size = bucket.size.plus(size);\n bucket.notional = bucket.notional.plus(notional);\n } else {\n buckets.set(key, { price: bucketPrice, size, notional });\n }\n }\n\n const sorted = [...buckets.values()].sort((left, right) =>\n side === 'bid'\n ? right.price.comparedTo(left.price)\n : left.price.comparedTo(right.price),\n );\n\n let total = new BigNumber(0);\n let totalNotional = new BigNumber(0);\n return sorted.map((bucket) => {\n total = total.plus(bucket.size);\n totalNotional = totalNotional.plus(bucket.notional);\n return {\n price: bucket.price.toFixed(),\n size: bucket.size.toFixed(),\n total: total.toFixed(),\n notional: bucket.notional.toFixed(CLOSE_POSITION_CONFIG.UsdDecimalPlaces),\n totalNotional: totalNotional.toFixed(\n CLOSE_POSITION_CONFIG.UsdDecimalPlaces,\n ),\n };\n });\n}\n\n/** An order book regrouped for display. */\nexport type GroupedOrderBook = {\n bids: OrderBookLevel[];\n asks: OrderBookLevel[];\n /** Largest cumulative size across both trimmed sides, for depth bars. */\n maxTotal: number;\n /** Largest single-level size across both trimmed sides. */\n maxSize: number;\n};\n\n/**\n * Regroup both sides of a book at `grouping` and trim each to `maxLevels`.\n * With a `null` grouping (the stream is already aggregated by the venue) the\n * levels are only trimmed.\n *\n * @param orderBook - Book as delivered by `subscribeToOrderBook`.\n * @param grouping - Bucket width, or `null` to keep the venue's levels.\n * @param maxLevels - Levels kept per side.\n * @returns Trimmed sides plus the depth-bar denominators.\n */\nexport function groupOrderBook(\n orderBook: Pick<OrderBookData, 'bids' | 'asks'>,\n grouping: number | string | null,\n maxLevels: number,\n): GroupedOrderBook {\n const regroup = (\n levels: readonly OrderBookLevel[],\n side: 'bid' | 'ask',\n ): OrderBookLevel[] =>\n (grouping === null\n ? [...levels]\n : aggregateOrderBookLevels(levels, grouping, side)\n ).slice(0, maxLevels);\n const bids = regroup(orderBook.bids, 'bid');\n const asks = regroup(orderBook.asks, 'ask');\n\n let maxTotal = 0;\n let maxSize = 0;\n for (const level of [...bids, ...asks]) {\n const total = Number.parseFloat(level.total);\n const size = Number.parseFloat(level.size);\n if (Number.isFinite(total) && total > maxTotal) {\n maxTotal = total;\n }\n if (Number.isFinite(size) && size > maxSize) {\n maxSize = size;\n }\n }\n\n return { bids, asks, maxTotal, maxSize };\n}\n"]}
1
+ {"version":3,"file":"orderBookGrouping.js","sourceRoot":"","sources":["../../src/utils/orderBookGrouping.ts"],"names":[],"mappings":"AAA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\nimport type {\n OrderBookData,\n OrderBookLevel,\n SubscribeOrderBookParams,\n} from '../types/index.js';\n\n/**\n * Group order-book levels into price buckets of `grouping` width. Bids round\n * down to their bucket and asks round up, so a bucket never claims a better\n * price than the orders in it. Bucketing uses exact decimal arithmetic: 100.1\n * at a grouping of 0.1 stays in the 100.1 bucket. Sizes and notionals are\n * summed per bucket and the cumulative totals rebuilt from the best price out.\n * A level with an unreadable price or size is skipped; one with an unreadable\n * notional counts `price * size`.\n *\n * @param levels - Levels for one side, in any order.\n * @param grouping - Bucket width in quote units; a non-positive or\n * non-finite value returns the levels unchanged.\n * @param side - `bid` (best first = highest) or `ask` (best first = lowest).\n * @returns Grouped levels, best price first.\n */\nexport function aggregateOrderBookLevels(\n levels: readonly OrderBookLevel[],\n grouping: number | string,\n side: 'bid' | 'ask',\n): OrderBookLevel[] {\n const step = new BigNumber(grouping);\n if (levels.length === 0 || !step.isFinite() || step.lte(0)) {\n return [...levels];\n }\n\n const buckets = new Map<\n string,\n { price: BigNumber; size: BigNumber; notional: BigNumber }\n >();\n\n for (const level of levels) {\n const price = new BigNumber(level.price);\n const size = new BigNumber(level.size);\n if (!price.isFinite() || !size.isFinite()) {\n continue;\n }\n const reportedNotional = new BigNumber(level.notional);\n const notional = reportedNotional.isFinite()\n ? reportedNotional\n : price.multipliedBy(size);\n const gridPrice = price.dividedToIntegerBy(step).multipliedBy(step);\n // Integer division truncates toward zero without rounding away the\n // remainder, even when a price sits just beside an exact grid point.\n let bucketPrice = gridPrice;\n if (side === 'bid' && gridPrice.gt(price)) {\n bucketPrice = gridPrice.minus(step);\n } else if (side === 'ask' && gridPrice.lt(price)) {\n bucketPrice = gridPrice.plus(step);\n }\n const key = bucketPrice.toFixed();\n const bucket = buckets.get(key);\n if (bucket) {\n bucket.size = bucket.size.plus(size);\n bucket.notional = bucket.notional.plus(notional);\n } else {\n buckets.set(key, { price: bucketPrice, size, notional });\n }\n }\n\n const sorted = [...buckets.values()].sort((left, right) =>\n side === 'bid'\n ? right.price.comparedTo(left.price)\n : left.price.comparedTo(right.price),\n );\n\n let total = new BigNumber(0);\n let totalNotional = new BigNumber(0);\n return sorted.map((bucket) => {\n total = total.plus(bucket.size);\n totalNotional = totalNotional.plus(bucket.notional);\n return {\n price: bucket.price.toFixed(),\n size: bucket.size.toFixed(),\n total: total.toFixed(),\n notional: bucket.notional.toFixed(CLOSE_POSITION_CONFIG.UsdDecimalPlaces),\n totalNotional: totalNotional.toFixed(\n CLOSE_POSITION_CONFIG.UsdDecimalPlaces,\n ),\n };\n });\n}\n\n/** An order book regrouped for display. */\nexport type GroupedOrderBook = {\n bids: OrderBookLevel[];\n asks: OrderBookLevel[];\n /** Largest cumulative size across both trimmed sides, for depth bars. */\n maxTotal: number;\n /** Largest single-level size across both trimmed sides. */\n maxSize: number;\n};\n\n/**\n * Regroup both sides of a book at `grouping` and trim each to `maxLevels`.\n * With a `null` grouping (the stream is already aggregated by the venue) the\n * levels are only trimmed.\n *\n * @param orderBook - Book as delivered by `subscribeToOrderBook`.\n * @param grouping - Bucket width, or `null` to keep the venue's levels.\n * @param maxLevels - Levels kept per side.\n * @returns Trimmed sides plus the depth-bar denominators.\n */\nexport function groupOrderBook(\n orderBook: Pick<OrderBookData, 'bids' | 'asks'>,\n grouping: number | string | null,\n maxLevels: number,\n): GroupedOrderBook {\n const regroup = (\n levels: readonly OrderBookLevel[],\n side: 'bid' | 'ask',\n ): OrderBookLevel[] =>\n (grouping === null\n ? [...levels]\n : aggregateOrderBookLevels(levels, grouping, side)\n ).slice(0, maxLevels);\n const bids = regroup(orderBook.bids, 'bid');\n const asks = regroup(orderBook.asks, 'ask');\n\n let maxTotal = 0;\n let maxSize = 0;\n for (const level of [...bids, ...asks]) {\n const total = Number.parseFloat(level.total);\n const size = Number.parseFloat(level.size);\n if (Number.isFinite(total) && total > maxTotal) {\n maxTotal = total;\n }\n if (Number.isFinite(size) && size > maxSize) {\n maxSize = size;\n }\n }\n\n return { bids, asks, maxTotal, maxSize };\n}\n\n/**\n * Grouping widths offered for a book at `midPrice`: a decade four below the\n * price's own, times 1, 2, 5, 10, 100 and 1000. Each width is rounded to\n * `DECIMAL_PRECISION_CONFIG.MaxPriceDecimals` decimals and duplicates are\n * dropped, so float noise never shows as a separate option and no width is\n * finer than the smallest price step a market can quote.\n *\n * @param midPrice - Mid price of the book.\n * @returns Grouping widths, ascending; `ORDER_BOOK_GROUPING_CONFIG.FallbackOptions`\n * when the mid price is not a positive number.\n */\nexport function calculateOrderBookGroupingOptions(midPrice: number): number[] {\n if (!Number.isFinite(midPrice) || midPrice <= 0) {\n return [...ORDER_BOOK_GROUPING_CONFIG.FallbackOptions];\n }\n const base =\n 10 **\n (Math.floor(Math.log10(midPrice)) -\n ORDER_BOOK_GROUPING_CONFIG.DecadeOffset);\n const options = ORDER_BOOK_GROUPING_CONFIG.Multipliers.map((multiplier) =>\n Number(\n (base * multiplier).toFixed(DECIMAL_PRECISION_CONFIG.MaxPriceDecimals),\n ),\n ).filter((option) => option > 0);\n const unique = Array.from(new Set(options));\n return unique.length > 0\n ? unique\n : [10 ** -DECIMAL_PRECISION_CONFIG.MaxPriceDecimals];\n}\n\n/**\n * The grouping width a book opens at.\n *\n * @param options - Widths from {@link calculateOrderBookGroupingOptions}.\n * @returns The option at `ORDER_BOOK_GROUPING_CONFIG.DefaultOptionIndex`, else\n * the middle option, or undefined for an empty list.\n */\nexport function selectDefaultOrderBookGrouping(\n options: readonly number[],\n): number | undefined {\n return (\n options[ORDER_BOOK_GROUPING_CONFIG.DefaultOptionIndex] ??\n options[Math.floor(options.length / 2)]\n );\n}\n\n/** Book-stream aggregation for a grouping width (`SubscribeOrderBookParams`). */\nexport type OrderBookAggregationParams = {\n nSigFigs: NonNullable<SubscribeOrderBookParams['nSigFigs']>;\n mantissa?: SubscribeOrderBookParams['mantissa'];\n};\n\n/**\n * The `nSigFigs` and `mantissa` to subscribe a book at so the venue already\n * aggregates it at `grouping`. Widths finer than five significant figures of\n * the price use five, with a mantissa of 2 or 5 for widths starting with those\n * digits. These are Hyperliquid's book-stream parameters; on a venue that\n * streams raw levels, group client-side with {@link groupOrderBook} instead.\n *\n * @param grouping - Grouping width in quote units.\n * @param price - Reference price, usually the mid.\n * @returns The aggregation; five significant figures when either input is not\n * a positive number.\n */\nexport function calculateOrderBookAggregationParams(\n grouping: number,\n price: number,\n): OrderBookAggregationParams {\n const { MinSignificantFigures, MaxSignificantFigures } =\n ORDER_BOOK_GROUPING_CONFIG;\n if (\n !Number.isFinite(price) ||\n !Number.isFinite(grouping) ||\n price <= 0 ||\n grouping <= 0\n ) {\n return { nSigFigs: MaxSignificantFigures };\n }\n const groupingMagnitude = Math.floor(Math.log10(grouping));\n const significantFigures =\n Math.floor(Math.log10(price)) - groupingMagnitude + 1;\n if (significantFigures >= MaxSignificantFigures) {\n const firstDigit = Math.floor(grouping / 10 ** groupingMagnitude);\n if (firstDigit <= 1) {\n return { nSigFigs: MaxSignificantFigures };\n }\n return {\n nSigFigs: MaxSignificantFigures,\n mantissa: firstDigit <= 2 ? 2 : 5,\n };\n }\n return {\n nSigFigs: Math.max(\n MinSignificantFigures,\n significantFigures,\n ) as OrderBookAggregationParams['nSigFigs'],\n };\n}\n\n/** Top-of-book spread from {@link calculateOrderBookSpread}. */\nexport type OrderBookSpread = {\n /** Best ask minus best bid, in quote units. */\n spread: number;\n /** Midpoint of the best bid and ask. */\n midPrice: number;\n /** Spread as a percent of the mid price (0.2 = 0.2%). */\n spreadPercentage: number;\n};\n\n/**\n * Spread, mid price and spread percent from the best bid and ask, in exact\n * decimal arithmetic.\n *\n * @param params - Top of book.\n * @param params.bestBid - Best bid price.\n * @param params.bestAsk - Best ask price.\n * @returns The spread, or undefined when either side is missing or not a\n * positive number.\n */\nexport function calculateOrderBookSpread(params: {\n bestBid: number | string | undefined;\n bestAsk: number | string | undefined;\n}): OrderBookSpread | undefined {\n const bid = new BigNumber(params.bestBid ?? Number.NaN);\n const ask = new BigNumber(params.bestAsk ?? Number.NaN);\n if (!bid.isFinite() || !ask.isFinite() || bid.lte(0) || ask.lte(0)) {\n return undefined;\n }\n const spread = ask.minus(bid);\n const midPrice = ask.plus(bid).dividedBy(2);\n return {\n spread: spread.toNumber(),\n midPrice: midPrice.toNumber(),\n spreadPercentage: spread.dividedBy(midPrice).multipliedBy(100).toNumber(),\n };\n}\n"]}
@@ -0,0 +1,39 @@
1
+ import type { OrderBookData } from '../types/index.js';
2
+ /** Inputs to {@link estimateOrderBookSlippage}. */
3
+ export type OrderBookSlippageParams = {
4
+ /** Book to sweep, as delivered by `subscribeToOrderBook`. */
5
+ orderBook: Pick<OrderBookData, 'bids' | 'asks' | 'midPrice'>;
6
+ /** A buy sweeps the asks, a sell the bids. */
7
+ isBuy: boolean;
8
+ /** Order size in base units. Takes precedence over `sizeUsd`. */
9
+ size?: number | string;
10
+ /** Order value in USD, converted to a size at the reference price. */
11
+ sizeUsd?: number;
12
+ /** Price slippage is measured from. Defaults to the book's mid price. */
13
+ referencePrice?: number | string;
14
+ };
15
+ /** Result of {@link estimateOrderBookSlippage}. Undefined fields are unknown. */
16
+ export type OrderBookSlippageEstimate = {
17
+ /** Average fill price's distance from the reference price, in basis points. */
18
+ estimatedSlippageBps: number | undefined;
19
+ /** Last level the order reaches, as distance from the reference, in basis points. */
20
+ worstSlippageBps: number | undefined;
21
+ /**
22
+ * Whether the visible book holds the whole order. Depth only: to check a
23
+ * max-slippage cap, compare `worstSlippageBps` with it.
24
+ */
25
+ canFill: boolean | undefined;
26
+ };
27
+ /**
28
+ * Slippage a market order would take by sweeping the visible book: the
29
+ * volume-weighted fill price and the last level reached, each measured from
30
+ * the reference price in basis points against the order's side and floored at
31
+ * zero.
32
+ *
33
+ * @param params - See {@link OrderBookSlippageParams}.
34
+ * @returns The estimate. `canFill` is false, with both slippages undefined,
35
+ * when the visible levels cannot hold the order; every field is undefined
36
+ * when the size or reference price is missing or not a positive number.
37
+ */
38
+ export declare function estimateOrderBookSlippage(params: OrderBookSlippageParams): OrderBookSlippageEstimate;
39
+ //# sourceMappingURL=orderBookSlippage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orderBookSlippage.d.ts","sourceRoot":"","sources":["../../src/utils/orderBookSlippage.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEvD,mDAAmD;AACnD,MAAM,MAAM,uBAAuB,GAAG;IACpC,6DAA6D;IAC7D,SAAS,EAAE,IAAI,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,GAAG,UAAU,CAAC,CAAC;IAC7D,8CAA8C;IAC9C,KAAK,EAAE,OAAO,CAAC;IACf,iEAAiE;IACjE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,sEAAsE;IACtE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,cAAc,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;CAClC,CAAC;AAEF,iFAAiF;AACjF,MAAM,MAAM,yBAAyB,GAAG;IACtC,+EAA+E;IAC/E,oBAAoB,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,qFAAqF;IACrF,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC;;;OAGG;IACH,OAAO,EAAE,OAAO,GAAG,SAAS,CAAC;CAC9B,CAAC;AAUF;;;;;;;;;;GAUG;AACH,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,uBAAuB,GAC9B,yBAAyB,CA0D3B"}
@@ -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,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;QAC9C,OAAO,eAAe,EAAE,CAAC;IAC3B,CAAC;IACD,MAAM,MAAM,GACV,MAAM,CAAC,IAAI,KAAK,SAAS;QACvB,CAAC,CAAC,IAAI,SAAS,CAAC,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC;QAClE,CAAC,CAAC,IAAI,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC;IACvC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;QACxC,OAAO,eAAe,EAAE,CAAC;IAC3B,CAAC;IAED,mEAAmE;IACnE,IAAI,MAAM,GAAG,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;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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;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,wBAAwB,CAUtC,QAAsB,EAAE,KAAsB;IAC9C,MAAM,YAAY,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACtD,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;IAC1D,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC9C,MAAM,SAAS,GAAG,oBAAoB,CAAC,IAAI,CAAC,CAAC;IAC7C,IACE,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC;QAC9B,YAAY,IAAI,CAAC;QACjB,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC5B,UAAU,IAAI,CAAC;QACf,SAAS,KAAK,SAAS,EACvB,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,MAAM,UAAU,GAAG,0BAA0B,CAAC,YAAY,CAAC,QAAQ,EAAE,EAAE;QACrE,YAAY;QACZ,SAAS;QACT,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,KAAK;QACjC,UAAU;KACX,CAAC,CAAC;IACH,OAAO;QACL,GAAG,QAAQ;QACX,aAAa,EAAE,CAAC,CAAC,YAAY,GAAG,UAAU,CAAC,GAAG,IAAI,CAAC,CAAC,QAAQ,EAAE;QAC9D,cAAc,EAAE,UAAU;YACxB,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,GAAG,GAAG,CAAC,CAAC,QAAQ,EAAE;YAClD,CAAC,CAAC,QAAQ,CAAC,cAAc;QAC3B,aAAa,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,YAAY,CAAC,CAAC,QAAQ,EAAE;KAC1D,CAAC;AACJ,CAAC","sourcesContent":["import type { Position } from '../types/index.js';\nimport { calculateSignedRoEForPrice } from './tpslCalculations.js';\n\n/**\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;QA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,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