@metamask-previews/perps-controller 0.0.0-preview-e4aa1532 → 0.0.0-preview-6dfa4aeba
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -11
- package/dist/PerpsController.cjs +66 -2224
- package/dist/PerpsController.cjs.map +1 -1
- package/dist/PerpsController.d.cts +79 -933
- package/dist/PerpsController.d.cts.map +1 -1
- package/dist/PerpsController.d.mts +79 -933
- package/dist/PerpsController.d.mts.map +1 -1
- package/dist/PerpsController.mjs +64 -2221
- package/dist/PerpsController.mjs.map +1 -1
- package/dist/index.cjs +1 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -6
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -6
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -9
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -19
- package/dist/__mocks__/hyperliquidMock.cjs +0 -68
- package/dist/__mocks__/hyperliquidMock.cjs.map +0 -1
- package/dist/__mocks__/hyperliquidMock.d.cts +0 -15
- package/dist/__mocks__/hyperliquidMock.d.cts.map +0 -1
- package/dist/__mocks__/hyperliquidMock.d.mts +0 -15
- package/dist/__mocks__/hyperliquidMock.d.mts.map +0 -1
- package/dist/__mocks__/hyperliquidMock.mjs +0 -65
- package/dist/__mocks__/hyperliquidMock.mjs.map +0 -1
- package/dist/__mocks__/providerMocks.cjs +0 -144
- package/dist/__mocks__/providerMocks.cjs.map +0 -1
- package/dist/__mocks__/providerMocks.d.cts +0 -44
- package/dist/__mocks__/providerMocks.d.cts.map +0 -1
- package/dist/__mocks__/providerMocks.d.mts +0 -44
- package/dist/__mocks__/providerMocks.d.mts.map +0 -1
- package/dist/__mocks__/providerMocks.mjs +0 -136
- package/dist/__mocks__/providerMocks.mjs.map +0 -1
- package/dist/__mocks__/serviceMocks.cjs +0 -187
- package/dist/__mocks__/serviceMocks.cjs.map +0 -1
- package/dist/__mocks__/serviceMocks.d.cts +0 -58
- package/dist/__mocks__/serviceMocks.d.cts.map +0 -1
- package/dist/__mocks__/serviceMocks.d.mts +0 -58
- package/dist/__mocks__/serviceMocks.d.mts.map +0 -1
- package/dist/__mocks__/serviceMocks.mjs +0 -180
- package/dist/__mocks__/serviceMocks.mjs.map +0 -1
- package/dist/aggregation/SubscriptionMultiplexer.cjs +0 -459
- package/dist/aggregation/SubscriptionMultiplexer.cjs.map +0 -1
- package/dist/aggregation/SubscriptionMultiplexer.d.cts +0 -222
- package/dist/aggregation/SubscriptionMultiplexer.d.cts.map +0 -1
- package/dist/aggregation/SubscriptionMultiplexer.d.mts +0 -222
- package/dist/aggregation/SubscriptionMultiplexer.d.mts.map +0 -1
- package/dist/aggregation/SubscriptionMultiplexer.mjs +0 -455
- package/dist/aggregation/SubscriptionMultiplexer.mjs.map +0 -1
- package/dist/aggregation/index.cjs +0 -9
- package/dist/aggregation/index.cjs.map +0 -1
- package/dist/aggregation/index.d.cts +0 -6
- package/dist/aggregation/index.d.cts.map +0 -1
- package/dist/aggregation/index.d.mts +0 -6
- package/dist/aggregation/index.d.mts.map +0 -1
- package/dist/aggregation/index.mjs +0 -5
- package/dist/aggregation/index.mjs.map +0 -1
- package/dist/constants/eventNames.cjs +0 -117
- package/dist/constants/eventNames.cjs.map +0 -1
- package/dist/constants/eventNames.d.cts +0 -106
- package/dist/constants/eventNames.d.cts.map +0 -1
- package/dist/constants/eventNames.d.mts +0 -106
- package/dist/constants/eventNames.d.mts.map +0 -1
- package/dist/constants/eventNames.mjs +0 -114
- package/dist/constants/eventNames.mjs.map +0 -1
- package/dist/constants/hyperLiquidConfig.cjs +0 -366
- package/dist/constants/hyperLiquidConfig.cjs.map +0 -1
- package/dist/constants/hyperLiquidConfig.d.cts +0 -276
- package/dist/constants/hyperLiquidConfig.d.cts.map +0 -1
- package/dist/constants/hyperLiquidConfig.d.mts +0 -276
- package/dist/constants/hyperLiquidConfig.d.mts.map +0 -1
- package/dist/constants/hyperLiquidConfig.mjs +0 -357
- package/dist/constants/hyperLiquidConfig.mjs.map +0 -1
- package/dist/constants/index.cjs +0 -23
- package/dist/constants/index.cjs.map +0 -1
- package/dist/constants/index.d.cts +0 -7
- package/dist/constants/index.d.cts.map +0 -1
- package/dist/constants/index.d.mts +0 -7
- package/dist/constants/index.d.mts.map +0 -1
- package/dist/constants/index.mjs +0 -7
- package/dist/constants/index.mjs.map +0 -1
- package/dist/constants/orderTypes.cjs +0 -31
- package/dist/constants/orderTypes.cjs.map +0 -1
- package/dist/constants/orderTypes.d.cts +0 -19
- package/dist/constants/orderTypes.d.cts.map +0 -1
- package/dist/constants/orderTypes.d.mts +0 -19
- package/dist/constants/orderTypes.d.mts.map +0 -1
- package/dist/constants/orderTypes.mjs +0 -27
- package/dist/constants/orderTypes.mjs.map +0 -1
- package/dist/constants/performanceMetrics.cjs +0 -61
- package/dist/constants/performanceMetrics.cjs.map +0 -1
- package/dist/constants/performanceMetrics.d.cts +0 -44
- package/dist/constants/performanceMetrics.d.cts.map +0 -1
- package/dist/constants/performanceMetrics.d.mts +0 -44
- package/dist/constants/performanceMetrics.d.mts.map +0 -1
- package/dist/constants/performanceMetrics.mjs +0 -58
- package/dist/constants/performanceMetrics.mjs.map +0 -1
- package/dist/constants/perpsConfig.cjs +0 -461
- package/dist/constants/perpsConfig.cjs.map +0 -1
- package/dist/constants/perpsConfig.d.cts +0 -343
- package/dist/constants/perpsConfig.d.cts.map +0 -1
- package/dist/constants/perpsConfig.d.mts +0 -343
- package/dist/constants/perpsConfig.d.mts.map +0 -1
- package/dist/constants/perpsConfig.mjs +0 -458
- package/dist/constants/perpsConfig.mjs.map +0 -1
- package/dist/constants/perpsErrorCodes.cjs +0 -79
- package/dist/constants/perpsErrorCodes.cjs.map +0 -1
- package/dist/constants/perpsErrorCodes.d.cts +0 -64
- package/dist/constants/perpsErrorCodes.d.cts.map +0 -1
- package/dist/constants/perpsErrorCodes.d.mts +0 -64
- package/dist/constants/perpsErrorCodes.d.mts.map +0 -1
- package/dist/constants/perpsErrorCodes.mjs +0 -76
- package/dist/constants/perpsErrorCodes.mjs.map +0 -1
- package/dist/platform-services/HyperLiquidClientService.cjs +0 -857
- package/dist/platform-services/HyperLiquidClientService.cjs.map +0 -1
- package/dist/platform-services/HyperLiquidClientService.d.cts +0 -263
- package/dist/platform-services/HyperLiquidClientService.d.cts.map +0 -1
- package/dist/platform-services/HyperLiquidClientService.d.mts +0 -263
- package/dist/platform-services/HyperLiquidClientService.d.mts.map +0 -1
- package/dist/platform-services/HyperLiquidClientService.mjs +0 -853
- package/dist/platform-services/HyperLiquidClientService.mjs.map +0 -1
- package/dist/platform-services/HyperLiquidSubscriptionService.cjs +0 -2170
- package/dist/platform-services/HyperLiquidSubscriptionService.cjs.map +0 -1
- package/dist/platform-services/HyperLiquidSubscriptionService.d.cts +0 -424
- package/dist/platform-services/HyperLiquidSubscriptionService.d.cts.map +0 -1
- package/dist/platform-services/HyperLiquidSubscriptionService.d.mts +0 -424
- package/dist/platform-services/HyperLiquidSubscriptionService.d.mts.map +0 -1
- package/dist/platform-services/HyperLiquidSubscriptionService.mjs +0 -2166
- package/dist/platform-services/HyperLiquidSubscriptionService.mjs.map +0 -1
- package/dist/platform-services/HyperLiquidWalletService.cjs +0 -140
- package/dist/platform-services/HyperLiquidWalletService.cjs.map +0 -1
- package/dist/platform-services/HyperLiquidWalletService.d.cts +0 -78
- package/dist/platform-services/HyperLiquidWalletService.d.cts.map +0 -1
- package/dist/platform-services/HyperLiquidWalletService.d.mts +0 -78
- package/dist/platform-services/HyperLiquidWalletService.d.mts.map +0 -1
- package/dist/platform-services/HyperLiquidWalletService.mjs +0 -136
- package/dist/platform-services/HyperLiquidWalletService.mjs.map +0 -1
- package/dist/providers/AggregatedPerpsProvider.cjs +0 -777
- package/dist/providers/AggregatedPerpsProvider.cjs.map +0 -1
- package/dist/providers/AggregatedPerpsProvider.d.cts +0 -466
- package/dist/providers/AggregatedPerpsProvider.d.cts.map +0 -1
- package/dist/providers/AggregatedPerpsProvider.d.mts +0 -466
- package/dist/providers/AggregatedPerpsProvider.d.mts.map +0 -1
- package/dist/providers/AggregatedPerpsProvider.mjs +0 -773
- package/dist/providers/AggregatedPerpsProvider.mjs.map +0 -1
- package/dist/providers/HyperLiquidProvider.cjs +0 -5172
- package/dist/providers/HyperLiquidProvider.cjs.map +0 -1
- package/dist/providers/HyperLiquidProvider.d.cts +0 -881
- package/dist/providers/HyperLiquidProvider.d.cts.map +0 -1
- package/dist/providers/HyperLiquidProvider.d.mts +0 -881
- package/dist/providers/HyperLiquidProvider.d.mts.map +0 -1
- package/dist/providers/HyperLiquidProvider.mjs +0 -5168
- package/dist/providers/HyperLiquidProvider.mjs.map +0 -1
- package/dist/providers/index.cjs +0 -11
- package/dist/providers/index.cjs.map +0 -1
- package/dist/providers/index.d.cts +0 -6
- package/dist/providers/index.d.cts.map +0 -1
- package/dist/providers/index.d.mts +0 -6
- package/dist/providers/index.d.mts.map +0 -1
- package/dist/providers/index.mjs +0 -6
- package/dist/providers/index.mjs.map +0 -1
- package/dist/routing/ProviderRouter.cjs +0 -148
- package/dist/routing/ProviderRouter.cjs.map +0 -1
- package/dist/routing/ProviderRouter.d.cts +0 -124
- package/dist/routing/ProviderRouter.d.cts.map +0 -1
- package/dist/routing/ProviderRouter.d.mts +0 -124
- package/dist/routing/ProviderRouter.d.mts.map +0 -1
- package/dist/routing/ProviderRouter.mjs +0 -144
- package/dist/routing/ProviderRouter.mjs.map +0 -1
- package/dist/routing/index.cjs +0 -9
- package/dist/routing/index.cjs.map +0 -1
- package/dist/routing/index.d.cts +0 -6
- package/dist/routing/index.d.cts.map +0 -1
- package/dist/routing/index.d.mts +0 -6
- package/dist/routing/index.d.mts.map +0 -1
- package/dist/routing/index.mjs +0 -5
- package/dist/routing/index.mjs.map +0 -1
- package/dist/selectors.cjs +0 -161
- package/dist/selectors.cjs.map +0 -1
- package/dist/selectors.d.cts +0 -345
- package/dist/selectors.d.cts.map +0 -1
- package/dist/selectors.d.mts +0 -345
- package/dist/selectors.d.mts.map +0 -1
- package/dist/selectors.mjs +0 -153
- package/dist/selectors.mjs.map +0 -1
- package/dist/services/AccountService.cjs +0 -313
- package/dist/services/AccountService.cjs.map +0 -1
- package/dist/services/AccountService.d.cts +0 -53
- package/dist/services/AccountService.d.cts.map +0 -1
- package/dist/services/AccountService.d.mts +0 -53
- package/dist/services/AccountService.d.mts.map +0 -1
- package/dist/services/AccountService.mjs +0 -309
- package/dist/services/AccountService.mjs.map +0 -1
- package/dist/services/DataLakeService.cjs +0 -219
- package/dist/services/DataLakeService.cjs.map +0 -1
- package/dist/services/DataLakeService.d.cts +0 -49
- package/dist/services/DataLakeService.d.cts.map +0 -1
- package/dist/services/DataLakeService.d.mts +0 -49
- package/dist/services/DataLakeService.d.mts.map +0 -1
- package/dist/services/DataLakeService.mjs +0 -215
- package/dist/services/DataLakeService.mjs.map +0 -1
- package/dist/services/DepositService.cjs +0 -96
- package/dist/services/DepositService.cjs.map +0 -1
- package/dist/services/DepositService.d.cts +0 -37
- package/dist/services/DepositService.d.cts.map +0 -1
- package/dist/services/DepositService.d.mts +0 -37
- package/dist/services/DepositService.d.mts.map +0 -1
- package/dist/services/DepositService.mjs +0 -92
- package/dist/services/DepositService.mjs.map +0 -1
- package/dist/services/EligibilityService.cjs +0 -156
- package/dist/services/EligibilityService.cjs.map +0 -1
- package/dist/services/EligibilityService.d.cts +0 -48
- package/dist/services/EligibilityService.d.cts.map +0 -1
- package/dist/services/EligibilityService.d.mts +0 -48
- package/dist/services/EligibilityService.d.mts.map +0 -1
- package/dist/services/EligibilityService.mjs +0 -152
- package/dist/services/EligibilityService.mjs.map +0 -1
- package/dist/services/FeatureFlagConfigurationService.cjs +0 -258
- package/dist/services/FeatureFlagConfigurationService.cjs.map +0 -1
- package/dist/services/FeatureFlagConfigurationService.d.cts +0 -100
- package/dist/services/FeatureFlagConfigurationService.d.cts.map +0 -1
- package/dist/services/FeatureFlagConfigurationService.d.mts +0 -100
- package/dist/services/FeatureFlagConfigurationService.d.mts.map +0 -1
- package/dist/services/FeatureFlagConfigurationService.mjs +0 -254
- package/dist/services/FeatureFlagConfigurationService.mjs.map +0 -1
- package/dist/services/MarketDataService.cjs +0 -875
- package/dist/services/MarketDataService.cjs.map +0 -1
- package/dist/services/MarketDataService.d.cts +0 -289
- package/dist/services/MarketDataService.d.cts.map +0 -1
- package/dist/services/MarketDataService.d.mts +0 -289
- package/dist/services/MarketDataService.d.mts.map +0 -1
- package/dist/services/MarketDataService.mjs +0 -871
- package/dist/services/MarketDataService.mjs.map +0 -1
- package/dist/services/RewardsIntegrationService.cjs +0 -94
- package/dist/services/RewardsIntegrationService.cjs.map +0 -1
- package/dist/services/RewardsIntegrationService.d.cts +0 -30
- package/dist/services/RewardsIntegrationService.d.cts.map +0 -1
- package/dist/services/RewardsIntegrationService.d.mts +0 -30
- package/dist/services/RewardsIntegrationService.d.mts.map +0 -1
- package/dist/services/RewardsIntegrationService.mjs +0 -90
- package/dist/services/RewardsIntegrationService.mjs.map +0 -1
- package/dist/services/ServiceContext.cjs +0 -3
- package/dist/services/ServiceContext.cjs.map +0 -1
- package/dist/services/ServiceContext.d.cts +0 -110
- package/dist/services/ServiceContext.d.cts.map +0 -1
- package/dist/services/ServiceContext.d.mts +0 -110
- package/dist/services/ServiceContext.d.mts.map +0 -1
- package/dist/services/ServiceContext.mjs +0 -2
- package/dist/services/ServiceContext.mjs.map +0 -1
- package/dist/services/TradingService.cjs +0 -1481
- package/dist/services/TradingService.cjs.map +0 -1
- package/dist/services/TradingService.d.cts +0 -308
- package/dist/services/TradingService.d.cts.map +0 -1
- package/dist/services/TradingService.d.mts +0 -308
- package/dist/services/TradingService.d.mts.map +0 -1
- package/dist/services/TradingService.mjs +0 -1477
- package/dist/services/TradingService.mjs.map +0 -1
- package/dist/services/index.cjs +0 -26
- package/dist/services/index.cjs.map +0 -1
- package/dist/services/index.d.cts +0 -11
- package/dist/services/index.d.cts.map +0 -1
- package/dist/services/index.d.mts +0 -11
- package/dist/services/index.d.mts.map +0 -1
- package/dist/services/index.mjs +0 -10
- package/dist/services/index.mjs.map +0 -1
- package/dist/services/utils.cjs +0 -16
- package/dist/services/utils.cjs.map +0 -1
- package/dist/services/utils.d.cts +0 -8
- package/dist/services/utils.d.cts.map +0 -1
- package/dist/services/utils.d.mts +0 -8
- package/dist/services/utils.d.mts.map +0 -1
- package/dist/services/utils.mjs +0 -12
- package/dist/services/utils.mjs.map +0 -1
- package/dist/types/chart.cjs +0 -42
- package/dist/types/chart.cjs.map +0 -1
- package/dist/types/chart.d.cts +0 -62
- package/dist/types/chart.d.cts.map +0 -1
- package/dist/types/chart.d.mts +0 -62
- package/dist/types/chart.d.mts.map +0 -1
- package/dist/types/chart.mjs +0 -39
- package/dist/types/chart.mjs.map +0 -1
- package/dist/types/hyperliquid-types.cjs +0 -3
- package/dist/types/hyperliquid-types.cjs.map +0 -1
- package/dist/types/hyperliquid-types.d.cts +0 -52
- package/dist/types/hyperliquid-types.d.cts.map +0 -1
- package/dist/types/hyperliquid-types.d.mts +0 -52
- package/dist/types/hyperliquid-types.d.mts.map +0 -1
- package/dist/types/hyperliquid-types.mjs +0 -2
- package/dist/types/hyperliquid-types.mjs.map +0 -1
- package/dist/types/index.cjs +0 -96
- package/dist/types/index.cjs.map +0 -1
- package/dist/types/index.d.cts +0 -1153
- package/dist/types/index.d.cts.map +0 -1
- package/dist/types/index.d.mts +0 -1153
- package/dist/types/index.d.mts.map +0 -1
- package/dist/types/index.mjs +0 -79
- package/dist/types/index.mjs.map +0 -1
- package/dist/types/transactionTypes.cjs +0 -28
- package/dist/types/transactionTypes.cjs.map +0 -1
- package/dist/types/transactionTypes.d.cts +0 -64
- package/dist/types/transactionTypes.d.cts.map +0 -1
- package/dist/types/transactionTypes.d.mts +0 -64
- package/dist/types/transactionTypes.d.mts.map +0 -1
- package/dist/types/transactionTypes.mjs +0 -23
- package/dist/types/transactionTypes.mjs.map +0 -1
- package/dist/utils/accountUtils.cjs +0 -65
- package/dist/utils/accountUtils.cjs.map +0 -1
- package/dist/utils/accountUtils.d.cts +0 -26
- package/dist/utils/accountUtils.d.cts.map +0 -1
- package/dist/utils/accountUtils.d.mts +0 -26
- package/dist/utils/accountUtils.d.mts.map +0 -1
- package/dist/utils/accountUtils.mjs +0 -61
- package/dist/utils/accountUtils.mjs.map +0 -1
- package/dist/utils/amountConversion.cjs +0 -61
- package/dist/utils/amountConversion.cjs.map +0 -1
- package/dist/utils/amountConversion.d.cts +0 -16
- package/dist/utils/amountConversion.d.cts.map +0 -1
- package/dist/utils/amountConversion.d.mts +0 -16
- package/dist/utils/amountConversion.d.mts.map +0 -1
- package/dist/utils/amountConversion.mjs +0 -54
- package/dist/utils/amountConversion.mjs.map +0 -1
- package/dist/utils/chartUtils.cjs +0 -98
- package/dist/utils/chartUtils.cjs.map +0 -1
- package/dist/utils/chartUtils.d.cts +0 -14
- package/dist/utils/chartUtils.d.cts.map +0 -1
- package/dist/utils/chartUtils.d.mts +0 -14
- package/dist/utils/chartUtils.d.mts.map +0 -1
- package/dist/utils/chartUtils.mjs +0 -94
- package/dist/utils/chartUtils.mjs.map +0 -1
- package/dist/utils/errorUtils.cjs +0 -22
- package/dist/utils/errorUtils.cjs.map +0 -1
- package/dist/utils/errorUtils.d.cts +0 -13
- package/dist/utils/errorUtils.d.cts.map +0 -1
- package/dist/utils/errorUtils.d.mts +0 -13
- package/dist/utils/errorUtils.d.mts.map +0 -1
- package/dist/utils/errorUtils.mjs +0 -18
- package/dist/utils/errorUtils.mjs.map +0 -1
- package/dist/utils/formatUtils.cjs +0 -987
- package/dist/utils/formatUtils.cjs.map +0 -1
- package/dist/utils/formatUtils.d.cts +0 -387
- package/dist/utils/formatUtils.d.cts.map +0 -1
- package/dist/utils/formatUtils.d.mts +0 -387
- package/dist/utils/formatUtils.d.mts.map +0 -1
- package/dist/utils/formatUtils.mjs +0 -966
- package/dist/utils/formatUtils.mjs.map +0 -1
- package/dist/utils/hyperLiquidAdapter.cjs +0 -454
- package/dist/utils/hyperLiquidAdapter.cjs.map +0 -1
- package/dist/utils/hyperLiquidAdapter.d.cts +0 -158
- package/dist/utils/hyperLiquidAdapter.d.cts.map +0 -1
- package/dist/utils/hyperLiquidAdapter.d.mts +0 -158
- package/dist/utils/hyperLiquidAdapter.d.mts.map +0 -1
- package/dist/utils/hyperLiquidAdapter.mjs +0 -439
- package/dist/utils/hyperLiquidAdapter.mjs.map +0 -1
- package/dist/utils/hyperLiquidOrderBookProcessor.cjs +0 -89
- package/dist/utils/hyperLiquidOrderBookProcessor.cjs.map +0 -1
- package/dist/utils/hyperLiquidOrderBookProcessor.d.cts +0 -58
- package/dist/utils/hyperLiquidOrderBookProcessor.d.cts.map +0 -1
- package/dist/utils/hyperLiquidOrderBookProcessor.d.mts +0 -58
- package/dist/utils/hyperLiquidOrderBookProcessor.d.mts.map +0 -1
- package/dist/utils/hyperLiquidOrderBookProcessor.mjs +0 -84
- package/dist/utils/hyperLiquidOrderBookProcessor.mjs.map +0 -1
- package/dist/utils/hyperLiquidValidation.cjs +0 -426
- package/dist/utils/hyperLiquidValidation.cjs.map +0 -1
- package/dist/utils/hyperLiquidValidation.d.cts +0 -143
- package/dist/utils/hyperLiquidValidation.d.cts.map +0 -1
- package/dist/utils/hyperLiquidValidation.d.mts +0 -143
- package/dist/utils/hyperLiquidValidation.d.mts.map +0 -1
- package/dist/utils/hyperLiquidValidation.mjs +0 -413
- package/dist/utils/hyperLiquidValidation.mjs.map +0 -1
- package/dist/utils/idUtils.cjs +0 -50
- package/dist/utils/idUtils.cjs.map +0 -1
- package/dist/utils/idUtils.d.cts +0 -38
- package/dist/utils/idUtils.d.cts.map +0 -1
- package/dist/utils/idUtils.d.mts +0 -38
- package/dist/utils/idUtils.d.mts.map +0 -1
- package/dist/utils/idUtils.mjs +0 -42
- package/dist/utils/idUtils.mjs.map +0 -1
- package/dist/utils/marginUtils.cjs +0 -137
- package/dist/utils/marginUtils.cjs.map +0 -1
- package/dist/utils/marginUtils.d.cts +0 -64
- package/dist/utils/marginUtils.d.cts.map +0 -1
- package/dist/utils/marginUtils.d.mts +0 -64
- package/dist/utils/marginUtils.d.mts.map +0 -1
- package/dist/utils/marginUtils.mjs +0 -131
- package/dist/utils/marginUtils.mjs.map +0 -1
- package/dist/utils/marketDataTransform.cjs +0 -227
- package/dist/utils/marketDataTransform.cjs.map +0 -1
- package/dist/utils/marketDataTransform.d.cts +0 -45
- package/dist/utils/marketDataTransform.d.cts.map +0 -1
- package/dist/utils/marketDataTransform.d.mts +0 -45
- package/dist/utils/marketDataTransform.d.mts.map +0 -1
- package/dist/utils/marketDataTransform.mjs +0 -220
- package/dist/utils/marketDataTransform.mjs.map +0 -1
- package/dist/utils/marketUtils.cjs +0 -420
- package/dist/utils/marketUtils.cjs.map +0 -1
- package/dist/utils/marketUtils.d.cts +0 -227
- package/dist/utils/marketUtils.d.cts.map +0 -1
- package/dist/utils/marketUtils.d.mts +0 -227
- package/dist/utils/marketUtils.d.mts.map +0 -1
- package/dist/utils/marketUtils.mjs +0 -404
- package/dist/utils/marketUtils.mjs.map +0 -1
- package/dist/utils/orderBookGrouping.cjs +0 -151
- package/dist/utils/orderBookGrouping.cjs.map +0 -1
- package/dist/utils/orderBookGrouping.d.cts +0 -76
- package/dist/utils/orderBookGrouping.d.cts.map +0 -1
- package/dist/utils/orderBookGrouping.d.mts +0 -76
- package/dist/utils/orderBookGrouping.d.mts.map +0 -1
- package/dist/utils/orderBookGrouping.mjs +0 -143
- package/dist/utils/orderBookGrouping.mjs.map +0 -1
- package/dist/utils/orderCalculations.cjs +0 -283
- package/dist/utils/orderCalculations.cjs.map +0 -1
- package/dist/utils/orderCalculations.d.cts +0 -107
- package/dist/utils/orderCalculations.d.cts.map +0 -1
- package/dist/utils/orderCalculations.d.mts +0 -107
- package/dist/utils/orderCalculations.d.mts.map +0 -1
- package/dist/utils/orderCalculations.mjs +0 -274
- package/dist/utils/orderCalculations.mjs.map +0 -1
- package/dist/utils/orderUtils.cjs +0 -159
- package/dist/utils/orderUtils.cjs.map +0 -1
- package/dist/utils/orderUtils.d.cts +0 -66
- package/dist/utils/orderUtils.d.cts.map +0 -1
- package/dist/utils/orderUtils.d.mts +0 -66
- package/dist/utils/orderUtils.d.mts.map +0 -1
- package/dist/utils/orderUtils.mjs +0 -151
- package/dist/utils/orderUtils.mjs.map +0 -1
- package/dist/utils/pnlCalculations.cjs +0 -107
- package/dist/utils/pnlCalculations.cjs.map +0 -1
- package/dist/utils/pnlCalculations.d.cts +0 -79
- package/dist/utils/pnlCalculations.d.cts.map +0 -1
- package/dist/utils/pnlCalculations.d.mts +0 -79
- package/dist/utils/pnlCalculations.d.mts.map +0 -1
- package/dist/utils/pnlCalculations.mjs +0 -97
- package/dist/utils/pnlCalculations.mjs.map +0 -1
- package/dist/utils/positionCalculations.cjs +0 -176
- package/dist/utils/positionCalculations.cjs.map +0 -1
- package/dist/utils/positionCalculations.d.cts +0 -85
- package/dist/utils/positionCalculations.d.cts.map +0 -1
- package/dist/utils/positionCalculations.d.mts +0 -85
- package/dist/utils/positionCalculations.d.mts.map +0 -1
- package/dist/utils/positionCalculations.mjs +0 -165
- package/dist/utils/positionCalculations.mjs.map +0 -1
- package/dist/utils/sortMarkets.cjs +0 -88
- package/dist/utils/sortMarkets.cjs.map +0 -1
- package/dist/utils/sortMarkets.d.cts +0 -21
- package/dist/utils/sortMarkets.d.cts.map +0 -1
- package/dist/utils/sortMarkets.d.mts +0 -21
- package/dist/utils/sortMarkets.d.mts.map +0 -1
- package/dist/utils/sortMarkets.mjs +0 -84
- package/dist/utils/sortMarkets.mjs.map +0 -1
- package/dist/utils/standaloneInfoClient.cjs +0 -34
- package/dist/utils/standaloneInfoClient.cjs.map +0 -1
- package/dist/utils/standaloneInfoClient.d.cts +0 -31
- package/dist/utils/standaloneInfoClient.d.cts.map +0 -1
- package/dist/utils/standaloneInfoClient.d.mts +0 -31
- package/dist/utils/standaloneInfoClient.d.mts.map +0 -1
- package/dist/utils/standaloneInfoClient.mjs +0 -30
- package/dist/utils/standaloneInfoClient.mjs.map +0 -1
- package/dist/utils/stringParseUtils.cjs +0 -49
- package/dist/utils/stringParseUtils.cjs.map +0 -1
- package/dist/utils/stringParseUtils.d.cts +0 -35
- package/dist/utils/stringParseUtils.d.cts.map +0 -1
- package/dist/utils/stringParseUtils.d.mts +0 -35
- package/dist/utils/stringParseUtils.d.mts.map +0 -1
- package/dist/utils/stringParseUtils.mjs +0 -44
- package/dist/utils/stringParseUtils.mjs.map +0 -1
- package/dist/utils/time.cjs +0 -37
- package/dist/utils/time.cjs.map +0 -1
- package/dist/utils/time.d.cts +0 -17
- package/dist/utils/time.d.cts.map +0 -1
- package/dist/utils/time.d.mts +0 -17
- package/dist/utils/time.d.mts.map +0 -1
- package/dist/utils/time.mjs +0 -33
- package/dist/utils/time.mjs.map +0 -1
- package/dist/utils/tpslValidation.cjs +0 -505
- package/dist/utils/tpslValidation.cjs.map +0 -1
- package/dist/utils/tpslValidation.d.cts +0 -182
- package/dist/utils/tpslValidation.d.cts.map +0 -1
- package/dist/utils/tpslValidation.d.mts +0 -182
- package/dist/utils/tpslValidation.d.mts.map +0 -1
- package/dist/utils/tpslValidation.mjs +0 -482
- package/dist/utils/tpslValidation.mjs.map +0 -1
- package/dist/utils/transactionUtils.cjs +0 -36
- package/dist/utils/transactionUtils.cjs.map +0 -1
- package/dist/utils/transactionUtils.d.cts +0 -17
- package/dist/utils/transactionUtils.d.cts.map +0 -1
- package/dist/utils/transactionUtils.d.mts +0 -17
- package/dist/utils/transactionUtils.d.mts.map +0 -1
- package/dist/utils/transactionUtils.mjs +0 -32
- package/dist/utils/transactionUtils.mjs.map +0 -1
- package/dist/utils/wait.cjs +0 -12
- package/dist/utils/wait.cjs.map +0 -1
- package/dist/utils/wait.d.cts +0 -8
- package/dist/utils/wait.d.cts.map +0 -1
- package/dist/utils/wait.d.mts +0 -8
- package/dist/utils/wait.d.mts.map +0 -1
- package/dist/utils/wait.mjs +0 -8
- package/dist/utils/wait.mjs.map +0 -1
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Order book level structure for grouping
|
|
3
|
-
*/
|
|
4
|
-
export type OrderBookLevel = {
|
|
5
|
-
price: string;
|
|
6
|
-
size: string;
|
|
7
|
-
total: string;
|
|
8
|
-
notional: string;
|
|
9
|
-
totalNotional: string;
|
|
10
|
-
};
|
|
11
|
-
/**
|
|
12
|
-
* Maximum API levels to request from Hyperliquid L2Book API.
|
|
13
|
-
* The API returns at most ~20 levels per side when using nSigFigs aggregation.
|
|
14
|
-
*/
|
|
15
|
-
export declare const MAX_ORDER_BOOK_LEVELS = 20;
|
|
16
|
-
/**
|
|
17
|
-
* Parameters for Hyperliquid L2Book API aggregation.
|
|
18
|
-
*/
|
|
19
|
-
export type AggregationParams = {
|
|
20
|
-
nSigFigs: 2 | 3 | 4 | 5;
|
|
21
|
-
mantissa?: 2 | 5;
|
|
22
|
-
};
|
|
23
|
-
/**
|
|
24
|
-
* Calculate nSigFigs and mantissa based on grouping and price.
|
|
25
|
-
* These parameters match Hyperliquid's L2Book API aggregation:
|
|
26
|
-
* - nSigFigs: 5, mantissa: 2 → finest granularity (~$1-2 for BTC)
|
|
27
|
-
* - nSigFigs: 5, mantissa: 5 → ~$5 increments for BTC
|
|
28
|
-
* - nSigFigs: 4 → ~$10 increments for BTC
|
|
29
|
-
* - nSigFigs: 3 → ~$100 increments for BTC
|
|
30
|
-
* - nSigFigs: 2 → ~$1000 increments for BTC (widest range)
|
|
31
|
-
*
|
|
32
|
-
* mantissa is only applicable when nSigFigs is 5.
|
|
33
|
-
*
|
|
34
|
-
* @param grouping - The price grouping increment
|
|
35
|
-
* @param price - The current mid price
|
|
36
|
-
* @returns Aggregation parameters for the API
|
|
37
|
-
*/
|
|
38
|
-
export declare function calculateAggregationParams(grouping: number, price: number): AggregationParams;
|
|
39
|
-
/**
|
|
40
|
-
* Calculate dynamic grouping options based on asset's mid price.
|
|
41
|
-
* Uses "1-2-5 per decade" scale anchored to price magnitude.
|
|
42
|
-
*
|
|
43
|
-
* @param midPrice - The current mid price of the asset
|
|
44
|
-
* @returns Array of grouping options suitable for the price magnitude
|
|
45
|
-
* @example
|
|
46
|
-
* calculateGroupingOptions(87000) → [1, 2, 5, 10, 100, 1000] // BTC
|
|
47
|
-
* calculateGroupingOptions(33) → [0.001, 0.002, 0.005, 0.01, 0.1, 1] // HYPE
|
|
48
|
-
* calculateGroupingOptions(0.002) → [0.000001, 0.00001, 0.0001] // PUMP
|
|
49
|
-
*/
|
|
50
|
-
export declare function calculateGroupingOptions(midPrice: number): number[];
|
|
51
|
-
/**
|
|
52
|
-
* Format grouping value for display (e.g., "0.001", "1", "100").
|
|
53
|
-
*
|
|
54
|
-
* @param value - The grouping value to format
|
|
55
|
-
* @returns Formatted string representation
|
|
56
|
-
*/
|
|
57
|
-
export declare function formatGroupingLabel(value: number): string;
|
|
58
|
-
/**
|
|
59
|
-
* Select a sensible default grouping option.
|
|
60
|
-
* Picks a middle option that gives reasonable granularity.
|
|
61
|
-
*
|
|
62
|
-
* @param options - Array of available grouping options
|
|
63
|
-
* @returns The recommended default grouping value
|
|
64
|
-
*/
|
|
65
|
-
export declare function selectDefaultGrouping(options: number[]): number;
|
|
66
|
-
/**
|
|
67
|
-
* Aggregate order book levels by price grouping.
|
|
68
|
-
* Groups prices into buckets, sums sizes, and recalculates cumulative totals.
|
|
69
|
-
*
|
|
70
|
-
* @param levels - Raw order book levels from API
|
|
71
|
-
* @param groupingSize - Price bucket size (e.g., 10 means group by $10 increments)
|
|
72
|
-
* @param side - 'bid' rounds down to bucket, 'ask' rounds up to bucket
|
|
73
|
-
* @returns Aggregated order book levels
|
|
74
|
-
*/
|
|
75
|
-
export declare function aggregateOrderBookLevels(levels: OrderBookLevel[], groupingSize: number, side: 'bid' | 'ask'): OrderBookLevel[];
|
|
76
|
-
//# sourceMappingURL=orderBookGrouping.d.cts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"orderBookGrouping.d.cts","sourceRoot":"","sources":["../../src/utils/orderBookGrouping.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,qBAAqB,KAAK,CAAC;AAExC;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACxB,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;CAClB,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,0BAA0B,CACxC,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,GACZ,iBAAiB,CAyBnB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,CAUnE;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOzD;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,CAI/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,cAAc,EAAE,EACxB,YAAY,EAAE,MAAM,EACpB,IAAI,EAAE,KAAK,GAAG,KAAK,GAClB,cAAc,EAAE,CA0DlB"}
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Order book level structure for grouping
|
|
3
|
-
*/
|
|
4
|
-
export type OrderBookLevel = {
|
|
5
|
-
price: string;
|
|
6
|
-
size: string;
|
|
7
|
-
total: string;
|
|
8
|
-
notional: string;
|
|
9
|
-
totalNotional: string;
|
|
10
|
-
};
|
|
11
|
-
/**
|
|
12
|
-
* Maximum API levels to request from Hyperliquid L2Book API.
|
|
13
|
-
* The API returns at most ~20 levels per side when using nSigFigs aggregation.
|
|
14
|
-
*/
|
|
15
|
-
export declare const MAX_ORDER_BOOK_LEVELS = 20;
|
|
16
|
-
/**
|
|
17
|
-
* Parameters for Hyperliquid L2Book API aggregation.
|
|
18
|
-
*/
|
|
19
|
-
export type AggregationParams = {
|
|
20
|
-
nSigFigs: 2 | 3 | 4 | 5;
|
|
21
|
-
mantissa?: 2 | 5;
|
|
22
|
-
};
|
|
23
|
-
/**
|
|
24
|
-
* Calculate nSigFigs and mantissa based on grouping and price.
|
|
25
|
-
* These parameters match Hyperliquid's L2Book API aggregation:
|
|
26
|
-
* - nSigFigs: 5, mantissa: 2 → finest granularity (~$1-2 for BTC)
|
|
27
|
-
* - nSigFigs: 5, mantissa: 5 → ~$5 increments for BTC
|
|
28
|
-
* - nSigFigs: 4 → ~$10 increments for BTC
|
|
29
|
-
* - nSigFigs: 3 → ~$100 increments for BTC
|
|
30
|
-
* - nSigFigs: 2 → ~$1000 increments for BTC (widest range)
|
|
31
|
-
*
|
|
32
|
-
* mantissa is only applicable when nSigFigs is 5.
|
|
33
|
-
*
|
|
34
|
-
* @param grouping - The price grouping increment
|
|
35
|
-
* @param price - The current mid price
|
|
36
|
-
* @returns Aggregation parameters for the API
|
|
37
|
-
*/
|
|
38
|
-
export declare function calculateAggregationParams(grouping: number, price: number): AggregationParams;
|
|
39
|
-
/**
|
|
40
|
-
* Calculate dynamic grouping options based on asset's mid price.
|
|
41
|
-
* Uses "1-2-5 per decade" scale anchored to price magnitude.
|
|
42
|
-
*
|
|
43
|
-
* @param midPrice - The current mid price of the asset
|
|
44
|
-
* @returns Array of grouping options suitable for the price magnitude
|
|
45
|
-
* @example
|
|
46
|
-
* calculateGroupingOptions(87000) → [1, 2, 5, 10, 100, 1000] // BTC
|
|
47
|
-
* calculateGroupingOptions(33) → [0.001, 0.002, 0.005, 0.01, 0.1, 1] // HYPE
|
|
48
|
-
* calculateGroupingOptions(0.002) → [0.000001, 0.00001, 0.0001] // PUMP
|
|
49
|
-
*/
|
|
50
|
-
export declare function calculateGroupingOptions(midPrice: number): number[];
|
|
51
|
-
/**
|
|
52
|
-
* Format grouping value for display (e.g., "0.001", "1", "100").
|
|
53
|
-
*
|
|
54
|
-
* @param value - The grouping value to format
|
|
55
|
-
* @returns Formatted string representation
|
|
56
|
-
*/
|
|
57
|
-
export declare function formatGroupingLabel(value: number): string;
|
|
58
|
-
/**
|
|
59
|
-
* Select a sensible default grouping option.
|
|
60
|
-
* Picks a middle option that gives reasonable granularity.
|
|
61
|
-
*
|
|
62
|
-
* @param options - Array of available grouping options
|
|
63
|
-
* @returns The recommended default grouping value
|
|
64
|
-
*/
|
|
65
|
-
export declare function selectDefaultGrouping(options: number[]): number;
|
|
66
|
-
/**
|
|
67
|
-
* Aggregate order book levels by price grouping.
|
|
68
|
-
* Groups prices into buckets, sums sizes, and recalculates cumulative totals.
|
|
69
|
-
*
|
|
70
|
-
* @param levels - Raw order book levels from API
|
|
71
|
-
* @param groupingSize - Price bucket size (e.g., 10 means group by $10 increments)
|
|
72
|
-
* @param side - 'bid' rounds down to bucket, 'ask' rounds up to bucket
|
|
73
|
-
* @returns Aggregated order book levels
|
|
74
|
-
*/
|
|
75
|
-
export declare function aggregateOrderBookLevels(levels: OrderBookLevel[], groupingSize: number, side: 'bid' | 'ask'): OrderBookLevel[];
|
|
76
|
-
//# sourceMappingURL=orderBookGrouping.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"orderBookGrouping.d.mts","sourceRoot":"","sources":["../../src/utils/orderBookGrouping.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,qBAAqB,KAAK,CAAC;AAExC;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACxB,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;CAClB,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,0BAA0B,CACxC,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,GACZ,iBAAiB,CAyBnB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,CAUnE;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOzD;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,CAI/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,cAAc,EAAE,EACxB,YAAY,EAAE,MAAM,EACpB,IAAI,EAAE,KAAK,GAAG,KAAK,GAClB,cAAc,EAAE,CA0DlB"}
|
|
@@ -1,143 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Maximum API levels to request from Hyperliquid L2Book API.
|
|
3
|
-
* The API returns at most ~20 levels per side when using nSigFigs aggregation.
|
|
4
|
-
*/
|
|
5
|
-
export const MAX_ORDER_BOOK_LEVELS = 20;
|
|
6
|
-
/**
|
|
7
|
-
* Calculate nSigFigs and mantissa based on grouping and price.
|
|
8
|
-
* These parameters match Hyperliquid's L2Book API aggregation:
|
|
9
|
-
* - nSigFigs: 5, mantissa: 2 → finest granularity (~$1-2 for BTC)
|
|
10
|
-
* - nSigFigs: 5, mantissa: 5 → ~$5 increments for BTC
|
|
11
|
-
* - nSigFigs: 4 → ~$10 increments for BTC
|
|
12
|
-
* - nSigFigs: 3 → ~$100 increments for BTC
|
|
13
|
-
* - nSigFigs: 2 → ~$1000 increments for BTC (widest range)
|
|
14
|
-
*
|
|
15
|
-
* mantissa is only applicable when nSigFigs is 5.
|
|
16
|
-
*
|
|
17
|
-
* @param grouping - The price grouping increment
|
|
18
|
-
* @param price - The current mid price
|
|
19
|
-
* @returns Aggregation parameters for the API
|
|
20
|
-
*/
|
|
21
|
-
export function calculateAggregationParams(grouping, price) {
|
|
22
|
-
// Guard against invalid inputs that would cause Math.log10 to return -Infinity or NaN
|
|
23
|
-
if (price <= 0 || grouping <= 0) {
|
|
24
|
-
return { nSigFigs: 5 };
|
|
25
|
-
}
|
|
26
|
-
const magnitude = Math.floor(Math.log10(price));
|
|
27
|
-
const groupingMagnitude = Math.floor(Math.log10(grouping));
|
|
28
|
-
const baseNSigFigs = magnitude - groupingMagnitude + 1;
|
|
29
|
-
if (baseNSigFigs >= 5) {
|
|
30
|
-
// Finest granularity needs mantissa
|
|
31
|
-
// Derive mantissa from the first digit of grouping
|
|
32
|
-
const firstDigit = Math.floor(grouping / Math.pow(10, groupingMagnitude));
|
|
33
|
-
const mantissa = firstDigit <= 2 ? 2 : 5;
|
|
34
|
-
return { nSigFigs: 5, mantissa };
|
|
35
|
-
}
|
|
36
|
-
// Clamp nSigFigs between 2 and 5 (API only supports these values)
|
|
37
|
-
const clampedNSigFigs = Math.max(2, Math.min(5, baseNSigFigs));
|
|
38
|
-
return { nSigFigs: clampedNSigFigs };
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Calculate dynamic grouping options based on asset's mid price.
|
|
42
|
-
* Uses "1-2-5 per decade" scale anchored to price magnitude.
|
|
43
|
-
*
|
|
44
|
-
* @param midPrice - The current mid price of the asset
|
|
45
|
-
* @returns Array of grouping options suitable for the price magnitude
|
|
46
|
-
* @example
|
|
47
|
-
* calculateGroupingOptions(87000) → [1, 2, 5, 10, 100, 1000] // BTC
|
|
48
|
-
* calculateGroupingOptions(33) → [0.001, 0.002, 0.005, 0.01, 0.1, 1] // HYPE
|
|
49
|
-
* calculateGroupingOptions(0.002) → [0.000001, 0.00001, 0.0001] // PUMP
|
|
50
|
-
*/
|
|
51
|
-
export function calculateGroupingOptions(midPrice) {
|
|
52
|
-
if (midPrice <= 0) {
|
|
53
|
-
return [0.01, 0.1, 1]; // Fallback for invalid prices
|
|
54
|
-
}
|
|
55
|
-
const priceExponent = Math.floor(Math.log10(midPrice));
|
|
56
|
-
const base = Math.pow(10, priceExponent - 4);
|
|
57
|
-
const multipliers = [1, 2, 5, 10, 100, 1000];
|
|
58
|
-
return multipliers.map((multiplier) => base * multiplier);
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* Format grouping value for display (e.g., "0.001", "1", "100").
|
|
62
|
-
*
|
|
63
|
-
* @param value - The grouping value to format
|
|
64
|
-
* @returns Formatted string representation
|
|
65
|
-
*/
|
|
66
|
-
export function formatGroupingLabel(value) {
|
|
67
|
-
if (value >= 1) {
|
|
68
|
-
return value.toString();
|
|
69
|
-
}
|
|
70
|
-
// Calculate decimal places needed
|
|
71
|
-
const decimals = Math.max(0, Math.ceil(-Math.log10(value)));
|
|
72
|
-
return value.toFixed(decimals);
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* Select a sensible default grouping option.
|
|
76
|
-
* Picks a middle option that gives reasonable granularity.
|
|
77
|
-
*
|
|
78
|
-
* @param options - Array of available grouping options
|
|
79
|
-
* @returns The recommended default grouping value
|
|
80
|
-
*/
|
|
81
|
-
export function selectDefaultGrouping(options) {
|
|
82
|
-
// Pick the 4th option (index 3) which is typically a good balance
|
|
83
|
-
// For BTC: 10, for HYPE: 0.01, etc.
|
|
84
|
-
return options[3] ?? options[Math.floor(options.length / 2)] ?? options[0];
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Aggregate order book levels by price grouping.
|
|
88
|
-
* Groups prices into buckets, sums sizes, and recalculates cumulative totals.
|
|
89
|
-
*
|
|
90
|
-
* @param levels - Raw order book levels from API
|
|
91
|
-
* @param groupingSize - Price bucket size (e.g., 10 means group by $10 increments)
|
|
92
|
-
* @param side - 'bid' rounds down to bucket, 'ask' rounds up to bucket
|
|
93
|
-
* @returns Aggregated order book levels
|
|
94
|
-
*/
|
|
95
|
-
export function aggregateOrderBookLevels(levels, groupingSize, side) {
|
|
96
|
-
if (!levels.length || groupingSize <= 0) {
|
|
97
|
-
return levels;
|
|
98
|
-
}
|
|
99
|
-
// Group levels by price bucket
|
|
100
|
-
const buckets = new Map();
|
|
101
|
-
for (const level of levels) {
|
|
102
|
-
const price = parseFloat(level.price);
|
|
103
|
-
const size = parseFloat(level.size);
|
|
104
|
-
const notional = parseFloat(level.notional);
|
|
105
|
-
// Round price to bucket
|
|
106
|
-
// Bids: round down (floor) to include in lower bucket
|
|
107
|
-
// Asks: round up (ceil) to include in higher bucket
|
|
108
|
-
let bucketPrice;
|
|
109
|
-
if (side === 'bid') {
|
|
110
|
-
bucketPrice = Math.floor(price / groupingSize) * groupingSize;
|
|
111
|
-
}
|
|
112
|
-
else {
|
|
113
|
-
bucketPrice = Math.ceil(price / groupingSize) * groupingSize;
|
|
114
|
-
}
|
|
115
|
-
const existing = buckets.get(bucketPrice);
|
|
116
|
-
if (existing) {
|
|
117
|
-
existing.size += size;
|
|
118
|
-
existing.notional += notional;
|
|
119
|
-
}
|
|
120
|
-
else {
|
|
121
|
-
buckets.set(bucketPrice, { size, notional, price: bucketPrice });
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
// Convert buckets to array and sort
|
|
125
|
-
const sortedBuckets = Array.from(buckets.values()).sort((bucketA, bucketB) => side === 'bid'
|
|
126
|
-
? bucketB.price - bucketA.price
|
|
127
|
-
: bucketA.price - bucketB.price);
|
|
128
|
-
// Calculate cumulative totals
|
|
129
|
-
let cumulativeSize = 0;
|
|
130
|
-
let cumulativeNotional = 0;
|
|
131
|
-
return sortedBuckets.map((bucket) => {
|
|
132
|
-
cumulativeSize += bucket.size;
|
|
133
|
-
cumulativeNotional += bucket.notional;
|
|
134
|
-
return {
|
|
135
|
-
price: bucket.price.toString(),
|
|
136
|
-
size: bucket.size.toString(),
|
|
137
|
-
total: cumulativeSize.toString(),
|
|
138
|
-
notional: bucket.notional.toFixed(2),
|
|
139
|
-
totalNotional: cumulativeNotional.toFixed(2),
|
|
140
|
-
};
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
//# sourceMappingURL=orderBookGrouping.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"orderBookGrouping.mjs","sourceRoot":"","sources":["../../src/utils/orderBookGrouping.ts"],"names":[],"mappings":"AAWA;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,CAAC;AAUxC;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,0BAA0B,CACxC,QAAgB,EAChB,KAAa;IAEb,sFAAsF;IACtF,IAAI,KAAK,IAAI,CAAC,IAAI,QAAQ,IAAI,CAAC,EAAE,CAAC;QAChC,OAAO,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;IACzB,CAAC;IAED,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IAChD,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC3D,MAAM,YAAY,GAAG,SAAS,GAAG,iBAAiB,GAAG,CAAC,CAAC;IAEvD,IAAI,YAAY,IAAI,CAAC,EAAE,CAAC;QACtB,oCAAoC;QACpC,mDAAmD;QACnD,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,iBAAiB,CAAC,CAAC,CAAC;QAC1E,MAAM,QA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: string;\n total: string;\n notional: string;\n totalNotional: string;\n};\n\n/**\n * Maximum API levels to request from Hyperliquid L2Book API.\n * The API returns at most ~20 levels per side when using nSigFigs aggregation.\n */\nexport const MAX_ORDER_BOOK_LEVELS = 20;\n\n/**\n * Parameters for Hyperliquid L2Book API aggregation.\n */\nexport type AggregationParams = {\n nSigFigs: 2 | 3 | 4 | 5;\n mantissa?: 2 | 5;\n};\n\n/**\n * Calculate nSigFigs and mantissa based on grouping and price.\n * These parameters match Hyperliquid's L2Book API aggregation:\n * - nSigFigs: 5, mantissa: 2 → finest granularity (~$1-2 for BTC)\n * - nSigFigs: 5, mantissa: 5 → ~$5 increments for BTC\n * - nSigFigs: 4 → ~$10 increments for BTC\n * - nSigFigs: 3 → ~$100 increments for BTC\n * - nSigFigs: 2 → ~$1000 increments for BTC (widest range)\n *\n * mantissa is only applicable when nSigFigs is 5.\n *\n * @param grouping - The price grouping increment\n * @param price - The current mid price\n * @returns Aggregation parameters for the API\n */\nexport function calculateAggregationParams(\n grouping: number,\n price: number,\n): AggregationParams {\n // Guard against invalid inputs that would cause Math.log10 to return -Infinity or NaN\n if (price <= 0 || grouping <= 0) {\n return { nSigFigs: 5 };\n }\n\n const magnitude = Math.floor(Math.log10(price));\n const groupingMagnitude = Math.floor(Math.log10(grouping));\n const baseNSigFigs = magnitude - groupingMagnitude + 1;\n\n if (baseNSigFigs >= 5) {\n // Finest granularity needs mantissa\n // Derive mantissa from the first digit of grouping\n const firstDigit = Math.floor(grouping / Math.pow(10, groupingMagnitude));\n const mantissa = firstDigit <= 2 ? 2 : 5;\n return { nSigFigs: 5, mantissa };\n }\n\n // Clamp nSigFigs between 2 and 5 (API only supports these values)\n const clampedNSigFigs = Math.max(2, Math.min(5, baseNSigFigs)) as\n | 2\n | 3\n | 4\n | 5;\n return { nSigFigs: clampedNSigFigs };\n}\n\n/**\n * Calculate dynamic grouping options based on asset's mid price.\n * Uses \"1-2-5 per decade\" scale anchored to price magnitude.\n *\n * @param midPrice - The current mid price of the asset\n * @returns Array of grouping options suitable for the price magnitude\n * @example\n * calculateGroupingOptions(87000) → [1, 2, 5, 10, 100, 1000] // BTC\n * calculateGroupingOptions(33) → [0.001, 0.002, 0.005, 0.01, 0.1, 1] // HYPE\n * calculateGroupingOptions(0.002) → [0.000001, 0.00001, 0.0001] // PUMP\n */\nexport function calculateGroupingOptions(midPrice: number): number[] {\n if (midPrice <= 0) {\n return [0.01, 0.1, 1]; // Fallback for invalid prices\n }\n\n const priceExponent = Math.floor(Math.log10(midPrice));\n const base = Math.pow(10, priceExponent - 4);\n const multipliers = [1, 2, 5, 10, 100, 1000];\n\n return multipliers.map((multiplier) => base * multiplier);\n}\n\n/**\n * Format grouping value for display (e.g., \"0.001\", \"1\", \"100\").\n *\n * @param value - The grouping value to format\n * @returns Formatted string representation\n */\nexport function formatGroupingLabel(value: number): string {\n if (value >= 1) {\n return value.toString();\n }\n // Calculate decimal places needed\n const decimals = Math.max(0, Math.ceil(-Math.log10(value)));\n return value.toFixed(decimals);\n}\n\n/**\n * Select a sensible default grouping option.\n * Picks a middle option that gives reasonable granularity.\n *\n * @param options - Array of available grouping options\n * @returns The recommended default grouping value\n */\nexport function selectDefaultGrouping(options: number[]): number {\n // Pick the 4th option (index 3) which is typically a good balance\n // For BTC: 10, for HYPE: 0.01, etc.\n return options[3] ?? options[Math.floor(options.length / 2)] ?? options[0];\n}\n\n/**\n * Aggregate order book levels by price grouping.\n * Groups prices into buckets, sums sizes, and recalculates cumulative totals.\n *\n * @param levels - Raw order book levels from API\n * @param groupingSize - Price bucket size (e.g., 10 means group by $10 increments)\n * @param side - 'bid' rounds down to bucket, 'ask' rounds up to bucket\n * @returns Aggregated order book levels\n */\nexport function aggregateOrderBookLevels(\n levels: OrderBookLevel[],\n groupingSize: number,\n side: 'bid' | 'ask',\n): OrderBookLevel[] {\n if (!levels.length || groupingSize <= 0) {\n return levels;\n }\n\n // Group levels by price bucket\n const buckets = new Map<\n number,\n { size: number; notional: number; price: number }\n >();\n\n for (const level of levels) {\n const price = parseFloat(level.price);\n const size = parseFloat(level.size);\n const notional = parseFloat(level.notional);\n\n // Round price to bucket\n // Bids: round down (floor) to include in lower bucket\n // Asks: round up (ceil) to include in higher bucket\n let bucketPrice: number;\n if (side === 'bid') {\n bucketPrice = Math.floor(price / groupingSize) * groupingSize;\n } else {\n bucketPrice = Math.ceil(price / groupingSize) * groupingSize;\n }\n\n const existing = buckets.get(bucketPrice);\n if (existing) {\n existing.size += size;\n existing.notional += notional;\n } else {\n buckets.set(bucketPrice, { size, notional, price: bucketPrice });\n }\n }\n\n // Convert buckets to array and sort\n const sortedBuckets = Array.from(buckets.values()).sort((bucketA, bucketB) =>\n side === 'bid'\n ? bucketB.price - bucketA.price\n : bucketA.price - bucketB.price,\n );\n\n // Calculate cumulative totals\n let cumulativeSize = 0;\n let cumulativeNotional = 0;\n\n return sortedBuckets.map((bucket) => {\n cumulativeSize += bucket.size;\n cumulativeNotional += bucket.notional;\n\n return {\n price: bucket.price.toString(),\n size: bucket.size.toString(),\n total: cumulativeSize.toString(),\n notional: bucket.notional.toFixed(2),\n totalNotional: cumulativeNotional.toFixed(2),\n };\n });\n}\n"]}
|
|
@@ -1,283 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.buildOrdersArray = exports.calculateOrderPriceAndSize = exports.calculateFinalPositionSize = exports.getMaxAllowedAmount = exports.calculateMarginRequired = exports.calculatePositionSize = void 0;
|
|
4
|
-
const hyperLiquidAdapter_1 = require("./hyperLiquidAdapter.cjs");
|
|
5
|
-
const perpsConfig_1 = require("../constants/perpsConfig.cjs");
|
|
6
|
-
const perpsErrorCodes_1 = require("../constants/perpsErrorCodes.cjs");
|
|
7
|
-
/**
|
|
8
|
-
* Calculate position size based on USD amount and asset price
|
|
9
|
-
*
|
|
10
|
-
* @param params - Amount in USD, current asset price, and required decimal precision
|
|
11
|
-
* @returns Position size formatted to the asset's decimal precision
|
|
12
|
-
*/
|
|
13
|
-
function calculatePositionSize(params) {
|
|
14
|
-
const { amount, price, szDecimals } = params;
|
|
15
|
-
// Validate required parameters
|
|
16
|
-
if (szDecimals === undefined || szDecimals === null) {
|
|
17
|
-
throw new Error('szDecimals is required for position size calculation');
|
|
18
|
-
}
|
|
19
|
-
if (szDecimals < 0) {
|
|
20
|
-
throw new Error(`szDecimals must be >= 0, got: ${szDecimals}`);
|
|
21
|
-
}
|
|
22
|
-
const amountNum = parseFloat(amount || '0');
|
|
23
|
-
if (isNaN(amountNum) || isNaN(price) || amountNum === 0 || price === 0) {
|
|
24
|
-
return (0).toFixed(szDecimals);
|
|
25
|
-
}
|
|
26
|
-
const positionSize = amountNum / price;
|
|
27
|
-
const multiplier = Math.pow(10, szDecimals);
|
|
28
|
-
let rounded = Math.round(positionSize * multiplier) / multiplier;
|
|
29
|
-
// Ensure rounded size meets requested USD (fix validation gap)
|
|
30
|
-
const actualUsd = rounded * price;
|
|
31
|
-
if (actualUsd < amountNum) {
|
|
32
|
-
rounded += 1 / multiplier;
|
|
33
|
-
}
|
|
34
|
-
return rounded.toFixed(szDecimals);
|
|
35
|
-
}
|
|
36
|
-
exports.calculatePositionSize = calculatePositionSize;
|
|
37
|
-
/**
|
|
38
|
-
* Calculate margin required for a position
|
|
39
|
-
*
|
|
40
|
-
* @param params - Position amount and leverage
|
|
41
|
-
* @returns Margin required formatted to 2 decimal places
|
|
42
|
-
*/
|
|
43
|
-
function calculateMarginRequired(params) {
|
|
44
|
-
const { amount, leverage } = params;
|
|
45
|
-
const amountNum = parseFloat(amount || '0');
|
|
46
|
-
if (isNaN(amountNum) ||
|
|
47
|
-
isNaN(leverage) ||
|
|
48
|
-
amountNum === 0 ||
|
|
49
|
-
leverage === 0) {
|
|
50
|
-
return '0.00';
|
|
51
|
-
}
|
|
52
|
-
return (amountNum / leverage).toFixed(2);
|
|
53
|
-
}
|
|
54
|
-
exports.calculateMarginRequired = calculateMarginRequired;
|
|
55
|
-
function getMaxAllowedAmount(params) {
|
|
56
|
-
const { availableBalance, assetPrice, assetSzDecimals, leverage } = params;
|
|
57
|
-
if (availableBalance === 0 || !assetPrice || assetSzDecimals === undefined) {
|
|
58
|
-
return 0;
|
|
59
|
-
}
|
|
60
|
-
// The theoretical maximum is simply availableBalance * leverage
|
|
61
|
-
const theoreticalMax = availableBalance * leverage;
|
|
62
|
-
// But we need to account for position size rounding
|
|
63
|
-
// Find the largest whole dollar amount that fits within this limit
|
|
64
|
-
let maxAmount = Math.floor(theoreticalMax);
|
|
65
|
-
// Verify this amount doesn't exceed available balance after rounding
|
|
66
|
-
const testPositionSize = calculatePositionSize({
|
|
67
|
-
amount: maxAmount.toString(),
|
|
68
|
-
price: assetPrice,
|
|
69
|
-
szDecimals: assetSzDecimals,
|
|
70
|
-
});
|
|
71
|
-
const actualNotionalValue = parseFloat(testPositionSize) * assetPrice;
|
|
72
|
-
const requiredMargin = actualNotionalValue / leverage;
|
|
73
|
-
// If rounding caused us to exceed available balance, step down by one position increment
|
|
74
|
-
if (requiredMargin > availableBalance) {
|
|
75
|
-
const minPositionSizeIncrement = 1 / Math.pow(10, assetSzDecimals);
|
|
76
|
-
const positionSizeIncrementUsd = Math.ceil(minPositionSizeIncrement * assetPrice);
|
|
77
|
-
maxAmount -= positionSizeIncrementUsd;
|
|
78
|
-
}
|
|
79
|
-
return Math.max(0, maxAmount);
|
|
80
|
-
}
|
|
81
|
-
exports.getMaxAllowedAmount = getMaxAllowedAmount;
|
|
82
|
-
/**
|
|
83
|
-
* Calculates final position size using USD as source of truth with price validation
|
|
84
|
-
*
|
|
85
|
-
* This function implements the hybrid approach where USD is the source of truth,
|
|
86
|
-
* but includes price staleness validation and proper rounding to prevent precision loss.
|
|
87
|
-
*
|
|
88
|
-
* @param params - USD amount, size, prices, and configuration
|
|
89
|
-
* @returns Final position size as a number
|
|
90
|
-
*/
|
|
91
|
-
function calculateFinalPositionSize(params) {
|
|
92
|
-
const { usdAmount, size, currentPrice, priceAtCalculation, maxSlippageBps, szDecimals, leverage, debugLogger, } = params;
|
|
93
|
-
let finalPositionSize;
|
|
94
|
-
if (usdAmount && parseFloat(usdAmount) > 0) {
|
|
95
|
-
// USD amount provided - use it as source of truth
|
|
96
|
-
const usdValue = parseFloat(usdAmount);
|
|
97
|
-
// 1. Validate price staleness if priceAtCalculation provided
|
|
98
|
-
if (priceAtCalculation) {
|
|
99
|
-
const priceDeltaBps = Math.abs(((currentPrice - priceAtCalculation) / priceAtCalculation) * 10000);
|
|
100
|
-
const maxSlippageBpsValue = maxSlippageBps ?? perpsConfig_1.ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps;
|
|
101
|
-
if (priceDeltaBps > maxSlippageBpsValue) {
|
|
102
|
-
throw new Error(`Price moved too much: ${priceDeltaBps.toFixed(0)} bps (max: ${maxSlippageBpsValue} bps). ` +
|
|
103
|
-
`Expected: ${priceAtCalculation.toFixed(2)}, Current: ${currentPrice.toFixed(2)}`);
|
|
104
|
-
}
|
|
105
|
-
debugLogger?.log('Price validation passed:', {
|
|
106
|
-
priceAtCalculation,
|
|
107
|
-
currentPrice,
|
|
108
|
-
deltaBps: priceDeltaBps.toFixed(2),
|
|
109
|
-
maxSlippageBps: maxSlippageBpsValue,
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
// 2. Recalculate position size with fresh price
|
|
113
|
-
finalPositionSize = usdValue / currentPrice;
|
|
114
|
-
// 3. Apply size decimals rounding
|
|
115
|
-
const multiplier = Math.pow(10, szDecimals);
|
|
116
|
-
finalPositionSize = Math.round(finalPositionSize * multiplier) / multiplier;
|
|
117
|
-
// 4. Ensure rounded size meets requested USD (fix validation gap)
|
|
118
|
-
let actualNotionalValue = finalPositionSize * currentPrice;
|
|
119
|
-
if (actualNotionalValue < usdValue) {
|
|
120
|
-
// Add 1 minimum increment to meet requested USD
|
|
121
|
-
finalPositionSize += 1 / multiplier;
|
|
122
|
-
actualNotionalValue = finalPositionSize * currentPrice;
|
|
123
|
-
debugLogger?.log('Position size adjusted to meet USD minimum:', {
|
|
124
|
-
requestedUsd: usdValue,
|
|
125
|
-
beforeAdjustment: finalPositionSize - 1 / multiplier,
|
|
126
|
-
afterAdjustment: finalPositionSize,
|
|
127
|
-
actualUsd: actualNotionalValue,
|
|
128
|
-
});
|
|
129
|
-
}
|
|
130
|
-
const requiredMargin = actualNotionalValue / (leverage ?? 1);
|
|
131
|
-
// Log if rounding caused significant difference
|
|
132
|
-
const usdDifference = Math.abs(actualNotionalValue - usdValue);
|
|
133
|
-
if (usdDifference > 0.01) {
|
|
134
|
-
debugLogger?.log('Position size rounding caused USD difference (acceptable):', {
|
|
135
|
-
requestedUsd: usdValue,
|
|
136
|
-
actualUsd: actualNotionalValue,
|
|
137
|
-
difference: usdDifference,
|
|
138
|
-
positionSize: finalPositionSize,
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
debugLogger?.log('Recalculated position size with fresh price:', {
|
|
142
|
-
usdAmount: usdValue,
|
|
143
|
-
priceAtCalculation,
|
|
144
|
-
currentPrice,
|
|
145
|
-
originalSize: size,
|
|
146
|
-
recalculatedSize: finalPositionSize,
|
|
147
|
-
requiredMargin,
|
|
148
|
-
minIncrement: 1 / multiplier,
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
|
-
else {
|
|
152
|
-
// Legacy: Use provided size (backward compatibility)
|
|
153
|
-
finalPositionSize = parseFloat(size ?? '0');
|
|
154
|
-
debugLogger?.log('Using legacy size calculation (no USD amount provided):', {
|
|
155
|
-
providedSize: size,
|
|
156
|
-
finalSize: finalPositionSize,
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
return { finalPositionSize };
|
|
160
|
-
}
|
|
161
|
-
exports.calculateFinalPositionSize = calculateFinalPositionSize;
|
|
162
|
-
/**
|
|
163
|
-
* Calculates order price and formatted size based on order type
|
|
164
|
-
*
|
|
165
|
-
* @param params - Order parameters including type, direction, size, and prices
|
|
166
|
-
* @returns Formatted order price, size, and price string
|
|
167
|
-
*/
|
|
168
|
-
function calculateOrderPriceAndSize(params) {
|
|
169
|
-
const { orderType, isBuy, finalPositionSize, currentPrice, limitPrice, slippage, szDecimals, } = params;
|
|
170
|
-
let orderPrice;
|
|
171
|
-
let formattedSize;
|
|
172
|
-
if (orderType === 'market') {
|
|
173
|
-
// Market orders: add slippage (3% conservative default)
|
|
174
|
-
const slippageValue = slippage ?? perpsConfig_1.ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps / 10000;
|
|
175
|
-
orderPrice = isBuy
|
|
176
|
-
? currentPrice * (1 + slippageValue)
|
|
177
|
-
: currentPrice * (1 - slippageValue);
|
|
178
|
-
formattedSize = (0, hyperLiquidAdapter_1.formatHyperLiquidSize)({
|
|
179
|
-
size: finalPositionSize,
|
|
180
|
-
szDecimals,
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
else {
|
|
184
|
-
// Limit orders: use provided price (no slippage applied)
|
|
185
|
-
if (!limitPrice) {
|
|
186
|
-
throw new Error(perpsErrorCodes_1.PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED);
|
|
187
|
-
}
|
|
188
|
-
orderPrice = parseFloat(limitPrice);
|
|
189
|
-
formattedSize = (0, hyperLiquidAdapter_1.formatHyperLiquidSize)({
|
|
190
|
-
size: finalPositionSize,
|
|
191
|
-
szDecimals,
|
|
192
|
-
});
|
|
193
|
-
}
|
|
194
|
-
const formattedPrice = (0, hyperLiquidAdapter_1.formatHyperLiquidPrice)({
|
|
195
|
-
price: orderPrice,
|
|
196
|
-
szDecimals,
|
|
197
|
-
});
|
|
198
|
-
return { orderPrice, formattedSize, formattedPrice };
|
|
199
|
-
}
|
|
200
|
-
exports.calculateOrderPriceAndSize = calculateOrderPriceAndSize;
|
|
201
|
-
/**
|
|
202
|
-
* Builds orders array including main order and optional TP/SL orders
|
|
203
|
-
*
|
|
204
|
-
* @param params - Order construction parameters
|
|
205
|
-
* @returns Array of SDK order params and grouping type
|
|
206
|
-
*/
|
|
207
|
-
function buildOrdersArray(params) {
|
|
208
|
-
const { assetId, isBuy, formattedPrice, formattedSize, reduceOnly, orderType, clientOrderId, takeProfitPrice, stopLossPrice, szDecimals, grouping, } = params;
|
|
209
|
-
const orders = [];
|
|
210
|
-
// 1. Main order
|
|
211
|
-
const mainOrder = {
|
|
212
|
-
a: assetId,
|
|
213
|
-
b: isBuy,
|
|
214
|
-
p: formattedPrice,
|
|
215
|
-
s: formattedSize,
|
|
216
|
-
r: reduceOnly || false,
|
|
217
|
-
t: orderType === 'limit'
|
|
218
|
-
? { limit: { tif: 'Gtc' } }
|
|
219
|
-
: { limit: { tif: 'FrontendMarket' } },
|
|
220
|
-
c: clientOrderId ? clientOrderId : undefined,
|
|
221
|
-
};
|
|
222
|
-
orders.push(mainOrder);
|
|
223
|
-
// 2. Take Profit order
|
|
224
|
-
if (takeProfitPrice) {
|
|
225
|
-
const tpOrder = {
|
|
226
|
-
a: assetId,
|
|
227
|
-
b: !isBuy,
|
|
228
|
-
p: (0, hyperLiquidAdapter_1.formatHyperLiquidPrice)({
|
|
229
|
-
price: parseFloat(takeProfitPrice),
|
|
230
|
-
szDecimals,
|
|
231
|
-
}),
|
|
232
|
-
s: formattedSize,
|
|
233
|
-
r: true,
|
|
234
|
-
t: {
|
|
235
|
-
trigger: {
|
|
236
|
-
isMarket: false,
|
|
237
|
-
triggerPx: (0, hyperLiquidAdapter_1.formatHyperLiquidPrice)({
|
|
238
|
-
price: parseFloat(takeProfitPrice),
|
|
239
|
-
szDecimals,
|
|
240
|
-
}),
|
|
241
|
-
tpsl: 'tp',
|
|
242
|
-
},
|
|
243
|
-
},
|
|
244
|
-
};
|
|
245
|
-
orders.push(tpOrder);
|
|
246
|
-
}
|
|
247
|
-
// 3. Stop Loss order
|
|
248
|
-
if (stopLossPrice) {
|
|
249
|
-
// Apply 10% slippage to SL limit price (executes as market order when triggered)
|
|
250
|
-
// HyperLiquid recommended: 10% for TP/SL orders
|
|
251
|
-
const stopLossPriceNum = parseFloat(stopLossPrice);
|
|
252
|
-
const slippageValue = perpsConfig_1.ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps / 10000;
|
|
253
|
-
const limitPriceWithSlippage = isBuy
|
|
254
|
-
? stopLossPriceNum * (1 - slippageValue) // Selling to close long: willing to accept LESS (slippage protection)
|
|
255
|
-
: stopLossPriceNum * (1 + slippageValue); // Buying to close short: willing to pay MORE (slippage protection)
|
|
256
|
-
const slOrder = {
|
|
257
|
-
a: assetId,
|
|
258
|
-
b: !isBuy,
|
|
259
|
-
p: (0, hyperLiquidAdapter_1.formatHyperLiquidPrice)({
|
|
260
|
-
price: limitPriceWithSlippage,
|
|
261
|
-
szDecimals,
|
|
262
|
-
}),
|
|
263
|
-
s: formattedSize,
|
|
264
|
-
r: true,
|
|
265
|
-
t: {
|
|
266
|
-
trigger: {
|
|
267
|
-
isMarket: true,
|
|
268
|
-
triggerPx: (0, hyperLiquidAdapter_1.formatHyperLiquidPrice)({
|
|
269
|
-
price: stopLossPriceNum,
|
|
270
|
-
szDecimals,
|
|
271
|
-
}),
|
|
272
|
-
tpsl: 'sl',
|
|
273
|
-
},
|
|
274
|
-
},
|
|
275
|
-
};
|
|
276
|
-
orders.push(slOrder);
|
|
277
|
-
}
|
|
278
|
-
// Determine grouping
|
|
279
|
-
const finalGrouping = grouping ?? ((takeProfitPrice ?? stopLossPrice) ? 'normalTpsl' : 'na');
|
|
280
|
-
return { orders, grouping: finalGrouping };
|
|
281
|
-
}
|
|
282
|
-
exports.buildOrdersArray = buildOrdersArray;
|
|
283
|
-
//# sourceMappingURL=orderCalculations.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"orderCalculations.cjs","sourceRoot":"","sources":["../../src/utils/orderCalculations.ts"],"names":[],"mappings":";;;AAEA,iEAG8B;AAC9B,8DAAiE;AACjE,sEAAiE;AA+EjE;;;;;GAKG;AACH,SAAgB,qBAAqB,CAAC,MAA0B;IAC9D,MAAM,EAAE,MAAM,EAAE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7C,CAAC;AAjGD,4CAiGC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nimport {\n formatHyperLiquidPrice,\n formatHyperLiquidSize,\n} from './hyperLiquidAdapter';\nimport { ORDER_SLIPPAGE_CONFIG } from '../constants/perpsConfig';\nimport { PERPS_ERROR_CODES } from '../constants/perpsErrorCodes';\nimport type { PerpsDebugLogger } from '../types';\nimport type { SDKOrderParams } from '../types/hyperliquid-types';\n\n/**\n * Optional debug logger for order calculation functions.\n * When provided, enables detailed logging for debugging.\n */\nexport type OrderCalculationsDebugLogger = PerpsDebugLogger | undefined;\n\ntype PositionSizeParams = {\n amount: string;\n price: number;\n szDecimals: number;\n};\n\ntype MarginRequiredParams = {\n amount: string;\n leverage: number;\n};\n\ntype MaxAllowedAmountParams = {\n availableBalance: number;\n assetPrice: number;\n assetSzDecimals: number;\n leverage: number;\n};\n\n// Advanced order calculation interfaces\nexport type CalculateFinalPositionSizeParams = {\n usdAmount?: string;\n size?: string;\n currentPrice: number;\n priceAtCalculation?: number;\n maxSlippageBps?: number;\n szDecimals: number;\n leverage?: number;\n debugLogger?: OrderCalculationsDebugLogger;\n};\n\nexport type CalculateFinalPositionSizeResult = {\n finalPositionSize: number;\n};\n\nexport type CalculateOrderPriceAndSizeParams = {\n orderType: 'market' | 'limit';\n isBuy: boolean;\n finalPositionSize: number;\n currentPrice: number;\n limitPrice?: string;\n slippage?: number;\n szDecimals: number;\n};\n\nexport type CalculateOrderPriceAndSizeResult = {\n orderPrice: number;\n formattedSize: string;\n formattedPrice: string;\n};\n\nexport type BuildOrdersArrayParams = {\n assetId: number;\n isBuy: boolean;\n formattedPrice: string;\n formattedSize: string;\n reduceOnly: boolean;\n orderType: 'market' | 'limit';\n clientOrderId?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n szDecimals: number;\n grouping?: 'na' | 'normalTpsl' | 'positionTpsl';\n};\n\nexport type BuildOrdersArrayResult = {\n orders: SDKOrderParams[];\n grouping: 'na' | 'normalTpsl' | 'positionTpsl';\n};\n\n/**\n * Calculate position size based on USD amount and asset price\n *\n * @param params - Amount in USD, current asset price, and required decimal precision\n * @returns Position size formatted to the asset's decimal precision\n */\nexport function calculatePositionSize(params: PositionSizeParams): string {\n const { amount, price, szDecimals } = params;\n\n // Validate required parameters\n if (szDecimals === undefined || szDecimals === null) {\n throw new Error('szDecimals is required for position size calculation');\n }\n if (szDecimals < 0) {\n throw new Error(`szDecimals must be >= 0, got: ${szDecimals}`);\n }\n\n const amountNum = parseFloat(amount || '0');\n\n if (isNaN(amountNum) || isNaN(price) || amountNum === 0 || price === 0) {\n return (0).toFixed(szDecimals);\n }\n\n const positionSize = amountNum / price;\n const multiplier = Math.pow(10, szDecimals);\n let rounded = Math.round(positionSize * multiplier) / multiplier;\n\n // Ensure rounded size meets requested USD (fix validation gap)\n const actualUsd = rounded * price;\n if (actualUsd < amountNum) {\n rounded += 1 / multiplier;\n }\n\n return rounded.toFixed(szDecimals);\n}\n\n/**\n * Calculate margin required for a position\n *\n * @param params - Position amount and leverage\n * @returns Margin required formatted to 2 decimal places\n */\nexport function calculateMarginRequired(params: MarginRequiredParams): string {\n const { amount, leverage } = params;\n const amountNum = parseFloat(amount || '0');\n\n if (\n isNaN(amountNum) ||\n isNaN(leverage) ||\n amountNum === 0 ||\n leverage === 0\n ) {\n return '0.00';\n }\n\n return (amountNum / leverage).toFixed(2);\n}\n\nexport function getMaxAllowedAmount(params: MaxAllowedAmountParams): number {\n const { availableBalance, assetPrice, assetSzDecimals, leverage } = params;\n if (availableBalance === 0 || !assetPrice || assetSzDecimals === undefined) {\n return 0;\n }\n\n // The theoretical maximum is simply availableBalance * leverage\n const theoreticalMax = availableBalance * leverage;\n\n // But we need to account for position size rounding\n // Find the largest whole dollar amount that fits within this limit\n let maxAmount = Math.floor(theoreticalMax);\n\n // Verify this amount doesn't exceed available balance after rounding\n const testPositionSize = calculatePositionSize({\n amount: maxAmount.toString(),\n price: assetPrice,\n szDecimals: assetSzDecimals,\n });\n\n const actualNotionalValue = parseFloat(testPositionSize) * assetPrice;\n const requiredMargin = actualNotionalValue / leverage;\n\n // If rounding caused us to exceed available balance, step down by one position increment\n if (requiredMargin > availableBalance) {\n const minPositionSizeIncrement = 1 / Math.pow(10, assetSzDecimals);\n const positionSizeIncrementUsd = Math.ceil(\n minPositionSizeIncrement * assetPrice,\n );\n maxAmount -= positionSizeIncrementUsd;\n }\n\n return Math.max(0, maxAmount);\n}\n\n/**\n * Calculates final position size using USD as source of truth with price validation\n *\n * This function implements the hybrid approach where USD is the source of truth,\n * but includes price staleness validation and proper rounding to prevent precision loss.\n *\n * @param params - USD amount, size, prices, and configuration\n * @returns Final position size as a number\n */\nexport function calculateFinalPositionSize(\n params: CalculateFinalPositionSizeParams,\n): CalculateFinalPositionSizeResult {\n const {\n usdAmount,\n size,\n currentPrice,\n priceAtCalculation,\n maxSlippageBps,\n szDecimals,\n leverage,\n debugLogger,\n } = params;\n\n let finalPositionSize: number;\n\n if (usdAmount && parseFloat(usdAmount) > 0) {\n // USD amount provided - use it as source of truth\n const usdValue = parseFloat(usdAmount);\n\n // 1. Validate price staleness if priceAtCalculation provided\n if (priceAtCalculation) {\n const priceDeltaBps = Math.abs(\n ((currentPrice - priceAtCalculation) / priceAtCalculation) * 10000,\n );\n const maxSlippageBpsValue =\n maxSlippageBps ?? ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps;\n\n if (priceDeltaBps > maxSlippageBpsValue) {\n throw new Error(\n `Price moved too much: ${priceDeltaBps.toFixed(0)} bps (max: ${maxSlippageBpsValue} bps). ` +\n `Expected: ${priceAtCalculation.toFixed(2)}, Current: ${currentPrice.toFixed(2)}`,\n );\n }\n\n debugLogger?.log('Price validation passed:', {\n priceAtCalculation,\n currentPrice,\n deltaBps: priceDeltaBps.toFixed(2),\n maxSlippageBps: maxSlippageBpsValue,\n });\n }\n\n // 2. Recalculate position size with fresh price\n finalPositionSize = usdValue / currentPrice;\n\n // 3. Apply size decimals rounding\n const multiplier = Math.pow(10, szDecimals);\n finalPositionSize = Math.round(finalPositionSize * multiplier) / multiplier;\n\n // 4. Ensure rounded size meets requested USD (fix validation gap)\n let actualNotionalValue = finalPositionSize * currentPrice;\n if (actualNotionalValue < usdValue) {\n // Add 1 minimum increment to meet requested USD\n finalPositionSize += 1 / multiplier;\n actualNotionalValue = finalPositionSize * currentPrice;\n\n debugLogger?.log('Position size adjusted to meet USD minimum:', {\n requestedUsd: usdValue,\n beforeAdjustment: finalPositionSize - 1 / multiplier,\n afterAdjustment: finalPositionSize,\n actualUsd: actualNotionalValue,\n });\n }\n\n const requiredMargin = actualNotionalValue / (leverage ?? 1);\n\n // Log if rounding caused significant difference\n const usdDifference = Math.abs(actualNotionalValue - usdValue);\n if (usdDifference > 0.01) {\n debugLogger?.log(\n 'Position size rounding caused USD difference (acceptable):',\n {\n requestedUsd: usdValue,\n actualUsd: actualNotionalValue,\n difference: usdDifference,\n positionSize: finalPositionSize,\n },\n );\n }\n\n debugLogger?.log('Recalculated position size with fresh price:', {\n usdAmount: usdValue,\n priceAtCalculation,\n currentPrice,\n originalSize: size,\n recalculatedSize: finalPositionSize,\n requiredMargin,\n minIncrement: 1 / multiplier,\n });\n } else {\n // Legacy: Use provided size (backward compatibility)\n finalPositionSize = parseFloat(size ?? '0');\n\n debugLogger?.log(\n 'Using legacy size calculation (no USD amount provided):',\n {\n providedSize: size,\n finalSize: finalPositionSize,\n },\n );\n }\n\n return { finalPositionSize };\n}\n\n/**\n * Calculates order price and formatted size based on order type\n *\n * @param params - Order parameters including type, direction, size, and prices\n * @returns Formatted order price, size, and price string\n */\nexport function calculateOrderPriceAndSize(\n params: CalculateOrderPriceAndSizeParams,\n): CalculateOrderPriceAndSizeResult {\n const {\n orderType,\n isBuy,\n finalPositionSize,\n currentPrice,\n limitPrice,\n slippage,\n szDecimals,\n } = params;\n\n let orderPrice: number;\n let formattedSize: string;\n\n if (orderType === 'market') {\n // Market orders: add slippage (3% conservative default)\n const slippageValue =\n slippage ?? ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps / 10000;\n orderPrice = isBuy\n ? currentPrice * (1 + slippageValue)\n : currentPrice * (1 - slippageValue);\n formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals,\n });\n } else {\n // Limit orders: use provided price (no slippage applied)\n if (!limitPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED);\n }\n orderPrice = parseFloat(limitPrice);\n formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals,\n });\n }\n\n const formattedPrice = formatHyperLiquidPrice({\n price: orderPrice,\n szDecimals,\n });\n\n return { orderPrice, formattedSize, formattedPrice };\n}\n\n/**\n * Builds orders array including main order and optional TP/SL orders\n *\n * @param params - Order construction parameters\n * @returns Array of SDK order params and grouping type\n */\nexport function buildOrdersArray(\n params: BuildOrdersArrayParams,\n): BuildOrdersArrayResult {\n const {\n assetId,\n isBuy,\n formattedPrice,\n formattedSize,\n reduceOnly,\n orderType,\n clientOrderId,\n takeProfitPrice,\n stopLossPrice,\n szDecimals,\n grouping,\n } = params;\n\n const orders: SDKOrderParams[] = [];\n\n // 1. Main order\n const mainOrder: SDKOrderParams = {\n a: assetId,\n b: isBuy,\n p: formattedPrice,\n s: formattedSize,\n r: reduceOnly || false,\n t:\n orderType === 'limit'\n ? { limit: { tif: 'Gtc' } }\n : { limit: { tif: 'FrontendMarket' } },\n c: clientOrderId ? (clientOrderId as Hex) : undefined,\n };\n orders.push(mainOrder);\n\n // 2. Take Profit order\n if (takeProfitPrice) {\n const tpOrder: SDKOrderParams = {\n a: assetId,\n b: !isBuy,\n p: formatHyperLiquidPrice({\n price: parseFloat(takeProfitPrice),\n szDecimals,\n }),\n s: formattedSize,\n r: true,\n t: {\n trigger: {\n isMarket: false,\n triggerPx: formatHyperLiquidPrice({\n price: parseFloat(takeProfitPrice),\n szDecimals,\n }),\n tpsl: 'tp',\n },\n },\n };\n orders.push(tpOrder);\n }\n\n // 3. Stop Loss order\n if (stopLossPrice) {\n // Apply 10% slippage to SL limit price (executes as market order when triggered)\n // HyperLiquid recommended: 10% for TP/SL orders\n const stopLossPriceNum = parseFloat(stopLossPrice);\n const slippageValue = ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps / 10000;\n const limitPriceWithSlippage = isBuy\n ? stopLossPriceNum * (1 - slippageValue) // Selling to close long: willing to accept LESS (slippage protection)\n : stopLossPriceNum * (1 + slippageValue); // Buying to close short: willing to pay MORE (slippage protection)\n\n const slOrder: SDKOrderParams = {\n a: assetId,\n b: !isBuy,\n p: formatHyperLiquidPrice({\n price: limitPriceWithSlippage,\n szDecimals,\n }),\n s: formattedSize,\n r: true,\n t: {\n trigger: {\n isMarket: true,\n triggerPx: formatHyperLiquidPrice({\n price: stopLossPriceNum,\n szDecimals,\n }),\n tpsl: 'sl',\n },\n },\n };\n orders.push(slOrder);\n }\n\n // Determine grouping\n const finalGrouping: 'na' | 'normalTpsl' | 'positionTpsl' =\n grouping ?? ((takeProfitPrice ?? stopLossPrice) ? 'normalTpsl' : 'na');\n\n return { orders, grouping: finalGrouping };\n}\n"]}
|