@pear-protocol/hyperliquid-sdk 0.1.20 → 0.1.22-beta
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/README.md +12 -3
- package/dist/clients/positions.d.ts +15 -3
- package/dist/hooks/usePosition.d.ts +2 -2
- package/dist/index.d.ts +32 -5
- package/dist/index.js +56 -2
- package/dist/types.d.ts +2 -0
- package/dist/utils/position-validator.d.ts +14 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -557,8 +557,17 @@ const result = await createPosition(apiBaseUrl, {
|
|
|
557
557
|
executionType: 'MARKET',
|
|
558
558
|
});
|
|
559
559
|
|
|
560
|
-
// Close position
|
|
561
|
-
await closePosition(apiBaseUrl, positionId, {
|
|
560
|
+
// Close position immediately
|
|
561
|
+
await closePosition(apiBaseUrl, positionId, { executionType: 'MARKET' });
|
|
562
|
+
|
|
563
|
+
// Close position conditionally
|
|
564
|
+
// Example: close when the weighted price ratio rises above 1.08.
|
|
565
|
+
await closePosition(apiBaseUrl, positionId, {
|
|
566
|
+
executionType: 'TRIGGER',
|
|
567
|
+
triggerType: 'WEIGHTED_RATIO',
|
|
568
|
+
triggerValue: '1.08',
|
|
569
|
+
direction: 'MORE_THAN',
|
|
570
|
+
});
|
|
562
571
|
|
|
563
572
|
// Update TP/SL
|
|
564
573
|
await updateRiskParameters(apiBaseUrl, positionId, {
|
|
@@ -864,7 +873,7 @@ function TradingInterface() {
|
|
|
864
873
|
{openPositions?.map(pos => (
|
|
865
874
|
<div key={pos.positionId}>
|
|
866
875
|
PnL: ${pos.unrealizedPnl.toFixed(2)}
|
|
867
|
-
<button onClick={() => closePosition(pos.positionId, {
|
|
876
|
+
<button onClick={() => closePosition(pos.positionId, { executionType: 'MARKET' })}>
|
|
868
877
|
Close
|
|
869
878
|
</button>
|
|
870
879
|
</div>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ApiResponse, CreatePositionRequestInput, CreatePositionResponseDto, TpSlThresholdInput } from "../types";
|
|
1
|
+
import type { ApiResponse, CloseExecutionType, CloseTriggerType, CreatePositionRequestInput, CreatePositionResponseDto, OrderDirection, TpSlThresholdInput } from "../types";
|
|
2
2
|
import type { CancelTwapResponseDto } from "./orders";
|
|
3
3
|
/**
|
|
4
4
|
* Create a position (MARKET/LIMIT/TWAP) using Pear Hyperliquid service
|
|
@@ -18,17 +18,22 @@ export interface UpdateRiskParametersResponseDto {
|
|
|
18
18
|
updatedAt: string;
|
|
19
19
|
}
|
|
20
20
|
export declare function updateRiskParameters(baseUrl: string, positionId: string, payload: UpdateRiskParametersRequestInput): Promise<ApiResponse<UpdateRiskParametersResponseDto>>;
|
|
21
|
-
export type
|
|
21
|
+
export type ClosePositionExecutionType = CloseExecutionType;
|
|
22
|
+
export type CloseAllExecutionType = "MARKET" | "TWAP";
|
|
22
23
|
export interface ClosePositionRequestInput {
|
|
23
24
|
executionType: CloseExecutionType;
|
|
24
25
|
twapDuration?: number;
|
|
25
26
|
twapIntervalSeconds?: number;
|
|
26
27
|
randomizeExecution?: boolean;
|
|
28
|
+
triggerType?: CloseTriggerType;
|
|
29
|
+
triggerValue?: string;
|
|
30
|
+
direction?: OrderDirection;
|
|
27
31
|
referralCode?: string;
|
|
28
32
|
}
|
|
29
33
|
export interface ClosePositionResponseDto {
|
|
30
34
|
orderId: string;
|
|
31
35
|
executionTime?: string;
|
|
36
|
+
orderIds?: string[];
|
|
32
37
|
chunksScheduled?: number;
|
|
33
38
|
}
|
|
34
39
|
export declare function closePosition(baseUrl: string, positionId: string, payload: ClosePositionRequestInput): Promise<ApiResponse<ClosePositionResponseDto>>;
|
|
@@ -41,7 +46,14 @@ export interface CloseAllPositionsResultDto {
|
|
|
41
46
|
export interface CloseAllPositionsResponseDto {
|
|
42
47
|
results: CloseAllPositionsResultDto[];
|
|
43
48
|
}
|
|
44
|
-
export
|
|
49
|
+
export interface CloseAllPositionsRequestInput {
|
|
50
|
+
executionType: CloseAllExecutionType;
|
|
51
|
+
twapDuration?: number;
|
|
52
|
+
twapIntervalSeconds?: number;
|
|
53
|
+
randomizeExecution?: boolean;
|
|
54
|
+
referralCode?: string;
|
|
55
|
+
}
|
|
56
|
+
export declare function closeAllPositions(baseUrl: string, payload: CloseAllPositionsRequestInput): Promise<ApiResponse<CloseAllPositionsResponseDto>>;
|
|
45
57
|
export type AdjustExecutionType = "MARKET" | "LIMIT";
|
|
46
58
|
export type PositionAdjustmentType = "REDUCE" | "INCREASE";
|
|
47
59
|
export interface AdjustPositionRequestInput {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type UpdateRiskParametersRequestInput, type UpdateRiskParametersResponseDto, type ClosePositionRequestInput, type ClosePositionResponseDto, type CloseAllPositionsResponseDto, type AdjustPositionRequestInput, type AdjustPositionResponseDto, type AdjustAdvanceItemInput, type AdjustAdvanceResponseDto, type UpdateLeverageResponseDto } from '../clients/positions';
|
|
1
|
+
import { type UpdateRiskParametersRequestInput, type UpdateRiskParametersResponseDto, type ClosePositionRequestInput, type ClosePositionResponseDto, type CloseAllPositionsRequestInput, type CloseAllPositionsResponseDto, type AdjustPositionRequestInput, type AdjustPositionResponseDto, type AdjustAdvanceItemInput, type AdjustAdvanceResponseDto, type UpdateLeverageResponseDto } from '../clients/positions';
|
|
2
2
|
import type { ApiResponse, CreatePositionRequestInput, CreatePositionResponseDto, OpenPositionDto } from '../types';
|
|
3
3
|
export interface RebalanceAssetPlan {
|
|
4
4
|
coin: string;
|
|
@@ -23,7 +23,7 @@ export declare function usePosition(): {
|
|
|
23
23
|
readonly createPosition: (payload: CreatePositionRequestInput) => Promise<ApiResponse<CreatePositionResponseDto>>;
|
|
24
24
|
readonly updateRiskParameters: (positionId: string, payload: UpdateRiskParametersRequestInput) => Promise<ApiResponse<UpdateRiskParametersResponseDto>>;
|
|
25
25
|
readonly closePosition: (positionId: string, payload: ClosePositionRequestInput) => Promise<ApiResponse<ClosePositionResponseDto>>;
|
|
26
|
-
readonly closeAllPositions: (payload:
|
|
26
|
+
readonly closeAllPositions: (payload: CloseAllPositionsRequestInput) => Promise<ApiResponse<CloseAllPositionsResponseDto>>;
|
|
27
27
|
readonly adjustPosition: (positionId: string, payload: AdjustPositionRequestInput) => Promise<ApiResponse<AdjustPositionResponseDto>>;
|
|
28
28
|
readonly adjustAdvancePosition: (positionId: string, payload: AdjustAdvanceItemInput[]) => Promise<ApiResponse<AdjustAdvanceResponseDto>>;
|
|
29
29
|
readonly updateLeverage: (positionId: string, leverage: number) => Promise<ApiResponse<UpdateLeverageResponseDto | null>>;
|
package/dist/index.d.ts
CHANGED
|
@@ -342,6 +342,8 @@ type TpSlTriggerType = 'PERCENTAGE' | 'DOLLAR' | 'POSITION_VALUE' | 'PRICE' | 'P
|
|
|
342
342
|
* Trigger type for trigger orders
|
|
343
343
|
*/
|
|
344
344
|
type TriggerType = 'PRICE' | 'PRICE_RATIO' | 'WEIGHTED_RATIO' | 'BTC_DOM' | 'CROSS_ASSET_PRICE' | 'PREDICTION_MARKET_OUTCOME';
|
|
345
|
+
type CloseTriggerType = 'PRICE' | 'PRICE_RATIO' | 'WEIGHTED_RATIO' | 'PERCENTAGE' | 'DOLLAR' | 'POSITION_VALUE';
|
|
346
|
+
type CloseExecutionType = 'MARKET' | 'TWAP' | 'TRIGGER';
|
|
345
347
|
type OrderDirection = 'MORE_THAN' | 'LESS_THAN';
|
|
346
348
|
/**
|
|
347
349
|
* Market order parameters
|
|
@@ -1232,17 +1234,22 @@ interface UpdateRiskParametersResponseDto {
|
|
|
1232
1234
|
updatedAt: string;
|
|
1233
1235
|
}
|
|
1234
1236
|
declare function updateRiskParameters(baseUrl: string, positionId: string, payload: UpdateRiskParametersRequestInput): Promise<ApiResponse<UpdateRiskParametersResponseDto>>;
|
|
1235
|
-
type
|
|
1237
|
+
type ClosePositionExecutionType = CloseExecutionType;
|
|
1238
|
+
type CloseAllExecutionType = "MARKET" | "TWAP";
|
|
1236
1239
|
interface ClosePositionRequestInput {
|
|
1237
1240
|
executionType: CloseExecutionType;
|
|
1238
1241
|
twapDuration?: number;
|
|
1239
1242
|
twapIntervalSeconds?: number;
|
|
1240
1243
|
randomizeExecution?: boolean;
|
|
1244
|
+
triggerType?: CloseTriggerType;
|
|
1245
|
+
triggerValue?: string;
|
|
1246
|
+
direction?: OrderDirection;
|
|
1241
1247
|
referralCode?: string;
|
|
1242
1248
|
}
|
|
1243
1249
|
interface ClosePositionResponseDto {
|
|
1244
1250
|
orderId: string;
|
|
1245
1251
|
executionTime?: string;
|
|
1252
|
+
orderIds?: string[];
|
|
1246
1253
|
chunksScheduled?: number;
|
|
1247
1254
|
}
|
|
1248
1255
|
declare function closePosition(baseUrl: string, positionId: string, payload: ClosePositionRequestInput): Promise<ApiResponse<ClosePositionResponseDto>>;
|
|
@@ -1255,7 +1262,14 @@ interface CloseAllPositionsResultDto {
|
|
|
1255
1262
|
interface CloseAllPositionsResponseDto {
|
|
1256
1263
|
results: CloseAllPositionsResultDto[];
|
|
1257
1264
|
}
|
|
1258
|
-
|
|
1265
|
+
interface CloseAllPositionsRequestInput {
|
|
1266
|
+
executionType: CloseAllExecutionType;
|
|
1267
|
+
twapDuration?: number;
|
|
1268
|
+
twapIntervalSeconds?: number;
|
|
1269
|
+
randomizeExecution?: boolean;
|
|
1270
|
+
referralCode?: string;
|
|
1271
|
+
}
|
|
1272
|
+
declare function closeAllPositions(baseUrl: string, payload: CloseAllPositionsRequestInput): Promise<ApiResponse<CloseAllPositionsResponseDto>>;
|
|
1259
1273
|
type AdjustExecutionType = "MARKET" | "LIMIT";
|
|
1260
1274
|
type PositionAdjustmentType = "REDUCE" | "INCREASE";
|
|
1261
1275
|
interface AdjustPositionRequestInput {
|
|
@@ -1320,7 +1334,7 @@ declare function usePosition(): {
|
|
|
1320
1334
|
readonly createPosition: (payload: CreatePositionRequestInput) => Promise<ApiResponse<CreatePositionResponseDto>>;
|
|
1321
1335
|
readonly updateRiskParameters: (positionId: string, payload: UpdateRiskParametersRequestInput) => Promise<ApiResponse<UpdateRiskParametersResponseDto>>;
|
|
1322
1336
|
readonly closePosition: (positionId: string, payload: ClosePositionRequestInput) => Promise<ApiResponse<ClosePositionResponseDto>>;
|
|
1323
|
-
readonly closeAllPositions: (payload:
|
|
1337
|
+
readonly closeAllPositions: (payload: CloseAllPositionsRequestInput) => Promise<ApiResponse<CloseAllPositionsResponseDto>>;
|
|
1324
1338
|
readonly adjustPosition: (positionId: string, payload: AdjustPositionRequestInput) => Promise<ApiResponse<AdjustPositionResponseDto>>;
|
|
1325
1339
|
readonly adjustAdvancePosition: (positionId: string, payload: AdjustAdvanceItemInput[]) => Promise<ApiResponse<AdjustAdvanceResponseDto>>;
|
|
1326
1340
|
readonly updateLeverage: (positionId: string, leverage: number) => Promise<ApiResponse<UpdateLeverageResponseDto | null>>;
|
|
@@ -1673,6 +1687,9 @@ declare class MaxAssetsPerLegError extends Error {
|
|
|
1673
1687
|
maxAllowed: number;
|
|
1674
1688
|
constructor(leg: "long" | "short", assetCount: number, maxAllowed: number);
|
|
1675
1689
|
}
|
|
1690
|
+
declare class ClosePositionValidationError extends Error {
|
|
1691
|
+
constructor(message: string);
|
|
1692
|
+
}
|
|
1676
1693
|
/**
|
|
1677
1694
|
* Validates that each leg doesn't exceed the maximum number of assets
|
|
1678
1695
|
* @param longAssets Array of long assets
|
|
@@ -1707,6 +1724,16 @@ declare function validatePositionSize(usdValue: number, longAssets?: PairAssetIn
|
|
|
1707
1724
|
error?: string;
|
|
1708
1725
|
minimumRequired?: number;
|
|
1709
1726
|
};
|
|
1727
|
+
interface ClosePositionValidationInput {
|
|
1728
|
+
executionType: CloseExecutionType;
|
|
1729
|
+
twapDuration?: number;
|
|
1730
|
+
twapIntervalSeconds?: number;
|
|
1731
|
+
randomizeExecution?: boolean;
|
|
1732
|
+
triggerType?: CloseTriggerType;
|
|
1733
|
+
triggerValue?: string;
|
|
1734
|
+
direction?: OrderDirection;
|
|
1735
|
+
}
|
|
1736
|
+
declare function validateClosePositionRequest(payload: ClosePositionValidationInput): void;
|
|
1710
1737
|
|
|
1711
1738
|
/**
|
|
1712
1739
|
* Helper functions to safely extract values from order parameters
|
|
@@ -1772,5 +1799,5 @@ interface MarketDataState {
|
|
|
1772
1799
|
}
|
|
1773
1800
|
declare const useMarketData: zustand.UseBoundStore<zustand.StoreApi<MarketDataState>>;
|
|
1774
1801
|
|
|
1775
|
-
export { ConflictDetector, MAX_ASSETS_PER_LEG, MINIMUM_ASSET_USD_VALUE, MaxAssetsPerLegError, MinimumPositionSizeError, PearHyperliquidProvider, ReadyState, adjustAdvancePosition, adjustOrder, adjustPosition, calculateMinimumPositionValue, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closeAllPositions, closePosition, computeBasketCandles, createCandleLookups, createPosition, executeSpotOrder, getCompleteTimestamps, getKalshiMarkets, getOrderDirection, getOrderLadderConfig, getOrderLeverage, getOrderReduceOnly, getOrderTpSlTriggerType, getOrderTrailingInfo, getOrderTriggerType, getOrderTriggerValue, getOrderTwapDuration, getOrderUsdValue, getPortfolio, isBtcDomOrder, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, markNotificationReadById, markNotificationsRead, toggleWatchlist, updateLeverage, updateRiskParameters, useAccountSummary, useAgentWallet, useAllUserBalances, useAuth, useBasketCandles, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidUserFills, useMarket, useMarketData, useMarketDataHook, useNotifications, useOpenOrders, useOrders, usePearHyperliquid, usePerformanceOverlays, usePortfolio, usePosition, useSpotOrder, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWatchlist, validateMaxAssetsPerLeg, validateMinimumAssetSize, validatePositionSize };
|
|
1776
|
-
export type { AccountSummaryResponseDto, ActiveAssetData, ActiveAssetGroupItem, ActiveAssetsAllResponse, ActiveAssetsResponse, AddressState, AdjustAdvanceAssetInput, AdjustAdvanceItemInput, AdjustAdvanceResponseDto, AdjustExecutionType, AdjustOrderRequestInput, AdjustOrderResponseDto, AdjustPositionRequestInput, AdjustPositionResponseDto, AgentWalletDto, AgentWalletState, AgentWalletStatus, AllDexsAssetCtxsData, AllDexsClearinghouseStateData, AllPerpMetasItem, AllPerpMetasResponse, ApiErrorResponse, ApiResponse, AssetCtx, AssetInformationDetail, AssetMarketData, AssetPosition, AuthenticateRequest, AuthenticateResponse, AvailableToTrades, BalanceSummaryDto, BaseTriggerOrderNotificationParams, BtcDomTriggerParams, CancelOrderResponseDto, CancelTwapResponseDto, CandleChartData, CandleData, CandleInterval, CandleSnapshotRequest, ChunkFillDto, ClearinghouseState, CloseAllPositionsResponseDto, CloseAllPositionsResultDto, CloseExecutionType, ClosePositionRequestInput, ClosePositionResponseDto, CollateralToken, CreateAgentWalletResponseDto, CreatePositionRequestInput, CreatePositionResponseDto, CrossAssetPriceTriggerParams, CrossMarginSummaryDto, CumFundingDto, EIP712AuthDetails, ExecutionType, ExternalFillDto, ExternalLiquidationDto, ExtraAgent, GetAgentWalletResponseDto, GetEIP712MessageResponse, GetKalshiMarketsParams, HLChannel, HLChannelDataMap, HLWebSocketResponse, HistoricalRange, KalshiMarket, KalshiMarketsResponse, KalshiMveLeg, KalshiPriceRange, LadderConfigInput, LadderOrderParameters, LeverageInfo, LogoutRequest, LogoutResponse, MarginRequiredPerCollateral, MarginRequiredResult, MarginSummaryDto, MarginTableDef, MarginTablesEntry, MarginTier, MarketOrderParameters, NotificationCategory, NotificationDto, OpenLimitOrderDto, OpenPositionDto, OrderAssetDto, OrderDirection, OrderParameters, OrderStatus, OrderType, PairAssetDto, PairAssetInput, PerformanceOverlay, PerpDex, PerpDexsResponse, PerpMetaAsset, PlatformAccountSummaryResponseDto, PortfolioBucketDto, PortfolioInterval, PortfolioIntervalsDto, PortfolioOverallDto, PortfolioResponseDto, PositionAdjustmentType, PositionAssetDetailDto, PredictionMarketOutcomeTriggerParams, PriceRatioTriggerParams, PriceTriggerParams, PrivyAuthDetails, RawAssetDto, RawPositionDto, RealtimeBar, RealtimeBarsCallback, RebalanceAssetPlan, RebalancePlan, RefreshTokenRequest, RefreshTokenResponse, SpotBalance, SpotBalances, SpotOrderFilledStatus, SpotOrderHyperliquidData, SpotOrderHyperliquidResult, SpotOrderRequestInput, SpotOrderResponseDto, SpotState, SyncFillsRequestDto, SyncFillsResponseDto, ToggleWatchlistResponseDto, TokenConflict, TokenEntry, TokenHistoricalPriceData, TokenMetadata, TokenSelection, TokenSelectorConfig, TpSlOrderParameters, TpSlThreshold, TpSlThresholdInput, TpSlThresholdType, TpSlTriggerType, TradeHistoryAssetDataDto, TradeHistoryDataDto, TriggerOrderNotificationAsset, TriggerOrderNotificationParams, TriggerOrderNotificationType, TriggerOrderParameters, TriggerType, TwapChunkStatus, TwapChunkStatusDto, TwapMonitoringDto, TwapOrderOverallStatus, TwapOrderParameters, TwapSliceFillResponseItem, UniverseAsset, UpdateLeverageRequestInput, UpdateLeverageResponseDto, UpdateRiskParametersRequestInput, UpdateRiskParametersResponseDto, UseAuthOptions, UseBasketCandlesReturn, UseHistoricalPriceDataReturn, UseHyperliquidUserFillsOptions, UseHyperliquidUserFillsState, UseNotificationsResult, UsePerformanceOverlaysReturn, UsePortfolioResult, UseSpotOrderResult, UseTokenSelectionMetadataReturn, UserAbstraction, UserProfile, UserSelectionState, WatchlistAssetDto, WatchlistItemDto, WebData3AssetCtx, WebData3PerpDexState, WebData3Response, WebData3UserState, WebSocketAckResponse, WebSocketChannel, WebSocketConnectionState, WebSocketDataMessage, WebSocketMessage, WebSocketSubscribeMessage, WsAllMidsData };
|
|
1802
|
+
export { ClosePositionValidationError, ConflictDetector, MAX_ASSETS_PER_LEG, MINIMUM_ASSET_USD_VALUE, MaxAssetsPerLegError, MinimumPositionSizeError, PearHyperliquidProvider, ReadyState, adjustAdvancePosition, adjustOrder, adjustPosition, calculateMinimumPositionValue, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closeAllPositions, closePosition, computeBasketCandles, createCandleLookups, createPosition, executeSpotOrder, getCompleteTimestamps, getKalshiMarkets, getOrderDirection, getOrderLadderConfig, getOrderLeverage, getOrderReduceOnly, getOrderTpSlTriggerType, getOrderTrailingInfo, getOrderTriggerType, getOrderTriggerValue, getOrderTwapDuration, getOrderUsdValue, getPortfolio, isBtcDomOrder, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, markNotificationReadById, markNotificationsRead, toggleWatchlist, updateLeverage, updateRiskParameters, useAccountSummary, useAgentWallet, useAllUserBalances, useAuth, useBasketCandles, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidUserFills, useMarket, useMarketData, useMarketDataHook, useNotifications, useOpenOrders, useOrders, usePearHyperliquid, usePerformanceOverlays, usePortfolio, usePosition, useSpotOrder, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWatchlist, validateClosePositionRequest, validateMaxAssetsPerLeg, validateMinimumAssetSize, validatePositionSize };
|
|
1803
|
+
export type { AccountSummaryResponseDto, ActiveAssetData, ActiveAssetGroupItem, ActiveAssetsAllResponse, ActiveAssetsResponse, AddressState, AdjustAdvanceAssetInput, AdjustAdvanceItemInput, AdjustAdvanceResponseDto, AdjustExecutionType, AdjustOrderRequestInput, AdjustOrderResponseDto, AdjustPositionRequestInput, AdjustPositionResponseDto, AgentWalletDto, AgentWalletState, AgentWalletStatus, AllDexsAssetCtxsData, AllDexsClearinghouseStateData, AllPerpMetasItem, AllPerpMetasResponse, ApiErrorResponse, ApiResponse, AssetCtx, AssetInformationDetail, AssetMarketData, AssetPosition, AuthenticateRequest, AuthenticateResponse, AvailableToTrades, BalanceSummaryDto, BaseTriggerOrderNotificationParams, BtcDomTriggerParams, CancelOrderResponseDto, CancelTwapResponseDto, CandleChartData, CandleData, CandleInterval, CandleSnapshotRequest, ChunkFillDto, ClearinghouseState, CloseAllExecutionType, CloseAllPositionsRequestInput, CloseAllPositionsResponseDto, CloseAllPositionsResultDto, CloseExecutionType, ClosePositionExecutionType, ClosePositionRequestInput, ClosePositionResponseDto, CloseTriggerType, CollateralToken, CreateAgentWalletResponseDto, CreatePositionRequestInput, CreatePositionResponseDto, CrossAssetPriceTriggerParams, CrossMarginSummaryDto, CumFundingDto, EIP712AuthDetails, ExecutionType, ExternalFillDto, ExternalLiquidationDto, ExtraAgent, GetAgentWalletResponseDto, GetEIP712MessageResponse, GetKalshiMarketsParams, HLChannel, HLChannelDataMap, HLWebSocketResponse, HistoricalRange, KalshiMarket, KalshiMarketsResponse, KalshiMveLeg, KalshiPriceRange, LadderConfigInput, LadderOrderParameters, LeverageInfo, LogoutRequest, LogoutResponse, MarginRequiredPerCollateral, MarginRequiredResult, MarginSummaryDto, MarginTableDef, MarginTablesEntry, MarginTier, MarketOrderParameters, NotificationCategory, NotificationDto, OpenLimitOrderDto, OpenPositionDto, OrderAssetDto, OrderDirection, OrderParameters, OrderStatus, OrderType, PairAssetDto, PairAssetInput, PerformanceOverlay, PerpDex, PerpDexsResponse, PerpMetaAsset, PlatformAccountSummaryResponseDto, PortfolioBucketDto, PortfolioInterval, PortfolioIntervalsDto, PortfolioOverallDto, PortfolioResponseDto, PositionAdjustmentType, PositionAssetDetailDto, PredictionMarketOutcomeTriggerParams, PriceRatioTriggerParams, PriceTriggerParams, PrivyAuthDetails, RawAssetDto, RawPositionDto, RealtimeBar, RealtimeBarsCallback, RebalanceAssetPlan, RebalancePlan, RefreshTokenRequest, RefreshTokenResponse, SpotBalance, SpotBalances, SpotOrderFilledStatus, SpotOrderHyperliquidData, SpotOrderHyperliquidResult, SpotOrderRequestInput, SpotOrderResponseDto, SpotState, SyncFillsRequestDto, SyncFillsResponseDto, ToggleWatchlistResponseDto, TokenConflict, TokenEntry, TokenHistoricalPriceData, TokenMetadata, TokenSelection, TokenSelectorConfig, TpSlOrderParameters, TpSlThreshold, TpSlThresholdInput, TpSlThresholdType, TpSlTriggerType, TradeHistoryAssetDataDto, TradeHistoryDataDto, TriggerOrderNotificationAsset, TriggerOrderNotificationParams, TriggerOrderNotificationType, TriggerOrderParameters, TriggerType, TwapChunkStatus, TwapChunkStatusDto, TwapMonitoringDto, TwapOrderOverallStatus, TwapOrderParameters, TwapSliceFillResponseItem, UniverseAsset, UpdateLeverageRequestInput, UpdateLeverageResponseDto, UpdateRiskParametersRequestInput, UpdateRiskParametersResponseDto, UseAuthOptions, UseBasketCandlesReturn, UseHistoricalPriceDataReturn, UseHyperliquidUserFillsOptions, UseHyperliquidUserFillsState, UseNotificationsResult, UsePerformanceOverlaysReturn, UsePortfolioResult, UseSpotOrderResult, UseTokenSelectionMetadataReturn, UserAbstraction, UserProfile, UserSelectionState, WatchlistAssetDto, WatchlistItemDto, WebData3AssetCtx, WebData3PerpDexState, WebData3Response, WebData3UserState, WebSocketAckResponse, WebSocketChannel, WebSocketConnectionState, WebSocketDataMessage, WebSocketMessage, WebSocketSubscribeMessage, WsAllMidsData };
|
package/dist/index.js
CHANGED
|
@@ -696,6 +696,12 @@ class MaxAssetsPerLegError extends Error {
|
|
|
696
696
|
this.name = "MaxAssetsPerLegError";
|
|
697
697
|
}
|
|
698
698
|
}
|
|
699
|
+
class ClosePositionValidationError extends Error {
|
|
700
|
+
constructor(message) {
|
|
701
|
+
super(message);
|
|
702
|
+
this.name = "ClosePositionValidationError";
|
|
703
|
+
}
|
|
704
|
+
}
|
|
699
705
|
/**
|
|
700
706
|
* Validates that each leg doesn't exceed the maximum number of assets
|
|
701
707
|
* @param longAssets Array of long assets
|
|
@@ -776,6 +782,44 @@ function validatePositionSize(usdValue, longAssets, shortAssets) {
|
|
|
776
782
|
throw error;
|
|
777
783
|
}
|
|
778
784
|
}
|
|
785
|
+
function isNumberString(value) {
|
|
786
|
+
if (value.trim() === "") {
|
|
787
|
+
return false;
|
|
788
|
+
}
|
|
789
|
+
return Number.isFinite(Number(value));
|
|
790
|
+
}
|
|
791
|
+
function validateClosePositionRequest(payload) {
|
|
792
|
+
if (payload.executionType === "TWAP") {
|
|
793
|
+
if (payload.twapDuration === undefined || payload.twapDuration <= 0) {
|
|
794
|
+
throw new ClosePositionValidationError("twapDuration is required and must be greater than 0 when executionType is TWAP");
|
|
795
|
+
}
|
|
796
|
+
if (payload.twapIntervalSeconds !== undefined &&
|
|
797
|
+
payload.twapIntervalSeconds <= 0) {
|
|
798
|
+
throw new ClosePositionValidationError("twapIntervalSeconds must be greater than 0 when provided for TWAP closes");
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
else if (payload.twapDuration !== undefined ||
|
|
802
|
+
payload.twapIntervalSeconds !== undefined ||
|
|
803
|
+
payload.randomizeExecution !== undefined) {
|
|
804
|
+
throw new ClosePositionValidationError("twapDuration, twapIntervalSeconds, and randomizeExecution are only supported when executionType is TWAP");
|
|
805
|
+
}
|
|
806
|
+
if (payload.executionType === "TRIGGER") {
|
|
807
|
+
if (!payload.triggerType) {
|
|
808
|
+
throw new ClosePositionValidationError("triggerType is required when executionType is TRIGGER");
|
|
809
|
+
}
|
|
810
|
+
if (!payload.direction) {
|
|
811
|
+
throw new ClosePositionValidationError("direction is required when executionType is TRIGGER");
|
|
812
|
+
}
|
|
813
|
+
if (!payload.triggerValue || !isNumberString(payload.triggerValue)) {
|
|
814
|
+
throw new ClosePositionValidationError("triggerValue is required and must be a numeric string when executionType is TRIGGER");
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
else if (payload.triggerType !== undefined ||
|
|
818
|
+
payload.triggerValue !== undefined ||
|
|
819
|
+
payload.direction !== undefined) {
|
|
820
|
+
throw new ClosePositionValidationError("triggerType, triggerValue, and direction are only supported when executionType is TRIGGER");
|
|
821
|
+
}
|
|
822
|
+
}
|
|
779
823
|
|
|
780
824
|
const DEFAULT_STATE = {
|
|
781
825
|
longTokens: [
|
|
@@ -6950,10 +6994,20 @@ async function updateRiskParameters(baseUrl, positionId, payload) {
|
|
|
6950
6994
|
throw toApiError(error);
|
|
6951
6995
|
}
|
|
6952
6996
|
}
|
|
6997
|
+
function normalizeClosePositionPayload(payload) {
|
|
6998
|
+
return {
|
|
6999
|
+
...payload,
|
|
7000
|
+
triggerValue: payload.triggerValue === undefined
|
|
7001
|
+
? undefined
|
|
7002
|
+
: String(payload.triggerValue),
|
|
7003
|
+
};
|
|
7004
|
+
}
|
|
6953
7005
|
async function closePosition(baseUrl, positionId, payload) {
|
|
6954
7006
|
const url = joinUrl(baseUrl, `/positions/${positionId}/close`);
|
|
7007
|
+
const normalizedPayload = normalizeClosePositionPayload(payload);
|
|
7008
|
+
validateClosePositionRequest(normalizedPayload);
|
|
6955
7009
|
try {
|
|
6956
|
-
const resp = await apiClient.post(url,
|
|
7010
|
+
const resp = await apiClient.post(url, normalizedPayload, {
|
|
6957
7011
|
headers: {
|
|
6958
7012
|
"Content-Type": "application/json",
|
|
6959
7013
|
},
|
|
@@ -8773,4 +8827,4 @@ function getOrderTrailingInfo(order) {
|
|
|
8773
8827
|
return undefined;
|
|
8774
8828
|
}
|
|
8775
8829
|
|
|
8776
|
-
export { ConflictDetector, MAX_ASSETS_PER_LEG, MINIMUM_ASSET_USD_VALUE, MaxAssetsPerLegError, MinimumPositionSizeError, PearHyperliquidProvider, adjustAdvancePosition, adjustOrder, adjustPosition, calculateMinimumPositionValue, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closeAllPositions, closePosition, computeBasketCandles, createCandleLookups, createPosition, executeSpotOrder, getCompleteTimestamps, getKalshiMarkets, getOrderDirection, getOrderLadderConfig, getOrderLeverage, getOrderReduceOnly, getOrderTpSlTriggerType, getOrderTrailingInfo, getOrderTriggerType, getOrderTriggerValue, getOrderTwapDuration, getOrderUsdValue, getPortfolio, isBtcDomOrder, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, markNotificationReadById, markNotificationsRead, toggleWatchlist, updateLeverage, updateRiskParameters, useAccountSummary, useAgentWallet, useAllUserBalances, useAuth, useBasketCandles, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidUserFills, useMarket, useMarketData, useMarketDataHook, useNotifications, useOpenOrders, useOrders, usePearHyperliquid, usePerformanceOverlays, usePortfolio, usePosition, useSpotOrder, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWatchlist, validateMaxAssetsPerLeg, validateMinimumAssetSize, validatePositionSize };
|
|
8830
|
+
export { ClosePositionValidationError, ConflictDetector, MAX_ASSETS_PER_LEG, MINIMUM_ASSET_USD_VALUE, MaxAssetsPerLegError, MinimumPositionSizeError, PearHyperliquidProvider, adjustAdvancePosition, adjustOrder, adjustPosition, calculateMinimumPositionValue, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closeAllPositions, closePosition, computeBasketCandles, createCandleLookups, createPosition, executeSpotOrder, getCompleteTimestamps, getKalshiMarkets, getOrderDirection, getOrderLadderConfig, getOrderLeverage, getOrderReduceOnly, getOrderTpSlTriggerType, getOrderTrailingInfo, getOrderTriggerType, getOrderTriggerValue, getOrderTwapDuration, getOrderUsdValue, getPortfolio, isBtcDomOrder, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, markNotificationReadById, markNotificationsRead, toggleWatchlist, updateLeverage, updateRiskParameters, useAccountSummary, useAgentWallet, useAllUserBalances, useAuth, useBasketCandles, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidUserFills, useMarket, useMarketData, useMarketDataHook, useNotifications, useOpenOrders, useOrders, usePearHyperliquid, usePerformanceOverlays, usePortfolio, usePosition, useSpotOrder, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWatchlist, validateClosePositionRequest, validateMaxAssetsPerLeg, validateMinimumAssetSize, validatePositionSize };
|
package/dist/types.d.ts
CHANGED
|
@@ -314,6 +314,8 @@ export type TpSlTriggerType = 'PERCENTAGE' | 'DOLLAR' | 'POSITION_VALUE' | 'PRIC
|
|
|
314
314
|
* Trigger type for trigger orders
|
|
315
315
|
*/
|
|
316
316
|
export type TriggerType = 'PRICE' | 'PRICE_RATIO' | 'WEIGHTED_RATIO' | 'BTC_DOM' | 'CROSS_ASSET_PRICE' | 'PREDICTION_MARKET_OUTCOME';
|
|
317
|
+
export type CloseTriggerType = 'PRICE' | 'PRICE_RATIO' | 'WEIGHTED_RATIO' | 'PERCENTAGE' | 'DOLLAR' | 'POSITION_VALUE';
|
|
318
|
+
export type CloseExecutionType = 'MARKET' | 'TWAP' | 'TRIGGER';
|
|
317
319
|
export type OrderDirection = 'MORE_THAN' | 'LESS_THAN';
|
|
318
320
|
/**
|
|
319
321
|
* Market order parameters
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PairAssetInput } from "../types";
|
|
1
|
+
import type { CloseExecutionType, CloseTriggerType, OrderDirection, PairAssetInput } from "../types";
|
|
2
2
|
/**
|
|
3
3
|
* Minimum USD value required per asset when creating a position
|
|
4
4
|
*/
|
|
@@ -25,6 +25,9 @@ export declare class MaxAssetsPerLegError extends Error {
|
|
|
25
25
|
maxAllowed: number;
|
|
26
26
|
constructor(leg: "long" | "short", assetCount: number, maxAllowed: number);
|
|
27
27
|
}
|
|
28
|
+
export declare class ClosePositionValidationError extends Error {
|
|
29
|
+
constructor(message: string);
|
|
30
|
+
}
|
|
28
31
|
/**
|
|
29
32
|
* Validates that each leg doesn't exceed the maximum number of assets
|
|
30
33
|
* @param longAssets Array of long assets
|
|
@@ -59,3 +62,13 @@ export declare function validatePositionSize(usdValue: number, longAssets?: Pair
|
|
|
59
62
|
error?: string;
|
|
60
63
|
minimumRequired?: number;
|
|
61
64
|
};
|
|
65
|
+
export interface ClosePositionValidationInput {
|
|
66
|
+
executionType: CloseExecutionType;
|
|
67
|
+
twapDuration?: number;
|
|
68
|
+
twapIntervalSeconds?: number;
|
|
69
|
+
randomizeExecution?: boolean;
|
|
70
|
+
triggerType?: CloseTriggerType;
|
|
71
|
+
triggerValue?: string;
|
|
72
|
+
direction?: OrderDirection;
|
|
73
|
+
}
|
|
74
|
+
export declare function validateClosePositionRequest(payload: ClosePositionValidationInput): void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pear-protocol/hyperliquid-sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.22-beta",
|
|
4
4
|
"description": "React SDK for Pear Protocol Hyperliquid API integration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"zustand": "^5.0.9"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
|
-
"react": "^18.0.0",
|
|
32
|
-
"react-dom": "^18.0.0"
|
|
31
|
+
"react": "^18.0.0 || ^19.0.0",
|
|
32
|
+
"react-dom": "^18.0.0 || ^19.0.0"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@rollup/plugin-commonjs": "^25.0.0",
|