@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.
Files changed (108) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/PerpsController-method-action-types.d.ts +17 -7
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +20 -10
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +160 -97
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/eventNames.d.ts +32 -0
  10. package/dist/constants/eventNames.d.ts.map +1 -1
  11. package/dist/constants/eventNames.js +38 -0
  12. package/dist/constants/eventNames.js.map +1 -1
  13. package/dist/constants/hyperLiquidConfig.d.ts +4 -0
  14. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  15. package/dist/constants/hyperLiquidConfig.js +2 -0
  16. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  17. package/dist/constants/lighterConfig.js +2 -2
  18. package/dist/constants/lighterConfig.js.map +1 -1
  19. package/dist/constants/perpsConfig.d.ts +25 -0
  20. package/dist/constants/perpsConfig.d.ts.map +1 -1
  21. package/dist/constants/perpsConfig.js +26 -0
  22. package/dist/constants/perpsConfig.js.map +1 -1
  23. package/dist/index.d.ts +16 -11
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +10 -6
  26. package/dist/index.js.map +1 -1
  27. package/dist/providers/AggregatedPerpsProvider.d.ts +14 -1
  28. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  29. package/dist/providers/AggregatedPerpsProvider.js +46 -6
  30. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  31. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  32. package/dist/providers/HyperLiquidProvider.js +4 -10
  33. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  34. package/dist/providers/LighterProvider.d.ts.map +1 -1
  35. package/dist/providers/LighterProvider.js +10 -0
  36. package/dist/providers/LighterProvider.js.map +1 -1
  37. package/dist/services/MarketDataService.d.ts +5 -2
  38. package/dist/services/MarketDataService.d.ts.map +1 -1
  39. package/dist/services/MarketDataService.js +211 -55
  40. package/dist/services/MarketDataService.js.map +1 -1
  41. package/dist/services/ServiceContext.d.ts +12 -7
  42. package/dist/services/ServiceContext.d.ts.map +1 -1
  43. package/dist/services/ServiceContext.js.map +1 -1
  44. package/dist/services/TerminalMarketService.d.ts.map +1 -1
  45. package/dist/services/TerminalMarketService.js +64 -22
  46. package/dist/services/TerminalMarketService.js.map +1 -1
  47. package/dist/types/index.d.ts +42 -4
  48. package/dist/types/index.d.ts.map +1 -1
  49. package/dist/types/index.js.map +1 -1
  50. package/dist/utils/accountUtils.d.ts +10 -0
  51. package/dist/utils/accountUtils.d.ts.map +1 -1
  52. package/dist/utils/accountUtils.js +17 -0
  53. package/dist/utils/accountUtils.js.map +1 -1
  54. package/dist/utils/closeCalculations.d.ts +41 -0
  55. package/dist/utils/closeCalculations.d.ts.map +1 -1
  56. package/dist/utils/closeCalculations.js +44 -0
  57. package/dist/utils/closeCalculations.js.map +1 -1
  58. package/dist/utils/feeAmounts.d.ts +55 -0
  59. package/dist/utils/feeAmounts.d.ts.map +1 -0
  60. package/dist/utils/feeAmounts.js +92 -0
  61. package/dist/utils/feeAmounts.js.map +1 -0
  62. package/dist/utils/hyperLiquidScaleOrders.d.ts +73 -0
  63. package/dist/utils/hyperLiquidScaleOrders.d.ts.map +1 -0
  64. package/dist/utils/hyperLiquidScaleOrders.js +195 -0
  65. package/dist/utils/hyperLiquidScaleOrders.js.map +1 -0
  66. package/dist/utils/index.d.ts +13 -4
  67. package/dist/utils/index.d.ts.map +1 -1
  68. package/dist/utils/index.js +9 -2
  69. package/dist/utils/index.js.map +1 -1
  70. package/dist/utils/marketUtils.d.ts +60 -1
  71. package/dist/utils/marketUtils.d.ts.map +1 -1
  72. package/dist/utils/marketUtils.js +151 -3
  73. package/dist/utils/marketUtils.js.map +1 -1
  74. package/dist/utils/orderBookGrouping.d.ts +62 -1
  75. package/dist/utils/orderBookGrouping.d.ts.map +1 -1
  76. package/dist/utils/orderBookGrouping.js +96 -1
  77. package/dist/utils/orderBookGrouping.js.map +1 -1
  78. package/dist/utils/orderBookSlippage.d.ts +39 -0
  79. package/dist/utils/orderBookSlippage.d.ts.map +1 -0
  80. package/dist/utils/orderBookSlippage.js +72 -0
  81. package/dist/utils/orderBookSlippage.js.map +1 -0
  82. package/dist/utils/orderFills.d.ts +24 -0
  83. package/dist/utils/orderFills.d.ts.map +1 -0
  84. package/dist/utils/orderFills.js +71 -0
  85. package/dist/utils/orderFills.js.map +1 -0
  86. package/dist/utils/positionCalculations.d.ts +22 -0
  87. package/dist/utils/positionCalculations.d.ts.map +1 -0
  88. package/dist/utils/positionCalculations.js +54 -0
  89. package/dist/utils/positionCalculations.js.map +1 -0
  90. package/dist/utils/priceDeviation.d.ts +27 -0
  91. package/dist/utils/priceDeviation.d.ts.map +1 -0
  92. package/dist/utils/priceDeviation.js +58 -0
  93. package/dist/utils/priceDeviation.js.map +1 -0
  94. package/dist/utils/pricePrecision.d.ts +20 -0
  95. package/dist/utils/pricePrecision.d.ts.map +1 -0
  96. package/dist/utils/pricePrecision.js +52 -0
  97. package/dist/utils/pricePrecision.js.map +1 -0
  98. package/dist/utils/tpslCalculations.d.ts +22 -0
  99. package/dist/utils/tpslCalculations.d.ts.map +1 -1
  100. package/dist/utils/tpslCalculations.js +29 -0
  101. package/dist/utils/tpslCalculations.js.map +1 -1
  102. package/docs/architecture.md +9 -1
  103. package/docs/client-contract.md +31 -8
  104. package/docs/contracts/events.md +33 -31
  105. package/docs/contracts/feature-flags.md +5 -5
  106. package/docs/venues/lighter/capabilities.md +5 -0
  107. package/docs/venues/lighter/signer-provenance.md +52 -0
  108. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,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AC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,KAAK,CAAC;IAC1D,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC;QACzC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE;QACpB,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACxC,IAAI,OAAO,KAAK,CAAC,EAAE,CAAC;QAClB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,GAAG,GAAG,CAAC,EAAE,CAAC;QACZ,OAAO,IAAI,SAAS,EAAE,CAAC;IACzB,CAAC;IACD,OAAO,MAAM,CAAC,CAAC,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9C,CAAC;AAgBD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,2BAA2B,CACzC,MAAgC;IAEhC,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;IAC9D,OAAO,CAAC,YAAY,GAAG,UAAU,CAAC,GAAG,IAAI,GAAG,UAAU,CAAC;AACzD,CAAC","sourcesContent":["/**\n * Take profit / stop loss calculations shared by the MetaMask clients.\n *\n * RoE (return on equity) is signed: positive at a gain and negative at a loss,\n * for a take profit and a stop loss alike, so a stop loss can sit at a gain\n * and a take profit at a loss.\n *\n * For a long, a take profit sits above the reference price and a stop loss\n * below it; for a short, the other way round.\n */\nimport { TP_SL_PRECISION_CONFIG } from '../constants/perpsConfig.js';\nimport type { OrderDirection } from '../types/index.js';\nimport { parseFormattedPrice } from './stringParseUtils.js';\n\n/**\n * Price context for the TP/SL calculations and checks.\n */\nexport type TpslCalculationParams = {\n /** Reference price: the current market price, or a pending limit order's price. */\n currentPrice: number;\n /** Position or order side. */\n direction?: OrderDirection;\n /**\n * Position leverage. The RoE calculations need it and return '' while it is\n * unknown: they never assume 1x.\n */\n leverage?: number;\n /**\n * Entry price of an existing position. RoE is measured from it when set,\n * else from `currentPrice`; a set entry price that is not finite and above\n * zero makes the RoE calculations return ''.\n */\n entryPrice?: number;\n /** Liquidation price that a stop loss must stay clear of. */\n liquidationPrice?: string;\n};\n\n/**\n * Largest stop loss RoE loss, in percent per 1x of leverage: just short of\n * the 100% that would price the stop at zero.\n */\nconst MAX_STOP_LOSS_ROE_PER_LEVERAGE = 99;\n\n/**\n * Upper bound of a stop loss percentage, whatever the leverage.\n */\nconst MAX_STOP_LOSS_PERCENTAGE = 999;\n\n/**\n * Whether a trigger on this side gains as the price rises: a long's take\n * profit or a short's stop loss.\n *\n * @param direction - The position side.\n * @param isProfit - True for a take profit, false for a stop loss.\n * @returns True when the trigger sits above the reference price.\n */\nfunction isAboveReference(\n direction: OrderDirection | undefined,\n isProfit: boolean,\n): boolean {\n return (direction === 'long') === isProfit;\n}\n\n/**\n * Whether a value is a finite number above zero.\n *\n * @param value - The value to check.\n * @returns True for a finite number above zero.\n */\nfunction isPositiveFinite(value: number | undefined): value is number {\n return value !== undefined && Number.isFinite(value) && value > 0;\n}\n\n/**\n * Decimal places for a trigger price, from `TP_SL_PRECISION_CONFIG`: more for\n * low-priced assets.\n *\n * @param price - The trigger price.\n * @returns The number of decimal places to keep.\n */\nfunction getTriggerPriceDecimals(price: number): number {\n const band = TP_SL_PRECISION_CONFIG.TriggerPriceBands.find(\n ({ BelowPrice }) => price < BelowPrice,\n );\n return band?.Decimals ?? TP_SL_PRECISION_CONFIG.TriggerPriceDefaultDecimals;\n}\n\n/**\n * A calculated trigger price as a string, with the decimals its price range\n * needs and no trailing zeros. Rounding to the asset's submission precision\n * is left to the provider.\n *\n * @param price - The calculated trigger price.\n * @returns The trigger price as a string, or '' when it is not finite.\n */\nfunction toTriggerPriceString(price: number): string {\n if (!Number.isFinite(price)) {\n return '';\n }\n return Number.parseFloat(\n price.toFixed(getTriggerPriceDecimals(price)),\n ).toString();\n}\n\n/**\n * Price that RoE is measured from: the entry price of an existing position,\n * else the current price. Only an omitted entry price falls back; a set one\n * that is not usable (0, NaN) stays as is, so the callers' checks reject it.\n *\n * @param params - Price context.\n * @returns The base price.\n */\nfunction getBasePrice(params: TpslCalculationParams): number {\n return params.entryPrice ?? params.currentPrice;\n}\n\n/**\n * Signed RoE of a trigger price as a number.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @param params - Price context.\n * @returns The RoE in percent, or undefined without a usable price, side or\n * leverage: each price and the leverage must be finite and above zero.\n */\nfunction getSignedRoE(\n price: string,\n params: TpslCalculationParams,\n): number | undefined {\n const { direction, leverage } = params;\n const basePrice = getBasePrice(params);\n if (\n !price ||\n !direction ||\n !isPositiveFinite(basePrice) ||\n !isPositiveFinite(leverage)\n ) {\n return undefined;\n }\n const triggerPrice = parseFormattedPrice(price);\n if (!isPositiveFinite(triggerPrice)) {\n return undefined;\n }\n const roe = ((triggerPrice - basePrice) / basePrice) * leverage * 100;\n return direction === 'long' ? roe : -roe;\n}\n\n/**\n * Trigger price for a signed RoE. RoE is measured from the entry price when\n * set, else from the current price; the price moves by RoE / leverage.\n *\n * A stop loss's loss is capped at 99% of the margin per 1x of leverage, so a\n * stop loss at a loss is never priced at or below zero. Any other RoE that\n * moves the price down by 100% or more (a large short gain, or a long take\n * profit at a large loss) gives a price at or below zero, returned as is;\n * `isPositiveTriggerPrice` rejects it.\n *\n * @param roePercentage - Signed RoE in percent (10 for +10%, -5 for -5%).\n * @param isProfit - True for a take profit, false for a stop loss.\n * @param params - Price context.\n * @returns The trigger price as a string, or '' without a usable price, side,\n * leverage or RoE: the base price and leverage must be finite and above zero,\n * and the RoE finite.\n * @example calculatePriceForRoE(-10, false, { currentPrice: 2500, direction: 'long', leverage: 2 }) => '2375'\n */\nexport function calculatePriceForRoE(\n roePercentage: number,\n isProfit: boolean,\n params: TpslCalculationParams,\n): string {\n const { direction, leverage } = params;\n const basePrice = getBasePrice(params);\n if (\n !direction ||\n !isPositiveFinite(basePrice) ||\n !isPositiveFinite(leverage) ||\n !Number.isFinite(roePercentage)\n ) {\n return '';\n }\n\n const roe = isProfit\n ? roePercentage\n : Math.max(roePercentage, -leverage * MAX_STOP_LOSS_ROE_PER_LEVERAGE);\n const priceChangeRatio = roe / (leverage * 100);\n return toTriggerPriceString(\n basePrice *\n (direction === 'long' ? 1 + priceChangeRatio : 1 - priceChangeRatio),\n );\n}\n\n/**\n * Signed RoE of a trigger price: positive at a gain and negative at a loss,\n * for a take profit or a stop loss alike. Use it for a TP/SL bound to an open\n * position.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @param params - Price context.\n * @returns The RoE in percent with `TP_SL_PRECISION_CONFIG.PercentageDecimals`\n * decimals, or '' without a usable price, side or leverage.\n * @example calculateSignedRoEForPrice('2375', { currentPrice: 2500, direction: 'long', leverage: 2 }) => '-10.00'\n */\nexport function calculateSignedRoEForPrice(\n price: string,\n params: TpslCalculationParams,\n): string {\n return (\n getSignedRoE(price, params)?.toFixed(\n TP_SL_PRECISION_CONFIG.PercentageDecimals,\n ) ?? ''\n );\n}\n\n/**\n * RoE of a trigger price on its own side: a take profit's gain (zero or\n * more) and a stop loss's loss (zero or less). A trigger on the wrong side\n * reads as zero.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @param isProfit - True for a take profit, false for a stop loss.\n * @param params - Price context.\n * @returns The RoE in percent with `TP_SL_PRECISION_CONFIG.PercentageDecimals`\n * decimals, or '' without a usable price, side or leverage.\n * @example calculateRoEForPrice('2375', true, { currentPrice: 2500, direction: 'long', leverage: 2 }) => '0.00'\n */\nexport function calculateRoEForPrice(\n price: string,\n isProfit: boolean,\n params: TpslCalculationParams,\n): string {\n const roe = getSignedRoE(price, params);\n if (roe === undefined) {\n return '';\n }\n const isWrongSide = isProfit ? roe < 0 : roe > 0;\n return (isWrongSide ? 0 : roe).toFixed(\n TP_SL_PRECISION_CONFIG.PercentageDecimals,\n );\n}\n\n/**\n * Trigger price for a price move from the current price, in the trigger's\n * profitable or losing direction.\n *\n * @param percentage - Price move in percent.\n * @param isProfit - True for a take profit, false for a stop loss.\n * @param params - Price context.\n * @returns The trigger price, with the decimals its price range needs (see\n * `TP_SL_PRECISION_CONFIG`), or '' without a current price, side or finite\n * percentage.\n * @example calculatePriceForPercentage(10, true, { currentPrice: 0.001, direction: 'long' }) => '0.0011'\n */\nexport function calculatePriceForPercentage(\n percentage: number,\n isProfit: boolean,\n params: TpslCalculationParams,\n): string {\n const { currentPrice, direction } = params;\n if (!currentPrice || !direction) {\n return '';\n }\n const move = percentage / 100;\n const multiplier = isAboveReference(direction, isProfit)\n ? 1 + move\n : 1 - move;\n return toTriggerPriceString(currentPrice * multiplier);\n}\n\n/**\n * Price move from the current price to a trigger price, negative when the\n * trigger sits on the wrong side for a take profit or stop loss.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @param isProfit - True for a take profit, false for a stop loss.\n * @param params - Price context.\n * @returns The move in percent with `TP_SL_PRECISION_CONFIG.PercentageDecimals`\n * decimals, or '' without a usable price or side: both prices must be finite.\n */\nexport function calculatePercentageForPrice(\n price: string,\n isProfit: boolean,\n params: TpslCalculationParams,\n): string {\n const { currentPrice, direction } = params;\n if (!currentPrice || !Number.isFinite(currentPrice) || !direction || !price) {\n return '';\n }\n const triggerPrice = parseFormattedPrice(price);\n if (!Number.isFinite(triggerPrice)) {\n return '';\n }\n const priceDiff = triggerPrice - currentPrice;\n const percentage = Math.abs((priceDiff / currentPrice) * 100).toFixed(\n TP_SL_PRECISION_CONFIG.PercentageDecimals,\n );\n const isExpectedSide = isAboveReference(direction, isProfit)\n ? priceDiff > 0\n : priceDiff < 0;\n return isExpectedSide ? percentage : `-${percentage}`;\n}\n\n/**\n * Largest stop loss percentage for a leverage: 99% per 1x, at most 999%.\n *\n * @param leverage - The position leverage.\n * @returns The maximum stop loss percentage.\n */\nexport function getMaxStopLossPercentage(leverage: number): number {\n return Math.min(\n leverage * MAX_STOP_LOSS_ROE_PER_LEVERAGE,\n MAX_STOP_LOSS_PERCENTAGE,\n );\n}\n\n/**\n * Whether a stop loss percentage is above zero and within the leverage's\n * maximum.\n *\n * @param percentage - The stop loss percentage, as a positive number.\n * @param leverage - The position leverage.\n * @returns True when the percentage is allowed.\n */\nexport function isValidStopLossPercentage(\n percentage: number,\n leverage: number,\n): boolean {\n return percentage > 0 && percentage <= getMaxStopLossPercentage(leverage);\n}\n\n/**\n * Whether a trigger price can be sent at all: the venue rejects a trigger at\n * or below zero. Direction checks alone would let a negative price through.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @returns False only when the price parses to a number at or below zero.\n */\nexport function isPositiveTriggerPrice(price?: string): boolean {\n if (!price) {\n return true;\n }\n const triggerPrice = parseFormattedPrice(price);\n return Number.isNaN(triggerPrice) || triggerPrice > 0;\n}\n\n/**\n * Whether a trigger price is positive and on its side of the reference price.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @param params - Price context.\n * @param isProfit - True for a take profit, false for a stop loss.\n * @returns False for a non-positive price or one on the wrong side; true\n * when the price, reference price or side is missing.\n */\nfunction isTriggerPriceOnSide(\n price: string,\n params: TpslCalculationParams,\n isProfit: boolean,\n): boolean {\n const { currentPrice, direction } = params;\n if (!isPositiveTriggerPrice(price)) {\n return false;\n }\n if (!currentPrice || !direction || !price) {\n return true;\n }\n const triggerPrice = parseFormattedPrice(price);\n if (Number.isNaN(triggerPrice)) {\n return true;\n }\n return isAboveReference(direction, isProfit)\n ? triggerPrice > currentPrice\n : triggerPrice < currentPrice;\n}\n\n/**\n * Whether a take profit price is positive and above the reference price for a\n * long, below it for a short.\n *\n * @param price - The take profit price; may carry `$` or `,` formatting.\n * @param params - Price context.\n * @returns False for an invalid price; true when the price, reference price or\n * side is missing.\n */\nexport function isValidTakeProfitPrice(\n price: string,\n params: TpslCalculationParams,\n): boolean {\n return isTriggerPriceOnSide(price, params, true);\n}\n\n/**\n * Whether a stop loss price is positive and below the reference price for a\n * long, above it for a short.\n *\n * @param price - The stop loss price; may carry `$` or `,` formatting.\n * @param params - Price context.\n * @returns False for an invalid price; true when the price, reference price or\n * side is missing.\n */\nexport function isValidStopLossPrice(\n price: string,\n params: TpslCalculationParams,\n): boolean {\n return isTriggerPriceOnSide(price, params, false);\n}\n\n/**\n * Whether a stop loss triggers before liquidation: above the liquidation price\n * for a long, below it for a short.\n *\n * @param price - The stop loss price; may carry `$` or `,` formatting.\n * @param liquidationPrice - The liquidation price; may carry formatting.\n * @param direction - The position side.\n * @returns False when the stop loss is at or beyond liquidation; true when an\n * input is missing or not a number.\n */\nexport function isStopLossSafeFromLiquidation(\n price?: string,\n liquidationPrice?: string,\n direction?: OrderDirection,\n): boolean {\n if (!liquidationPrice || !direction || !price) {\n return true;\n }\n const stopLossPrice = parseFormattedPrice(price);\n const liquidation = parseFormattedPrice(liquidationPrice);\n if (Number.isNaN(stopLossPrice) || Number.isNaN(liquidation)) {\n return true;\n }\n return direction === 'long'\n ? stopLossPrice > liquidation\n : stopLossPrice < liquidation;\n}\n\n/**\n * Outcome of `validateTPSLPrices`. `unresolved` means a set trigger could not\n * be checked: the reference price, the side or a readable liquidation price\n * is missing. It is not a pass.\n */\nexport type TpslValidationResult = 'valid' | 'invalid' | 'unresolved';\n\n/**\n * Whether a trigger price reads as a finite number above zero.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @returns True for a usable price.\n */\nfunction isReadableTriggerPrice(price: string): boolean {\n return isPositiveFinite(parseFormattedPrice(price));\n}\n\n/**\n * Check a take profit and stop loss pair: each set price must read as a\n * positive number, sit on its side of the reference price, and the stop loss\n * must trigger before liquidation. An unset trigger needs no check. The\n * liquidation check runs only when `params.liquidationPrice` is set.\n *\n * A failure found without the reference price (an unreadable or non-positive\n * price, a stop loss beyond liquidation) is `invalid` even when the rest of the\n * context is missing.\n *\n * @param takeProfitPrice - The take profit price, if any.\n * @param stopLossPrice - The stop loss price, if any.\n * @param params - Price context, including the liquidation price.\n * @returns `valid` when every set price passes, `invalid` when one fails, and\n * `unresolved` when a set price cannot be checked.\n */\nexport function validateTPSLPrices(\n takeProfitPrice: string | undefined,\n stopLossPrice: string | undefined,\n params: TpslCalculationParams,\n): TpslValidationResult {\n const { currentPrice, direction, liquidationPrice } = params;\n if (!takeProfitPrice && !stopLossPrice) {\n return 'valid';\n }\n if (\n (takeProfitPrice && !isReadableTriggerPrice(takeProfitPrice)) ||\n (stopLossPrice && !isReadableTriggerPrice(stopLossPrice)) ||\n !isStopLossSafeFromLiquidation(stopLossPrice, liquidationPrice, direction)\n ) {\n return 'invalid';\n }\n if (\n !direction ||\n !Number.isFinite(currentPrice) ||\n currentPrice <= 0 ||\n (stopLossPrice &&\n liquidationPrice &&\n !Number.isFinite(parseFormattedPrice(liquidationPrice)))\n ) {\n return 'unresolved';\n }\n const isOnSide =\n (!takeProfitPrice || isValidTakeProfitPrice(takeProfitPrice, params)) &&\n (!stopLossPrice || isValidStopLossPrice(stopLossPrice, params));\n return isOnSide ? 'valid' : 'invalid';\n}\n\n/**\n * Format a RoE percentage for display, without the `%` sign: rounded to\n * `TP_SL_PRECISION_CONFIG.PercentageDecimals` decimals, whole numbers without\n * decimals, `-` for a loss and, when `signed`, `+` for a gain. A value that\n * rounds to zero has no sign.\n *\n * @param value - RoE in percent, as a number or numeric string.\n * @param options - Formatting options.\n * @param options.signed - Prefix a gain with `+`. Defaults to false.\n * @returns The formatted RoE, or '' when the value is not a number.\n * @example formatRoePercent(10) => '10'\n * @example formatRoePercent(-25.5) => '-25.50'\n * @example formatRoePercent(12.5, { signed: true }) => '+12.50'\n */\nexport function formatRoePercent(\n value: number | string,\n { signed = false }: { signed?: boolean } = {},\n): string {\n const roe = typeof value === 'number' ? value : Number.parseFloat(value);\n if (!Number.isFinite(roe)) {\n return '';\n }\n const { PercentageDecimals } = TP_SL_PRECISION_CONFIG;\n const scale = 10 ** PercentageDecimals;\n const rounded = Math.round(Math.abs(roe) * scale) / scale;\n const magnitude = Number.isInteger(rounded)\n ? rounded.toString()\n : rounded.toFixed(PercentageDecimals);\n if (rounded === 0) {\n return magnitude;\n }\n if (roe < 0) {\n return `-${magnitude}`;\n }\n return signed ? `+${magnitude}` : magnitude;\n}\n\n/**\n * Parameters for `calculateExpectedTriggerPnl`.\n */\nexport type ExpectedTriggerPnlParams = {\n /** Take profit or stop loss trigger price. */\n triggerPrice: number;\n /** Position entry price, or the price an order is expected to fill at. */\n entryPrice: number;\n /** Signed position size: positive for a long, negative for a short. */\n size: number;\n /** Fee (USD) of the order that closes the position at the trigger price. */\n closingFee: number;\n};\n\n/**\n * Expected profit or loss (USD) when a take profit or stop loss closes the\n * position: the price move on the signed size, less the closing fee. Inputs\n * are not validated, as in Mobile's `calculateExpectedPnL`: callers pass\n * finite numbers, and a non-finite input gives a non-finite result.\n *\n * @param params - Trigger price, entry price, signed size and closing fee.\n * @returns The expected net PnL; positive for a gain.\n * @example calculateExpectedTriggerPnl({ triggerPrice: 110, entryPrice: 100, size: 2, closingFee: 0.1 }) => 19.9\n * @example calculateExpectedTriggerPnl({ triggerPrice: 110, entryPrice: 100, size: -2, closingFee: 0.1 }) => -20.1\n */\nexport function calculateExpectedTriggerPnl(\n params: ExpectedTriggerPnlParams,\n): number {\n const { triggerPrice, entryPrice, size, closingFee } = params;\n return (triggerPrice - entryPrice) * size - closingFee;\n}\n"]}
1
+ {"version":3,"file":"tpslCalculations.js","sourceRoot":"","sources":["../../src/utils/tpslCalculations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAGrE,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAyB5D;;;GAGG;AACH,MAAM,8BAA8B,GAAG,EAAE,CAAC;AAE1C;;GAEG;AACH,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAErC;;;;;;;GAOG;AACH,SAAS,gBAAgB,CACvB,SAAqC,EACrC,QAAiB;IAEjB,OAAO,CAAC,SAAS,KAAK,MAAM,CAA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AC,CAAC,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9C,CAAC;AAgBD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,2BAA2B,CACzC,MAAgC;IAEhC,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;IAC9D,OAAO,CAAC,YAAY,GAAG,UAAU,CAAC,GAAG,IAAI,GAAG,UAAU,CAAC;AACzD,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,yBAAyB,CAAC,MAKzC;IACC,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC;IAC/D,MAAM,SAAS,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC;IACnE,IACE,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;QACzB,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC;QAC3B,OAAO,IAAI,CAAC;QACZ,SAAS,IAAI,CAAC,EACd,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,8DAA8D;IAC9D,MAAM,UAAU,GAAG,gBAAgB,CACjC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,EAC/B,mBAAmB,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,aAAa,CACxD,CAAC;IACF,OAAO,UAAU,CAAC,CAAC,CAAC,OAAO,GAAG,SAAS,CAAC,CAAC,CAAC,OAAO,GAAG,SAAS,CAAC;AAChE,CAAC","sourcesContent":["/**\n * Take profit / stop loss calculations shared by the MetaMask clients.\n *\n * RoE (return on equity) is signed: positive at a gain and negative at a loss,\n * for a take profit and a stop loss alike, so a stop loss can sit at a gain\n * and a take profit at a loss.\n *\n * For a long, a take profit sits above the reference price and a stop loss\n * below it; for a short, the other way round.\n */\nimport { TP_SL_PRECISION_CONFIG } from '../constants/perpsConfig.js';\nimport type { OrderDirection } from '../types/index.js';\nimport type { TriggerOrderType } from '../types/perps-types.js';\nimport { getTriggerDirection } from './orderTypes.js';\nimport { parseFormattedPrice } from './stringParseUtils.js';\n\n/**\n * Price context for the TP/SL calculations and checks.\n */\nexport type TpslCalculationParams = {\n /** Reference price: the current market price, or a pending limit order's price. */\n currentPrice: number;\n /** Position or order side. */\n direction?: OrderDirection;\n /**\n * Position leverage. The RoE calculations need it and return '' while it is\n * unknown: they never assume 1x.\n */\n leverage?: number;\n /**\n * Entry price of an existing position. RoE is measured from it when set,\n * else from `currentPrice`; a set entry price that is not finite and above\n * zero makes the RoE calculations return ''.\n */\n entryPrice?: number;\n /** Liquidation price that a stop loss must stay clear of. */\n liquidationPrice?: string;\n};\n\n/**\n * Largest stop loss RoE loss, in percent per 1x of leverage: just short of\n * the 100% that would price the stop at zero.\n */\nconst MAX_STOP_LOSS_ROE_PER_LEVERAGE = 99;\n\n/**\n * Upper bound of a stop loss percentage, whatever the leverage.\n */\nconst MAX_STOP_LOSS_PERCENTAGE = 999;\n\n/**\n * Whether a trigger on this side gains as the price rises: a long's take\n * profit or a short's stop loss.\n *\n * @param direction - The position side.\n * @param isProfit - True for a take profit, false for a stop loss.\n * @returns True when the trigger sits above the reference price.\n */\nfunction isAboveReference(\n direction: OrderDirection | undefined,\n isProfit: boolean,\n): boolean {\n return (direction === 'long') === isProfit;\n}\n\n/**\n * Whether a value is a finite number above zero.\n *\n * @param value - The value to check.\n * @returns True for a finite number above zero.\n */\nfunction isPositiveFinite(value: number | undefined): value is number {\n return value !== undefined && Number.isFinite(value) && value > 0;\n}\n\n/**\n * Decimal places for a trigger price, from `TP_SL_PRECISION_CONFIG`: more for\n * low-priced assets.\n *\n * @param price - The trigger price.\n * @returns The number of decimal places to keep.\n */\nfunction getTriggerPriceDecimals(price: number): number {\n const band = TP_SL_PRECISION_CONFIG.TriggerPriceBands.find(\n ({ BelowPrice }) => price < BelowPrice,\n );\n return band?.Decimals ?? TP_SL_PRECISION_CONFIG.TriggerPriceDefaultDecimals;\n}\n\n/**\n * A calculated trigger price as a string, with the decimals its price range\n * needs and no trailing zeros. Rounding to the asset's submission precision\n * is left to the provider.\n *\n * @param price - The calculated trigger price.\n * @returns The trigger price as a string, or '' when it is not finite.\n */\nfunction toTriggerPriceString(price: number): string {\n if (!Number.isFinite(price)) {\n return '';\n }\n return Number.parseFloat(\n price.toFixed(getTriggerPriceDecimals(price)),\n ).toString();\n}\n\n/**\n * Price that RoE is measured from: the entry price of an existing position,\n * else the current price. Only an omitted entry price falls back; a set one\n * that is not usable (0, NaN) stays as is, so the callers' checks reject it.\n *\n * @param params - Price context.\n * @returns The base price.\n */\nfunction getBasePrice(params: TpslCalculationParams): number {\n return params.entryPrice ?? params.currentPrice;\n}\n\n/**\n * Signed RoE of a trigger price as a number.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @param params - Price context.\n * @returns The RoE in percent, or undefined without a usable price, side or\n * leverage: each price and the leverage must be finite and above zero.\n */\nfunction getSignedRoE(\n price: string,\n params: TpslCalculationParams,\n): number | undefined {\n const { direction, leverage } = params;\n const basePrice = getBasePrice(params);\n if (\n !price ||\n !direction ||\n !isPositiveFinite(basePrice) ||\n !isPositiveFinite(leverage)\n ) {\n return undefined;\n }\n const triggerPrice = parseFormattedPrice(price);\n if (!isPositiveFinite(triggerPrice)) {\n return undefined;\n }\n const roe = ((triggerPrice - basePrice) / basePrice) * leverage * 100;\n return direction === 'long' ? roe : -roe;\n}\n\n/**\n * Trigger price for a signed RoE. RoE is measured from the entry price when\n * set, else from the current price; the price moves by RoE / leverage.\n *\n * A stop loss's loss is capped at 99% of the margin per 1x of leverage, so a\n * stop loss at a loss is never priced at or below zero. Any other RoE that\n * moves the price down by 100% or more (a large short gain, or a long take\n * profit at a large loss) gives a price at or below zero, returned as is;\n * `isPositiveTriggerPrice` rejects it.\n *\n * @param roePercentage - Signed RoE in percent (10 for +10%, -5 for -5%).\n * @param isProfit - True for a take profit, false for a stop loss.\n * @param params - Price context.\n * @returns The trigger price as a string, or '' without a usable price, side,\n * leverage or RoE: the base price and leverage must be finite and above zero,\n * and the RoE finite.\n * @example calculatePriceForRoE(-10, false, { currentPrice: 2500, direction: 'long', leverage: 2 }) => '2375'\n */\nexport function calculatePriceForRoE(\n roePercentage: number,\n isProfit: boolean,\n params: TpslCalculationParams,\n): string {\n const { direction, leverage } = params;\n const basePrice = getBasePrice(params);\n if (\n !direction ||\n !isPositiveFinite(basePrice) ||\n !isPositiveFinite(leverage) ||\n !Number.isFinite(roePercentage)\n ) {\n return '';\n }\n\n const roe = isProfit\n ? roePercentage\n : Math.max(roePercentage, -leverage * MAX_STOP_LOSS_ROE_PER_LEVERAGE);\n const priceChangeRatio = roe / (leverage * 100);\n return toTriggerPriceString(\n basePrice *\n (direction === 'long' ? 1 + priceChangeRatio : 1 - priceChangeRatio),\n );\n}\n\n/**\n * Signed RoE of a trigger price: positive at a gain and negative at a loss,\n * for a take profit or a stop loss alike. Use it for a TP/SL bound to an open\n * position.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @param params - Price context.\n * @returns The RoE in percent with `TP_SL_PRECISION_CONFIG.PercentageDecimals`\n * decimals, or '' without a usable price, side or leverage.\n * @example calculateSignedRoEForPrice('2375', { currentPrice: 2500, direction: 'long', leverage: 2 }) => '-10.00'\n */\nexport function calculateSignedRoEForPrice(\n price: string,\n params: TpslCalculationParams,\n): string {\n return (\n getSignedRoE(price, params)?.toFixed(\n TP_SL_PRECISION_CONFIG.PercentageDecimals,\n ) ?? ''\n );\n}\n\n/**\n * RoE of a trigger price on its own side: a take profit's gain (zero or\n * more) and a stop loss's loss (zero or less). A trigger on the wrong side\n * reads as zero.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @param isProfit - True for a take profit, false for a stop loss.\n * @param params - Price context.\n * @returns The RoE in percent with `TP_SL_PRECISION_CONFIG.PercentageDecimals`\n * decimals, or '' without a usable price, side or leverage.\n * @example calculateRoEForPrice('2375', true, { currentPrice: 2500, direction: 'long', leverage: 2 }) => '0.00'\n */\nexport function calculateRoEForPrice(\n price: string,\n isProfit: boolean,\n params: TpslCalculationParams,\n): string {\n const roe = getSignedRoE(price, params);\n if (roe === undefined) {\n return '';\n }\n const isWrongSide = isProfit ? roe < 0 : roe > 0;\n return (isWrongSide ? 0 : roe).toFixed(\n TP_SL_PRECISION_CONFIG.PercentageDecimals,\n );\n}\n\n/**\n * Trigger price for a price move from the current price, in the trigger's\n * profitable or losing direction.\n *\n * @param percentage - Price move in percent.\n * @param isProfit - True for a take profit, false for a stop loss.\n * @param params - Price context.\n * @returns The trigger price, with the decimals its price range needs (see\n * `TP_SL_PRECISION_CONFIG`), or '' without a current price, side or finite\n * percentage.\n * @example calculatePriceForPercentage(10, true, { currentPrice: 0.001, direction: 'long' }) => '0.0011'\n */\nexport function calculatePriceForPercentage(\n percentage: number,\n isProfit: boolean,\n params: TpslCalculationParams,\n): string {\n const { currentPrice, direction } = params;\n if (!currentPrice || !direction) {\n return '';\n }\n const move = percentage / 100;\n const multiplier = isAboveReference(direction, isProfit)\n ? 1 + move\n : 1 - move;\n return toTriggerPriceString(currentPrice * multiplier);\n}\n\n/**\n * Price move from the current price to a trigger price, negative when the\n * trigger sits on the wrong side for a take profit or stop loss.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @param isProfit - True for a take profit, false for a stop loss.\n * @param params - Price context.\n * @returns The move in percent with `TP_SL_PRECISION_CONFIG.PercentageDecimals`\n * decimals, or '' without a usable price or side: both prices must be finite.\n */\nexport function calculatePercentageForPrice(\n price: string,\n isProfit: boolean,\n params: TpslCalculationParams,\n): string {\n const { currentPrice, direction } = params;\n if (!currentPrice || !Number.isFinite(currentPrice) || !direction || !price) {\n return '';\n }\n const triggerPrice = parseFormattedPrice(price);\n if (!Number.isFinite(triggerPrice)) {\n return '';\n }\n const priceDiff = triggerPrice - currentPrice;\n const percentage = Math.abs((priceDiff / currentPrice) * 100).toFixed(\n TP_SL_PRECISION_CONFIG.PercentageDecimals,\n );\n const isExpectedSide = isAboveReference(direction, isProfit)\n ? priceDiff > 0\n : priceDiff < 0;\n return isExpectedSide ? percentage : `-${percentage}`;\n}\n\n/**\n * Largest stop loss percentage for a leverage: 99% per 1x, at most 999%.\n *\n * @param leverage - The position leverage.\n * @returns The maximum stop loss percentage.\n */\nexport function getMaxStopLossPercentage(leverage: number): number {\n return Math.min(\n leverage * MAX_STOP_LOSS_ROE_PER_LEVERAGE,\n MAX_STOP_LOSS_PERCENTAGE,\n );\n}\n\n/**\n * Whether a stop loss percentage is above zero and within the leverage's\n * maximum.\n *\n * @param percentage - The stop loss percentage, as a positive number.\n * @param leverage - The position leverage.\n * @returns True when the percentage is allowed.\n */\nexport function isValidStopLossPercentage(\n percentage: number,\n leverage: number,\n): boolean {\n return percentage > 0 && percentage <= getMaxStopLossPercentage(leverage);\n}\n\n/**\n * Whether a trigger price can be sent at all: the venue rejects a trigger at\n * or below zero. Direction checks alone would let a negative price through.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @returns False only when the price parses to a number at or below zero.\n */\nexport function isPositiveTriggerPrice(price?: string): boolean {\n if (!price) {\n return true;\n }\n const triggerPrice = parseFormattedPrice(price);\n return Number.isNaN(triggerPrice) || triggerPrice > 0;\n}\n\n/**\n * Whether a trigger price is positive and on its side of the reference price.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @param params - Price context.\n * @param isProfit - True for a take profit, false for a stop loss.\n * @returns False for a non-positive price or one on the wrong side; true\n * when the price, reference price or side is missing.\n */\nfunction isTriggerPriceOnSide(\n price: string,\n params: TpslCalculationParams,\n isProfit: boolean,\n): boolean {\n const { currentPrice, direction } = params;\n if (!isPositiveTriggerPrice(price)) {\n return false;\n }\n if (!currentPrice || !direction || !price) {\n return true;\n }\n const triggerPrice = parseFormattedPrice(price);\n if (Number.isNaN(triggerPrice)) {\n return true;\n }\n return isAboveReference(direction, isProfit)\n ? triggerPrice > currentPrice\n : triggerPrice < currentPrice;\n}\n\n/**\n * Whether a take profit price is positive and above the reference price for a\n * long, below it for a short.\n *\n * @param price - The take profit price; may carry `$` or `,` formatting.\n * @param params - Price context.\n * @returns False for an invalid price; true when the price, reference price or\n * side is missing.\n */\nexport function isValidTakeProfitPrice(\n price: string,\n params: TpslCalculationParams,\n): boolean {\n return isTriggerPriceOnSide(price, params, true);\n}\n\n/**\n * Whether a stop loss price is positive and below the reference price for a\n * long, above it for a short.\n *\n * @param price - The stop loss price; may carry `$` or `,` formatting.\n * @param params - Price context.\n * @returns False for an invalid price; true when the price, reference price or\n * side is missing.\n */\nexport function isValidStopLossPrice(\n price: string,\n params: TpslCalculationParams,\n): boolean {\n return isTriggerPriceOnSide(price, params, false);\n}\n\n/**\n * Whether a stop loss triggers before liquidation: above the liquidation price\n * for a long, below it for a short.\n *\n * @param price - The stop loss price; may carry `$` or `,` formatting.\n * @param liquidationPrice - The liquidation price; may carry formatting.\n * @param direction - The position side.\n * @returns False when the stop loss is at or beyond liquidation; true when an\n * input is missing or not a number.\n */\nexport function isStopLossSafeFromLiquidation(\n price?: string,\n liquidationPrice?: string,\n direction?: OrderDirection,\n): boolean {\n if (!liquidationPrice || !direction || !price) {\n return true;\n }\n const stopLossPrice = parseFormattedPrice(price);\n const liquidation = parseFormattedPrice(liquidationPrice);\n if (Number.isNaN(stopLossPrice) || Number.isNaN(liquidation)) {\n return true;\n }\n return direction === 'long'\n ? stopLossPrice > liquidation\n : stopLossPrice < liquidation;\n}\n\n/**\n * Outcome of `validateTPSLPrices`. `unresolved` means a set trigger could not\n * be checked: the reference price, the side or a readable liquidation price\n * is missing. It is not a pass.\n */\nexport type TpslValidationResult = 'valid' | 'invalid' | 'unresolved';\n\n/**\n * Whether a trigger price reads as a finite number above zero.\n *\n * @param price - The trigger price; may carry `$` or `,` formatting.\n * @returns True for a usable price.\n */\nfunction isReadableTriggerPrice(price: string): boolean {\n return isPositiveFinite(parseFormattedPrice(price));\n}\n\n/**\n * Check a take profit and stop loss pair: each set price must read as a\n * positive number, sit on its side of the reference price, and the stop loss\n * must trigger before liquidation. An unset trigger needs no check. The\n * liquidation check runs only when `params.liquidationPrice` is set.\n *\n * A failure found without the reference price (an unreadable or non-positive\n * price, a stop loss beyond liquidation) is `invalid` even when the rest of the\n * context is missing.\n *\n * @param takeProfitPrice - The take profit price, if any.\n * @param stopLossPrice - The stop loss price, if any.\n * @param params - Price context, including the liquidation price.\n * @returns `valid` when every set price passes, `invalid` when one fails, and\n * `unresolved` when a set price cannot be checked.\n */\nexport function validateTPSLPrices(\n takeProfitPrice: string | undefined,\n stopLossPrice: string | undefined,\n params: TpslCalculationParams,\n): TpslValidationResult {\n const { currentPrice, direction, liquidationPrice } = params;\n if (!takeProfitPrice && !stopLossPrice) {\n return 'valid';\n }\n if (\n (takeProfitPrice && !isReadableTriggerPrice(takeProfitPrice)) ||\n (stopLossPrice && !isReadableTriggerPrice(stopLossPrice)) ||\n !isStopLossSafeFromLiquidation(stopLossPrice, liquidationPrice, direction)\n ) {\n return 'invalid';\n }\n if (\n !direction ||\n !Number.isFinite(currentPrice) ||\n currentPrice <= 0 ||\n (stopLossPrice &&\n liquidationPrice &&\n !Number.isFinite(parseFormattedPrice(liquidationPrice)))\n ) {\n return 'unresolved';\n }\n const isOnSide =\n (!takeProfitPrice || isValidTakeProfitPrice(takeProfitPrice, params)) &&\n (!stopLossPrice || isValidStopLossPrice(stopLossPrice, params));\n return isOnSide ? 'valid' : 'invalid';\n}\n\n/**\n * Format a RoE percentage for display, without the `%` sign: rounded to\n * `TP_SL_PRECISION_CONFIG.PercentageDecimals` decimals, whole numbers without\n * decimals, `-` for a loss and, when `signed`, `+` for a gain. A value that\n * rounds to zero has no sign.\n *\n * @param value - RoE in percent, as a number or numeric string.\n * @param options - Formatting options.\n * @param options.signed - Prefix a gain with `+`. Defaults to false.\n * @returns The formatted RoE, or '' when the value is not a number.\n * @example formatRoePercent(10) => '10'\n * @example formatRoePercent(-25.5) => '-25.50'\n * @example formatRoePercent(12.5, { signed: true }) => '+12.50'\n */\nexport function formatRoePercent(\n value: number | string,\n { signed = false }: { signed?: boolean } = {},\n): string {\n const roe = typeof value === 'number' ? value : Number.parseFloat(value);\n if (!Number.isFinite(roe)) {\n return '';\n }\n const { PercentageDecimals } = TP_SL_PRECISION_CONFIG;\n const scale = 10 ** PercentageDecimals;\n const rounded = Math.round(Math.abs(roe) * scale) / scale;\n const magnitude = Number.isInteger(rounded)\n ? rounded.toString()\n : rounded.toFixed(PercentageDecimals);\n if (rounded === 0) {\n return magnitude;\n }\n if (roe < 0) {\n return `-${magnitude}`;\n }\n return signed ? `+${magnitude}` : magnitude;\n}\n\n/**\n * Parameters for `calculateExpectedTriggerPnl`.\n */\nexport type ExpectedTriggerPnlParams = {\n /** Take profit or stop loss trigger price. */\n triggerPrice: number;\n /** Position entry price, or the price an order is expected to fill at. */\n entryPrice: number;\n /** Signed position size: positive for a long, negative for a short. */\n size: number;\n /** Fee (USD) of the order that closes the position at the trigger price. */\n closingFee: number;\n};\n\n/**\n * Expected profit or loss (USD) when a take profit or stop loss closes the\n * position: the price move on the signed size, less the closing fee. Inputs\n * are not validated, as in Mobile's `calculateExpectedPnL`: callers pass\n * finite numbers, and a non-finite input gives a non-finite result.\n *\n * @param params - Trigger price, entry price, signed size and closing fee.\n * @returns The expected net PnL; positive for a gain.\n * @example calculateExpectedTriggerPnl({ triggerPrice: 110, entryPrice: 100, size: 2, closingFee: 0.1 }) => 19.9\n * @example calculateExpectedTriggerPnl({ triggerPrice: 110, entryPrice: 100, size: -2, closingFee: 0.1 }) => -20.1\n */\nexport function calculateExpectedTriggerPnl(\n params: ExpectedTriggerPnlParams,\n): number {\n const { triggerPrice, entryPrice, size, closingFee } = params;\n return (triggerPrice - entryPrice) * size - closingFee;\n}\n\n/**\n * Whether a trigger price sits on the side its order fires from. A buy stop\n * and a sell take profit fire as the price rises, so they trigger above the\n * reference price; a buy take profit and a sell stop trigger below it. A\n * trigger at the reference price is on neither side.\n *\n * @param params - Trigger parameters.\n * @param params.orderType - Trigger order type.\n * @param params.isBuy - Side of the trigger order itself (a buy closes a short).\n * @param params.triggerPrice - Price at which the order activates.\n * @param params.referencePrice - Current price, or the parent's price for an\n * attached trigger.\n * @returns Whether the trigger is on its side, or undefined when either price\n * is missing or not a positive number.\n */\nexport function isTriggerPriceOnValidSide(params: {\n orderType: TriggerOrderType;\n isBuy: boolean;\n triggerPrice: number | string | undefined;\n referencePrice: number | string | undefined;\n}): boolean | undefined {\n const trigger = Number.parseFloat(String(params.triggerPrice));\n const reference = Number.parseFloat(String(params.referencePrice));\n if (\n !Number.isFinite(trigger) ||\n !Number.isFinite(reference) ||\n trigger <= 0 ||\n reference <= 0\n ) {\n return undefined;\n }\n // A buy trigger closes a short, a sell trigger closes a long.\n const firesAbove = isAboveReference(\n params.isBuy ? 'short' : 'long',\n getTriggerDirection(params.orderType) === 'take_profit',\n );\n return firesAbove ? trigger > reference : trigger < reference;\n}\n"]}
@@ -120,12 +120,20 @@ The controller creates `TradingService`, `MarketDataService`, `AccountService`,
120
120
  | `providerNetwork.ts` | Whether a provider runs on testnet |
121
121
  | `RewardsIntegrationService` | Unified fee resolver; lowest of `default`, `rewards`, `grant` and `subscription` |
122
122
  | `ServiceContext.ts` | Per-call context type (tracing, error context, state callbacks) |
123
- | `TerminalMarketService` | Market metadata from the MetaMask Terminal API, cached for `TERMINAL_API_CONFIG.CacheTtlMs`, and the schema-v4 global snapshot, cached until `receivedAt` plus the smaller of its `maxAgeMs` and 30 s |
123
+ | `TerminalMarketService` | Market metadata from the MetaMask Terminal API, cached for `TERMINAL_API_CONFIG.CacheTtlMs`, and one schema-v4 global snapshot per provider, cached until `receivedAt` plus the smaller of its `maxAgeMs` and 30 s |
124
124
  | `TradingReadinessCache.ts` | Global signing cache (unified account, builder fee, referral) that survives provider recreation so hardware wallets are not prompted again |
125
125
  | `TradingService` | Orders, cancels and positions with fee discounts; signals `cacheInvalidator` after changes |
126
126
 
127
127
  Code: `src/services/`; `src/PerpsController.ts` constructor.
128
128
 
129
+ ## Market lists and saved markets
130
+
131
+ Aggregated reads return the original venue rows. A market served directly from a v4 snapshot carries the provider ID that Core validated. Clients can call `groupMarketsByMarketKey(rows, defaultProvider)` for display. Rows group when they share a backend key and each explicitly has `priceScale: 1`. Each group puts the default venue first when present. Use `rowId` as the display row identity and the selected venue's `providerId` and `symbol` for charts and trading. Rows with missing keys or with missing or non-unit scales remain separate and omit `marketKey`. Saving one stores its bare symbol when it is on the legacy venue, otherwise `venue:<provider>:<symbol>`, never a backend key.
132
+
133
+ `toggleWatchlistMarket`, `isWatchlistMarket` and `recordMarketViewed` take an optional backend key from a unit-scale row. Pass the original group's `venues` as the third argument and the venue that owned saved symbols as the fourth (`legacyProvider`, default HyperLiquid, the same default as `resolveSavedPerpsMarkets`). These actions also match each tagged group row with the same backend key and `priceScale: 1` by the entry it would have saved ungrouped: its symbol on the legacy venue, otherwise `venue:<provider>:<symbol>`. A favorite or recent saved before the row grouped is replaced with the keyed entry. When opening a saved item, pass the saved strings and ungrouped venue rows to `resolveSavedPerpsMarkets`. A legacy symbol requires an exact match on its original venue and stays unresolved while that row is unavailable. A `venue:` reference opens only that venue's row with the same symbol. The resolver defaults legacy ownership to HyperLiquid and accepts the prior venue for entries saved on Lighter. New keyed entries look for unit-scale rows and prefer the configured default venue.
134
+
135
+ With snapshots configured, a missing or expired venue slice invalidates the aggregated preload. The client can fetch a fresh list from Core.
136
+
129
137
  ## Platform dependencies
130
138
 
131
139
  `PerpsPlatformDependencies` is passed as `infrastructure` to the constructor. Venue credentials and signer hooks come separately through `clientConfig.providerCredentials`.
@@ -15,19 +15,24 @@ Shared answers clients used to keep their own copies of. Each one is exported fr
15
15
 
16
16
  `orderLimits`:
17
17
 
18
- | Field | HyperLiquid | Lighter |
19
- | --------------------- | ------------------------- | ------------------------- |
20
- | `sizeDecimals` | market `szDecimals` | `supported_size_decimals` |
21
- | `minOrderNotionalUsd` | per-order minimum ($10) | `min_quote_amount` |
22
- | `minOrderSize` | not reported | `min_base_amount` |
23
- | `minimumAppliesTo` | `all_orders` | `resting_limit_orders` |
24
- | `scaleOrderCount` | `SCALE_ORDER_COUNT` | `SCALE_ORDER_COUNT` |
25
- | `twap` | `HYPERLIQUID_TWAP_LIMITS` | not reported (no TWAP) |
18
+ | Field | HyperLiquid | Lighter |
19
+ | ------------------------- | ----------------------------------------------------------- | ------------------------- |
20
+ | `sizeDecimals` | market `szDecimals` | `supported_size_decimals` |
21
+ | `minOrderNotionalUsd` | per-order minimum ($10) | `min_quote_amount` |
22
+ | `minOrderSize` | not reported | `min_base_amount` |
23
+ | `minimumAppliesTo` | `all_orders` | `resting_limit_orders` |
24
+ | `scaleOrderCount` | `SCALE_ORDER_COUNT` | `SCALE_ORDER_COUNT` |
25
+ | `twap` | `HYPERLIQUID_TWAP_LIMITS` | not reported (no TWAP) |
26
+ | `maxOraclePriceDeviation` | `0.95` (`HYPERLIQUID_ORDER_LIMITS.MaxOraclePriceDeviation`) | not reported |
26
27
 
27
28
  Apply the reported minimums to the orders named by `minimumAppliesTo`. On Lighter, market and IOC orders can go down to one size step. Lighter reports `resting_limit_orders` even when maker minimums are unavailable. It omits both minimums if either is missing or invalid, if either grid is unavailable, or if the maker bounds cannot be met within the venue's wire limits. The largest base size is `(2^48 − 1) × 10^(-sizeDecimals)`, and the largest quote notional is that size times the largest wire price expressed in quote units. A valid grid remains available independently.
28
29
 
29
30
  A verified full close can qualify for an exception to the normal minimum notional. The close must still satisfy the venue's size grid. For example, a HyperLiquid batch close refuses a position whose size rounds down to zero, with `ORDER_SIZE_POSITIVE` on that row.
30
31
 
32
+ Check a limit price against `maxOraclePriceDeviation` with `isPriceOutsideDeviationBand(price, oraclePrice, maxOraclePriceDeviation)`, or show the accepted range from `getPriceDeviationBand`. Skip the check when the venue omits the limit. Round a price onto the reported grid with `roundPerpsPrice({ price, pricePrecision })`: a HyperLiquid grid gives the same string as `formatHyperLiquidPrice` except that a price rounding to zero returns `undefined` rather than `'0'`, and a Lighter grid rounds the supplied decimal string half up to `tickSize`.
33
+
34
+ `attachedTpslGroupLimit` (`{ takeProfit, stopLoss }`) is the most take-profit and stop-loss legs one order can attach. HyperLiquid and Lighter both report one of each.
35
+
31
36
  For HyperLiquid markets that prohibit Cross, `getOrderCapabilities` reports `supportedMarginModes: ['isolated']` and `crossMarginUnavailableReason`. The reason is `noCross`, `strictIsolated` or `isolatedOnly` for a legacy or unrecognized restriction. Show the disabled Cross option with the corresponding explanation. A cross-capable market omits the reason.
32
37
 
33
38
  ## Order-book grouping
@@ -39,6 +44,24 @@ For HyperLiquid markets that prohibit Cross, `getOrderCapabilities` reports `sup
39
44
  - Sizes and notionals are summed per bucket (a level without a readable notional counts `price * size`); `total` and `totalNotional` are rebuilt from the best price outward.
40
45
  - A `null` grouping only trims, for a stream the venue already aggregated.
41
46
 
47
+ `calculateOrderBookGroupingOptions(midPrice)` builds the grouping ladder (`ORDER_BOOK_GROUPING_CONFIG`) and `selectDefaultOrderBookGrouping(options)` picks the one a book opens at. On HyperLiquid, `calculateOrderBookAggregationParams(grouping, price)` gives the `nSigFigs`/`mantissa` to subscribe at so the venue aggregates the stream. `calculateOrderBookSpread({ bestBid, bestAsk })` returns the spread, mid and spread percent as numbers. `estimateOrderBookSlippage` sweeps the visible book for a market order's average and worst-level slippage in basis points; compare `worstSlippageBps` with the max-slippage setting for a cap check.
48
+
49
+ ## Order, fee and position helpers
50
+
51
+ | Helper | Use it for |
52
+ | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
53
+ | `calculateCloseSize` | Size to close for a percent or USD amount, on the venue's size grid; a full close returns the exact position size |
54
+ | `calculateFeeNotionalUsd`, `getUndiscountedFeeRate`, `calculateUndiscountedFeeAmount` | Fee notional (a TP/SL pair uses its higher trigger price) and the fee before a MetaMask discount |
55
+ | `isTriggerPriceOnValidSide` | Whether a stop or take-profit price sits on the side its order fires from |
56
+ | `getOrderFillKey`, `getFillAggregationKey` | Deduplicating REST and live fills, and grouping fills into one trade |
57
+ | `getPositionDirection` | `long` / `short` from a signed size; `undefined` for zero |
58
+ | `normalizeHyperLiquidScalePriceLadder`, `sizeHyperLiquidScaleLadder` | A Hyperliquid scale ladder: grid prices, and rung sizes that meet a USD target (Mobile's rule) or split an exact on-grid size |
59
+ | `recomputePositionAtPrice` | PnL, value and return on equity at a live price between account updates |
60
+ | `CROSS_MARGIN_RATIO_THRESHOLDS`, `getCrossMarginRatioTone` | Warning and danger levels for `accountRatio` |
61
+ | `buildProviderCacheKey` | The `provider:network` key the controller caches per-venue data under |
62
+
63
+ A missing or unreadable number gives `undefined` rather than 0: the whole result for the scalar helpers, the affected fields for `estimateOrderBookSlippage`, and the position unchanged for `recomputePositionAtPrice`. `isPriceOutsideDeviationBand` fails open instead: it returns `false` for unusable input so an unknown price never blocks an order.
64
+
42
65
  ## Cross-margin liquidation
43
66
 
44
67
  Beside the isolated estimates in `hyperLiquidPositionPreview`:
@@ -213,9 +213,11 @@ All keys live in `PERPS_EVENT_PROPERTY`. The constant name is the upper-case key
213
213
  | UTM attribution | `utm_source`, `utm_medium`, `utm_campaign`, `utm_content`, `utm_term` |
214
214
  | Client | `environment_type` |
215
215
  | Order funnel and quotes | `order_context`, `order_size_percent`, `limit_price_input_type`, `limit_price_input_preset`, `order_has_tp`, `order_has_sl`, `quote_latency_ms`, `error_reason`, `saved_order`, `default_payment_token`, `default_size_amount`, `default_leverage`, `default_auto_close`, `order_execution_latency_ms`, `screen_context`, `from_token`, `from_chain`, `to_token`, `to_chain` |
216
- | Search | `search_query`, `results_count`, `result_rank`, `mode`, `current_token` |
216
+ | Search | `search_query`, `results_count`, `result_rank`, `mode`, `current_token`, `query_count`, `time_in_search_ms`, `time_to_tap_ms`, `query_text`, `query_length`, `has_results`, `active_chips` |
217
217
  | Interface mode | `perps_mode` |
218
218
  | Sort, filter, abandon | `sort_field`, `sort_direction`, `filter_category`, `time_on_screen_ms` |
219
+ | Chase | `fill_pct_at_terminate` |
220
+ | Related markets | `source_market`, `market`, `category`, `position` |
219
221
 
220
222
  `perps_mode` is the Lite/Pro interface mode (`lite` or `pro`). It is separate from `mode`, which search uses for query intent (`discovery`, `intent` or `browse`).
221
223
 
@@ -225,36 +227,36 @@ Code: `src/constants/eventNames.ts` `PERPS_EVENT_PROPERTY`
225
227
 
226
228
  All values live in `PERPS_EVENT_VALUE`, one group per key below.
227
229
 
228
- | Group | Values |
229
- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
230
- | `DIRECTION` | `long`, `short` |
231
- | `ORDER_TYPE` | `market`, `limit`, `stop_market`, `stop_limit`, `take_profit_market`, `take_profit_limit`, `twap`, `scale`, `chase` |
232
- | `ORDER_TYPE_CAPITALIZED` | `market`, `limit` |
233
- | `CHART_LIBRARY` | `lightweight`, `advanced` |
234
- | `ASSET_TYPE` | `spot`, `perp` |
235
- | `INPUT_METHOD` | `slider`, `keyboard`, `preset`, `manual`, `percentage_button` |
236
- | `SOURCE` | `banner`, `notification`, `main_action_button`, `position_tab`, `perp_markets`, `deeplink`, `tutorial`, `trade_screen`, `homescreen_tab`, `perp_asset_screen`, `perp_market`, `perp_market_search`, `position_screen`, `bottom_nav_bar`, `tp_sl_view`, `perps_home`, `perps_tutorial`, `perps_home_empty_state`, `perps_asset_screen_no_funds`, `trade_menu_action`, `wallet_home`, `home_section`, `tooltip`, `magnifying_glass`, `crypto_button`, `stocks_button`, `close_toast`, `perps_home_position`, `perps_home_orders`, `perps_home_watchlist`, `perps_home_explore_crypto`, `perps_home_explore_stocks`, `perps_home_activity`, `explore`, `perps_market_list_all`, `perps_market_list_crypto`, `perps_market_list_stocks`, `perps_tab`, `wallet_main_action_menu`, `push_notification`, `order_book`, `full_screen_chart`, `stop_loss_prompt_banner`, `open_position`, `position_close_toast`, `trade_details`, `deposit_button`, `withdraw_button`, `trade_action`, `add_funds_action`, `cancel_order`, `asset_detail_screen`, `market_insights`, `close_position_action`, `modify_position_action`, `order_book_long_button`, `order_book_short_button`, `order_book_close_button`, `order_book_modify_button`, `auto_close_action`, `adjust_margin_action`, `stop_loss_prompt_add_margin`, `stop_loss_prompt_set_sl`, `close_all_positions_button`, `cancel_all_orders_button` |
237
- | `WARNING_TYPE` | `minimum_deposit`, `minimum_order_size`, `insufficient_balance` |
238
- | `ERROR_TYPE` | `network`, `app_crash`, `backend`, `validation`, `warning` |
239
- | `ERROR_MESSAGE_KEY` | `order_changed_from_limit_to_market`, `open_cross_margin_position_detected`, `insufficient_balance`, `order_failed`, `geo_restriction`, `minimum_order_size`, `maximum_leverage_exceeded`, `price_deviation_too_high`, `market_at_capacity`, `network_error`, `connection_failed`, `position_update_failed`, `tp_sl_update_failed`, `margin_update_failed`, `unknown` |
240
- | `SOURCE_SECTION` | `positions`, `orders`, `watchlist`, `whats_happening`, `products`, `top_gainers`, `top_losers`, `crypto`, `commodity`, `stock`, `forex`, `perps_movers`, `perps_crypto`, `perps_stocks_commodities`, `perps_markets`, `all_markets`, `new`, `active_search` |
241
- | `SECTION_NAME` | `balance`, `positions`, `orders`, `watchlist`, `whats_happening`, `products`, `top_movers`, `explore`, `explore_crypto`, `explore_commodities`, `explore_stocks`, `explore_forex`, `recently_added`, `recent_activity` |
242
- | `INTERACTION_TYPE` | `tap`, `zoom`, `slide`, `search_clicked`, `order_type_viewed`, `order_type_selected`, `setting_changed`, `leverage_changed`, `tutorial_started`, `tutorial_completed`, `tutorial_navigation`, `candle_period_viewed`, `candle_period_changed`, `favorite_toggled`, `button_clicked`, `contact_support`, `stop_loss_one_click_prompt`, `add_margin`, `remove_margin`, `increase_exposure`, `reduce_exposure`, `flip_position`, `display_hero_card`, `share_pnl_hero_card`, `full_screen_chart`, `payment_token_selector`, `payment_method_changed`, `cancel_trade_with_token`, `slippage_config_opened`, `slippage_config_changed`, `slippage_limit_blocked_order`, `scale_config_changed`, `scale_validation_error_shown`, `tpsl_roe_sign_toggled`, `market_list_filter`, `sort_applied`, `filter_applied`, `chase_backgrounded_converted`, `chase_terminated`, `search_result_tapped`, `search_chip_tapped`, `search_signal_tile_tapped`, `payment_token_selector_dismissed` |
243
- | `MAX_SLIPPAGE_SOURCE` | `default`, `user_configured` |
244
- | `ACTION_TYPE` | `start_trading`, `skip`, `stop_loss_set`, `take_profit_set`, `adl_learn_more`, `learn_more`, `favorite_market`, `unfavorite_market` |
245
- | `NOTIFICATION_TYPE` | `position_liquidated`, `tp_executed`, `sl_executed`, `limit_order_executed`, `chase_backgrounded` |
246
- | `CLOSE_TYPE` | `full`, `partial` |
247
- | `NAVIGATION_METHOD` | `swipe`, `continue_button`, `progress_dot` |
248
- | `STATUS` | `viewed`, `started`, `completed`, `initiated`, `submitted`, `executed`, `partially_filled`, `failed`, `success`, `already_enabled`, `migration_required`, `not_applicable` |
249
- | `SCREEN_TYPE` | `markets`, `market_list`, `asset_details`, `trading`, `homescreen`, `perps_home`, `wallet_home_perps_tab`, `position_close`, `leverage`, `tutorial`, `withdrawal`, `tp_sl`, `create_tpsl`, `edit_tpsl`, `deposit_input`, `deposit_review`, `close_all_positions`, `cancel_all_orders`, `pnl_hero_card`, `order_book`, `error`, `market_list_all`, `market_list_crypto`, `market_list_stocks`, `full_screen_chart`, `activity`, `increase_exposure`, `add_margin`, `remove_margin`, `geo_block_notif`, `compliance_block_notif`, `cancel_trade_with_token_toast`, `search_results_shown`, `search_no_results` |
250
- | `SETTING_TYPE` | `leverage`, `slippage`, `start_price`, `end_price`, `total_orders`, `size_skew` |
251
- | `SCREEN_NAME` | `connection_error`, `perps_hero_card`, `perps_activity_history`, `perps_home`, `perps_market_details`, `perps_order` |
252
- | `ACTION` | `connection_retry`, `connection_go_back`, `share`, `add_margin`, `remove_margin`, `edit_tp_sl`, `create_tp_sl`, `tp`, `sl`, `tpsl`, `create_position`, `increase_exposure`, `flip_long_to_short`, `flip_short_to_long`, `abandon_order` |
253
- | `RISK_MANAGEMENT_SOURCE` | `trade_screen`, `position_screen`, `stop_loss_prompt_banner` |
254
- | `PERPS_HISTORY_TABS` | `trades`, `orders`, `funding`, `deposits` |
255
- | `MM_PAY_TOKEN` | `Perps Balance` |
256
- | `BUTTON_CLICKED` | `deposit`, `withdraw`, `perps_home`, `tutorial`, `tooltip`, `market_list`, `open_position`, `magnifying_glass`, `crypto`, `stocks`, `commodities`, `forex`, `new`, `give_feedback`, `watchlist`, `top_movers`, `whats_happening`, `place_order`, `close`, `reduce_exposure` |
257
- | `BUTTON_LOCATION` | `perps_home`, `perps_tutorial`, `perps_home_empty_state`, `perps_asset_screen`, `perps_tab`, `trade_menu_action`, `wallet_home`, `market_list`, `screen`, `tooltip`, `perp_market_details`, `order_book`, `full_screen_chart`, `asset_details` |
230
+ | Group | Values |
231
+ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
232
+ | `DIRECTION` | `long`, `short` |
233
+ | `ORDER_TYPE` | `market`, `limit`, `stop_market`, `stop_limit`, `take_profit_market`, `take_profit_limit`, `twap`, `scale`, `chase` |
234
+ | `ORDER_TYPE_CAPITALIZED` | `market`, `limit` |
235
+ | `CHART_LIBRARY` | `lightweight`, `advanced` |
236
+ | `ASSET_TYPE` | `spot`, `perp` |
237
+ | `INPUT_METHOD` | `slider`, `keyboard`, `preset`, `manual`, `percentage_button` |
238
+ | `SOURCE` | `banner`, `notification`, `main_action_button`, `position_tab`, `perp_markets`, `deeplink`, `tutorial`, `trade_screen`, `homescreen_tab`, `perp_asset_screen`, `perp_market`, `perp_market_search`, `position_screen`, `bottom_nav_bar`, `tp_sl_view`, `perps_home`, `perps_tutorial`, `perps_home_empty_state`, `perps_asset_screen_no_funds`, `trade_menu_action`, `wallet_home`, `home_section`, `tooltip`, `magnifying_glass`, `crypto_button`, `stocks_button`, `close_toast`, `perps_home_position`, `perps_home_orders`, `perps_home_watchlist`, `perps_home_explore_crypto`, `perps_home_explore_stocks`, `perps_home_activity`, `explore`, `perps_market_list_all`, `perps_market_list_crypto`, `perps_market_list_stocks`, `perps_tab`, `wallet_main_action_menu`, `push_notification`, `order_book`, `full_screen_chart`, `stop_loss_prompt_banner`, `open_position`, `position_close_toast`, `trade_details`, `deposit_button`, `withdraw_button`, `trade_action`, `add_funds_action`, `cancel_order`, `asset_detail_screen`, `market_insights`, `close_position_action`, `modify_position_action`, `order_book_long_button`, `order_book_short_button`, `order_book_close_button`, `order_book_modify_button`, `auto_close_action`, `adjust_margin_action`, `stop_loss_prompt_add_margin`, `stop_loss_prompt_set_sl`, `close_all_positions_button`, `cancel_all_orders_button`, `related_markets` |
239
+ | `WARNING_TYPE` | `minimum_deposit`, `minimum_order_size`, `insufficient_balance` |
240
+ | `ERROR_TYPE` | `network`, `app_crash`, `backend`, `validation`, `warning` |
241
+ | `ERROR_MESSAGE_KEY` | `order_changed_from_limit_to_market`, `open_cross_margin_position_detected`, `insufficient_balance`, `order_failed`, `geo_restriction`, `minimum_order_size`, `maximum_leverage_exceeded`, `price_deviation_too_high`, `market_at_capacity`, `network_error`, `connection_failed`, `position_update_failed`, `tp_sl_update_failed`, `margin_update_failed`, `unknown` |
242
+ | `SOURCE_SECTION` | `positions`, `orders`, `watchlist`, `whats_happening`, `products`, `top_gainers`, `top_losers`, `crypto`, `commodity`, `stock`, `forex`, `perps_movers`, `perps_crypto`, `perps_stocks_commodities`, `perps_markets`, `all_markets`, `new`, `active_search` |
243
+ | `SECTION_NAME` | `balance`, `positions`, `orders`, `watchlist`, `whats_happening`, `products`, `top_movers`, `explore`, `explore_crypto`, `explore_commodities`, `explore_stocks`, `explore_forex`, `recently_added`, `recent_activity` |
244
+ | `INTERACTION_TYPE` | `tap`, `zoom`, `slide`, `search_clicked`, `order_type_viewed`, `order_type_selected`, `setting_changed`, `leverage_changed`, `tutorial_started`, `tutorial_completed`, `tutorial_navigation`, `candle_period_viewed`, `candle_period_changed`, `favorite_toggled`, `button_clicked`, `contact_support`, `stop_loss_one_click_prompt`, `add_margin`, `remove_margin`, `increase_exposure`, `reduce_exposure`, `flip_position`, `display_hero_card`, `share_pnl_hero_card`, `full_screen_chart`, `payment_token_selector`, `payment_method_changed`, `cancel_trade_with_token`, `slippage_config_opened`, `slippage_config_changed`, `slippage_limit_blocked_order`, `scale_config_changed`, `scale_validation_error_shown`, `tpsl_roe_sign_toggled`, `market_list_filter`, `sort_applied`, `filter_applied`, `chase_backgrounded_converted`, `chase_terminated`, `search_result_tapped`, `search_chip_tapped`, `search_signal_tile_tapped`, `payment_token_selector_dismissed`, `chase_concurrency_limit_hit`, `chase_max_distance_hit`, `chase_reprice`, `close_all_tapped`, `close_all_confirmed`, `close_all_cancelled`, `chart_opened`, `chart_closed`, `order_book_opened`, `order_book_closed`, `related_market_clicked`, `related_markets_header_tapped` |
245
+ | `MAX_SLIPPAGE_SOURCE` | `default`, `user_configured` |
246
+ | `ACTION_TYPE` | `start_trading`, `skip`, `stop_loss_set`, `take_profit_set`, `adl_learn_more`, `learn_more`, `favorite_market`, `unfavorite_market` |
247
+ | `NOTIFICATION_TYPE` | `position_liquidated`, `tp_executed`, `sl_executed`, `limit_order_executed`, `chase_backgrounded` |
248
+ | `CLOSE_TYPE` | `full`, `partial` |
249
+ | `NAVIGATION_METHOD` | `swipe`, `continue_button`, `progress_dot` |
250
+ | `STATUS` | `viewed`, `started`, `completed`, `initiated`, `submitted`, `executed`, `partially_filled`, `failed`, `success`, `already_enabled`, `migration_required`, `not_applicable` |
251
+ | `SCREEN_TYPE` | `markets`, `market_list`, `asset_details`, `trading`, `homescreen`, `perps_home`, `wallet_home_perps_tab`, `position_close`, `leverage`, `tutorial`, `withdrawal`, `tp_sl`, `create_tpsl`, `edit_tpsl`, `deposit_input`, `deposit_review`, `close_all_positions`, `cancel_all_orders`, `pnl_hero_card`, `order_book`, `error`, `market_list_all`, `market_list_crypto`, `market_list_stocks`, `full_screen_chart`, `activity`, `increase_exposure`, `add_margin`, `remove_margin`, `geo_block_notif`, `compliance_block_notif`, `cancel_trade_with_token_toast`, `search_results_shown`, `search_no_results` |
252
+ | `SETTING_TYPE` | `leverage`, `slippage`, `start_price`, `end_price`, `total_orders`, `size_skew` |
253
+ | `SCREEN_NAME` | `connection_error`, `perps_hero_card`, `perps_activity_history`, `perps_home`, `perps_market_details`, `perps_order` |
254
+ | `ACTION` | `connection_retry`, `connection_go_back`, `share`, `add_margin`, `remove_margin`, `edit_tp_sl`, `create_tp_sl`, `tp`, `sl`, `tpsl`, `create_position`, `increase_exposure`, `flip_long_to_short`, `flip_short_to_long`, `abandon_order` |
255
+ | `RISK_MANAGEMENT_SOURCE` | `trade_screen`, `position_screen`, `stop_loss_prompt_banner` |
256
+ | `PERPS_HISTORY_TABS` | `trades`, `orders`, `funding`, `deposits` |
257
+ | `MM_PAY_TOKEN` | `Perps Balance` |
258
+ | `BUTTON_CLICKED` | `deposit`, `withdraw`, `perps_home`, `tutorial`, `tooltip`, `market_list`, `open_position`, `magnifying_glass`, `crypto`, `stocks`, `commodities`, `forex`, `new`, `give_feedback`, `watchlist`, `top_movers`, `whats_happening`, `place_order`, `close`, `reduce_exposure` |
259
+ | `BUTTON_LOCATION` | `perps_home`, `perps_tutorial`, `perps_home_empty_state`, `perps_asset_screen`, `perps_tab`, `trade_menu_action`, `wallet_home`, `market_list`, `screen`, `tooltip`, `perp_market_details`, `order_book`, `full_screen_chart`, `asset_details` |
258
260
 
259
261
  Code: `src/constants/eventNames.ts` `PERPS_EVENT_VALUE`
260
262
 
@@ -31,9 +31,9 @@ Code: `src/services/FeatureFlagConfigurationService.ts` `refreshHip3Config`, `re
31
31
 
32
32
  ## Not read by Core
33
33
 
34
- | Name | What Core does instead |
35
- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
- | `perpsPayWithAnyTokenAllowlistAssets` | Read by the client. See the Mobile doc |
37
- | Terminal market list source | Not a flag. A configured `terminalApi.globalSnapshotUrl` makes the schema-v4 snapshot the market list, except for `skipFilters: true` calls and calls without a snapshot context, which use the provider. Core validates it and falls back to the provider when it is unavailable or invalid. The caller's `useTerminalApi` option chooses the v1 path only when no snapshot URL is set |
34
+ | Name | What Core does instead |
35
+ | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
+ | `perpsPayWithAnyTokenAllowlistAssets` | Read by the client. See the Mobile doc |
37
+ | Terminal market list source | Not a flag. A configured `terminalApi.globalSnapshotUrl` makes each active provider read its own schema-v4 snapshot, both venues in aggregated mode. The HyperLiquid snapshot is the HyperLiquid market list, except for `skipFilters: true` calls and calls without a snapshot context, which use the provider. The Lighter snapshot adds names, categories, metadata, icons, volume, open interest and `marketKey` to the Lighter provider's rows; prices and trading rules stay with the provider. Core validates each snapshot and falls back to that provider alone when its snapshot is unavailable or invalid. The caller's `useTerminalApi` option chooses the v1 path only when no snapshot URL is set |
38
38
 
39
- Code: `src/constants/hyperLiquidConfig.ts` `HIP3_ASSET_MARKET_TYPES`; `src/providers/HyperLiquidProvider.ts`; `src/services/MarketDataService.ts` `getMarkets`; `src/services/TerminalMarketService.ts` `fetchGlobalSnapshot`
39
+ Code: `src/constants/hyperLiquidConfig.ts` `HIP3_ASSET_MARKET_TYPES`; `src/providers/HyperLiquidProvider.ts`; `src/services/MarketDataService.ts` `getMarkets`, `getMarketDataWithPrices`; `src/services/TerminalMarketService.ts` `fetchGlobalSnapshot`; `src/PerpsController.ts` `#buildGlobalSnapshotContexts`
@@ -18,6 +18,7 @@ What `LighterProvider` declares and implements. Lighter is a POC provider; how i
18
18
  | `strategyRules` | `scale`: `minOrders` 2, `maxOrders` 20 (`SCALE_ORDER_COUNT`). With chase advertised, also `chase`: `defaultIntervalMs` 15,000, `minIntervalMs` 1,000, and no `maxActiveSessions`, since Lighter does not cap concurrent chases |
19
19
  | `supportedMarginModes` | `cross`, `isolated` |
20
20
  | `supportedTriggerOrderTypes` | `stop_market`, `stop_limit`, `take_profit_market`, `take_profit_limit` |
21
+ | `attachedTpslGroupLimit` | `takeProfit: 1`, `stopLoss: 1` |
21
22
  | `attachedTpsl` | `submission: 'native-oto-otoco'`, `childCoverage: 'venue-native-zero-size'`, `partialSizes: false`, `lifecycleVerification: 'pending'`, `cancellation: 'explicit-exact-owned-orders'` |
22
23
  | `positionTpsl` | `supportsExpectedPosition: true`, `childOrderIds: 'request-correlated'`, TP `take_profit_market`, SL `stop_market`, `defaultCoverage: 'position-snapshot'` |
23
24
  | `positionTpsl.partialCoverage` | `single: true`, `pair: 'equal-quantity-oco'`, `supportedPairs` `equal-quantity-oco` and `independent`, `replacement: 'cancel-before-create'`, `recovery: 'explicit-current-position-intent'` |
@@ -67,6 +68,10 @@ Code: `src/providers/LighterProvider.ts` constructor, `#placeChaseProbe`, `#plac
67
68
 
68
69
  Code: `src/providers/LighterProvider.ts` `#assertStandardAccount`, `closePosition`, `editOrder`, `updateMargin`, `previewPositionModify`, `getDepositRoutes`, `getWithdrawalRoutes`; `src/utils/lighterNativeEdit.ts`.
69
70
 
71
+ With `terminalApi.globalSnapshotUrl` set, `getMarketDataWithPrices` adds the Lighter snapshot's name, description, icon, category, keywords, tags, listing time, volume, open interest and `marketKey` to each market it lists. Price, change, funding, leverage and the `getMarkets` trading rules stay with the venue. A missing or invalid Lighter snapshot leaves the venue rows unchanged.
72
+
73
+ Code: `src/services/MarketDataService.ts` `getMarketDataWithPrices`.
74
+
70
75
  ## Fees
71
76
 
72
77
  `calculateFees` first resolves the account and refuses a non-Standard one, so a Premium account is never quoted zero. The rate is the market's `makerFee` or `takerFee` from venue metadata (`'0'` when absent). `metamaskFeeRate` is 0 and `chargesMetamaskBuilderFee` is false; no partner or integrator fee is wired.