@pear-protocol/hyperliquid-sdk 0.1.1-9.2-pnl → 0.1.2-1.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 CHANGED
@@ -557,8 +557,16 @@ const result = await createPosition(apiBaseUrl, {
557
557
  executionType: 'MARKET',
558
558
  });
559
559
 
560
- // Close position
561
- await closePosition(apiBaseUrl, positionId, { slippage: 0.5 });
560
+ // Close position immediately
561
+ await closePosition(apiBaseUrl, positionId, { executionType: 'MARKET' });
562
+
563
+ // Close position conditionally
564
+ await closePosition(apiBaseUrl, positionId, {
565
+ executionType: 'TRIGGER',
566
+ triggerType: 'WEIGHTED_RATIO',
567
+ triggerValue: '1.08',
568
+ direction: 'MORE_THAN',
569
+ });
562
570
 
563
571
  // Update TP/SL
564
572
  await updateRiskParameters(apiBaseUrl, positionId, {
@@ -864,7 +872,7 @@ function TradingInterface() {
864
872
  {openPositions?.map(pos => (
865
873
  <div key={pos.positionId}>
866
874
  PnL: ${pos.unrealizedPnl.toFixed(2)}
867
- <button onClick={() => closePosition(pos.positionId, { slippage: 0.5 })}>
875
+ <button onClick={() => closePosition(pos.positionId, { executionType: 'MARKET' })}>
868
876
  Close
869
877
  </button>
870
878
  </div>
@@ -1,4 +1,4 @@
1
- import type { ApiResponse, CreatePositionRequestInput, CreatePositionResponseDto, TpSlThresholdInput } from "../types";
1
+ import type { ApiResponse, 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,12 +18,16 @@ 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 CloseExecutionType = "MARKET" | "TWAP";
21
+ export type ClosePositionExecutionType = "MARKET" | "TWAP" | "TRIGGER";
22
+ export type CloseAllExecutionType = "MARKET" | "TWAP";
22
23
  export interface ClosePositionRequestInput {
23
- executionType: CloseExecutionType;
24
+ executionType: ClosePositionExecutionType;
24
25
  twapDuration?: number;
25
26
  twapIntervalSeconds?: number;
26
27
  randomizeExecution?: boolean;
28
+ triggerType?: CloseTriggerType;
29
+ triggerValue?: string | number;
30
+ direction?: OrderDirection;
27
31
  referralCode?: string;
28
32
  }
29
33
  export interface ClosePositionResponseDto {
@@ -41,7 +45,14 @@ export interface CloseAllPositionsResultDto {
41
45
  export interface CloseAllPositionsResponseDto {
42
46
  results: CloseAllPositionsResultDto[];
43
47
  }
44
- export declare function closeAllPositions(baseUrl: string, payload: ClosePositionRequestInput): Promise<ApiResponse<CloseAllPositionsResponseDto>>;
48
+ export interface CloseAllPositionsRequestInput {
49
+ executionType: CloseAllExecutionType;
50
+ twapDuration?: number;
51
+ twapIntervalSeconds?: number;
52
+ randomizeExecution?: boolean;
53
+ referralCode?: string;
54
+ }
55
+ export declare function closeAllPositions(baseUrl: string, payload: CloseAllPositionsRequestInput): Promise<ApiResponse<CloseAllPositionsResponseDto>>;
45
56
  export type AdjustExecutionType = "MARKET" | "LIMIT";
46
57
  export type PositionAdjustmentType = "REDUCE" | "INCREASE";
47
58
  export interface AdjustPositionRequestInput {
@@ -18,4 +18,3 @@ export * from './usePortfolio';
18
18
  export * from './useAuth';
19
19
  export * from './useAllUserBalances';
20
20
  export * from './useHyperliquidUserFills';
21
- export * from './usePnlCalendar';
@@ -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: ClosePositionRequestInput) => Promise<ApiResponse<CloseAllPositionsResponseDto>>;
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,7 @@ 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';
345
346
  type OrderDirection = 'MORE_THAN' | 'LESS_THAN';
346
347
  /**
347
348
  * Market order parameters
@@ -1232,12 +1233,16 @@ interface UpdateRiskParametersResponseDto {
1232
1233
  updatedAt: string;
1233
1234
  }
1234
1235
  declare function updateRiskParameters(baseUrl: string, positionId: string, payload: UpdateRiskParametersRequestInput): Promise<ApiResponse<UpdateRiskParametersResponseDto>>;
1235
- type CloseExecutionType = "MARKET" | "TWAP";
1236
+ type ClosePositionExecutionType = "MARKET" | "TWAP" | "TRIGGER";
1237
+ type CloseAllExecutionType = "MARKET" | "TWAP";
1236
1238
  interface ClosePositionRequestInput {
1237
- executionType: CloseExecutionType;
1239
+ executionType: ClosePositionExecutionType;
1238
1240
  twapDuration?: number;
1239
1241
  twapIntervalSeconds?: number;
1240
1242
  randomizeExecution?: boolean;
1243
+ triggerType?: CloseTriggerType;
1244
+ triggerValue?: string | number;
1245
+ direction?: OrderDirection;
1241
1246
  referralCode?: string;
1242
1247
  }
1243
1248
  interface ClosePositionResponseDto {
@@ -1255,7 +1260,14 @@ interface CloseAllPositionsResultDto {
1255
1260
  interface CloseAllPositionsResponseDto {
1256
1261
  results: CloseAllPositionsResultDto[];
1257
1262
  }
1258
- declare function closeAllPositions(baseUrl: string, payload: ClosePositionRequestInput): Promise<ApiResponse<CloseAllPositionsResponseDto>>;
1263
+ interface CloseAllPositionsRequestInput {
1264
+ executionType: CloseAllExecutionType;
1265
+ twapDuration?: number;
1266
+ twapIntervalSeconds?: number;
1267
+ randomizeExecution?: boolean;
1268
+ referralCode?: string;
1269
+ }
1270
+ declare function closeAllPositions(baseUrl: string, payload: CloseAllPositionsRequestInput): Promise<ApiResponse<CloseAllPositionsResponseDto>>;
1259
1271
  type AdjustExecutionType = "MARKET" | "LIMIT";
1260
1272
  type PositionAdjustmentType = "REDUCE" | "INCREASE";
1261
1273
  interface AdjustPositionRequestInput {
@@ -1320,7 +1332,7 @@ declare function usePosition(): {
1320
1332
  readonly createPosition: (payload: CreatePositionRequestInput) => Promise<ApiResponse<CreatePositionResponseDto>>;
1321
1333
  readonly updateRiskParameters: (positionId: string, payload: UpdateRiskParametersRequestInput) => Promise<ApiResponse<UpdateRiskParametersResponseDto>>;
1322
1334
  readonly closePosition: (positionId: string, payload: ClosePositionRequestInput) => Promise<ApiResponse<ClosePositionResponseDto>>;
1323
- readonly closeAllPositions: (payload: ClosePositionRequestInput) => Promise<ApiResponse<CloseAllPositionsResponseDto>>;
1335
+ readonly closeAllPositions: (payload: CloseAllPositionsRequestInput) => Promise<ApiResponse<CloseAllPositionsResponseDto>>;
1324
1336
  readonly adjustPosition: (positionId: string, payload: AdjustPositionRequestInput) => Promise<ApiResponse<AdjustPositionResponseDto>>;
1325
1337
  readonly adjustAdvancePosition: (positionId: string, payload: AdjustAdvanceItemInput[]) => Promise<ApiResponse<AdjustAdvanceResponseDto>>;
1326
1338
  readonly updateLeverage: (positionId: string, leverage: number) => Promise<ApiResponse<UpdateLeverageResponseDto | null>>;
@@ -1498,52 +1510,6 @@ interface UseHyperliquidUserFillsState {
1498
1510
  */
1499
1511
  declare function useHyperliquidUserFills(options: UseHyperliquidUserFillsOptions): UseHyperliquidUserFillsState;
1500
1512
 
1501
- type PnlCalendarTimeframe = '2W' | '3W' | '2M' | '3M';
1502
- interface PnlCalendarOptions {
1503
- timeframe?: PnlCalendarTimeframe;
1504
- startDate?: Date | string;
1505
- endDate?: Date | string;
1506
- }
1507
- interface PnlCalendarDay {
1508
- date: string;
1509
- totalPnl: number;
1510
- volume: number;
1511
- positionsClosed: number;
1512
- result: 'profit' | 'loss' | 'breakeven';
1513
- tokens: string[];
1514
- }
1515
- interface PeriodSummary {
1516
- pnl: number;
1517
- volume: number;
1518
- winRate: number;
1519
- wins: number;
1520
- losses: number;
1521
- totalProfit: number;
1522
- totalLoss: number;
1523
- }
1524
- interface PnlCalendarWeek {
1525
- weekStart: string;
1526
- weekEnd: string;
1527
- days: PnlCalendarDay[];
1528
- summary: PeriodSummary;
1529
- }
1530
- interface PnlCalendarMonth {
1531
- month: string;
1532
- label: string;
1533
- days: PnlCalendarDay[];
1534
- summary: PeriodSummary;
1535
- }
1536
- interface UsePnlCalendarResult {
1537
- timeframe: PnlCalendarTimeframe;
1538
- weeks: PnlCalendarWeek[];
1539
- months: PnlCalendarMonth[];
1540
- overall: PeriodSummary;
1541
- isLoading: boolean;
1542
- error: string | null;
1543
- refetch: () => void;
1544
- }
1545
- declare function usePnlCalendar(options?: PnlCalendarTimeframe | PnlCalendarOptions): UsePnlCalendarResult;
1546
-
1547
1513
  /**
1548
1514
  * Mark notifications as read up to a given timestamp (ms)
1549
1515
  */
@@ -1818,5 +1784,5 @@ interface MarketDataState {
1818
1784
  }
1819
1785
  declare const useMarketData: zustand.UseBoundStore<zustand.StoreApi<MarketDataState>>;
1820
1786
 
1821
- 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, usePnlCalendar, usePortfolio, usePosition, useSpotOrder, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWatchlist, validateMaxAssetsPerLeg, validateMinimumAssetSize, validatePositionSize };
1822
- 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, PeriodSummary, PerpDex, PerpDexsResponse, PerpMetaAsset, PlatformAccountSummaryResponseDto, PnlCalendarDay, PnlCalendarMonth, PnlCalendarOptions, PnlCalendarTimeframe, PnlCalendarWeek, 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, UsePnlCalendarResult, UsePortfolioResult, UseSpotOrderResult, UseTokenSelectionMetadataReturn, UserAbstraction, UserProfile, UserSelectionState, WatchlistAssetDto, WatchlistItemDto, WebData3AssetCtx, WebData3PerpDexState, WebData3Response, WebData3UserState, WebSocketAckResponse, WebSocketChannel, WebSocketConnectionState, WebSocketDataMessage, WebSocketMessage, WebSocketSubscribeMessage, WsAllMidsData };
1787
+ 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 };
1788
+ 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, 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
@@ -981,7 +981,7 @@ const useHyperliquidNativeWebSocket = ({ address, enabled = true, onUserFills, }
981
981
  // finalAssetContexts now sourced from allDexsAssetCtxs channel
982
982
  const finalAtOICaps = webData3.perpDexStates.flatMap((dex) => dex.perpsAtOpenInterestCap);
983
983
  setFinalAtOICaps(finalAtOICaps);
984
- setUserAbstractionMode(webData3.userState.abstraction || null);
984
+ setUserAbstractionMode(webData3.userState.abstraction || 'disabled');
985
985
  break;
986
986
  case "allDexsAssetCtxs":
987
987
  {
@@ -8422,322 +8422,6 @@ function useHyperliquidUserFills(options) {
8422
8422
  };
8423
8423
  }
8424
8424
 
8425
- async function getTradeHistory(baseUrl, params) {
8426
- const url = joinUrl(baseUrl, '/trade-history');
8427
- try {
8428
- const resp = await apiClient.get(url, {
8429
- params,
8430
- timeout: 60000,
8431
- });
8432
- return { data: resp.data, status: resp.status, headers: resp.headers };
8433
- }
8434
- catch (error) {
8435
- throw toApiError(error);
8436
- }
8437
- }
8438
-
8439
- // ─── helpers ────────────────────────────────────────────────────
8440
- const EMPTY_SUMMARY = {
8441
- pnl: 0,
8442
- volume: 0,
8443
- winRate: 0,
8444
- wins: 0,
8445
- losses: 0,
8446
- totalProfit: 0,
8447
- totalLoss: 0,
8448
- };
8449
- const getTimeframeDays = (tf) => {
8450
- switch (tf) {
8451
- case '2W':
8452
- return 14;
8453
- case '3W':
8454
- return 21;
8455
- case '2M':
8456
- return 60;
8457
- case '3M':
8458
- return 90;
8459
- }
8460
- };
8461
- const isWeekTimeframe = (tf) => tf === '2W' || tf === '3W';
8462
- const toDateKey = (date) => {
8463
- const y = date.getFullYear();
8464
- const m = String(date.getMonth() + 1).padStart(2, '0');
8465
- const d = String(date.getDate()).padStart(2, '0');
8466
- return `${y}-${m}-${d}`;
8467
- };
8468
- const toMonthKey = (date) => {
8469
- const y = date.getFullYear();
8470
- const m = String(date.getMonth() + 1).padStart(2, '0');
8471
- return `${y}-${m}`;
8472
- };
8473
- const formatMonthLabel = (date) => date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
8474
- const getMonday = (date) => {
8475
- const d = new Date(date);
8476
- const day = d.getDay(); // 0=Sun … 6=Sat
8477
- const diff = day === 0 ? -6 : 1 - day;
8478
- d.setDate(d.getDate() + diff);
8479
- d.setHours(0, 0, 0, 0);
8480
- return d;
8481
- };
8482
- const toLocalMidnight = (input) => {
8483
- const d = typeof input === 'string' ? new Date(input + 'T00:00:00') : new Date(input);
8484
- d.setHours(0, 0, 0, 0);
8485
- return d;
8486
- };
8487
- const diffDays = (start, end) => {
8488
- return Math.round((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
8489
- };
8490
- const toISODateString = (input) => {
8491
- const d = typeof input === 'string' ? new Date(input + 'T00:00:00') : new Date(input);
8492
- return d.toISOString();
8493
- };
8494
- const round2 = (n) => Math.round(n * 100) / 100;
8495
- const buildSummary = (days) => {
8496
- let pnl = 0;
8497
- let volume = 0;
8498
- let wins = 0;
8499
- let losses = 0;
8500
- let totalProfit = 0;
8501
- let totalLoss = 0;
8502
- for (const day of days) {
8503
- pnl += day.totalPnl;
8504
- volume += day.volume;
8505
- if (day.positionsClosed === 0)
8506
- continue;
8507
- if (day.totalPnl > 0) {
8508
- wins++;
8509
- totalProfit += day.totalPnl;
8510
- }
8511
- else if (day.totalPnl < 0) {
8512
- losses++;
8513
- totalLoss += Math.abs(day.totalPnl);
8514
- }
8515
- }
8516
- const total = wins + losses;
8517
- const winRate = total > 0 ? Math.round((wins / total) * 100) : 0;
8518
- return {
8519
- pnl: round2(pnl),
8520
- volume: round2(volume),
8521
- winRate,
8522
- wins,
8523
- losses,
8524
- totalProfit: round2(totalProfit),
8525
- totalLoss: round2(totalLoss),
8526
- };
8527
- };
8528
- const extractTokens = (trade) => {
8529
- const tokens = new Set();
8530
- for (const asset of trade.closedLongAssets) {
8531
- if (asset.coin)
8532
- tokens.add(asset.coin);
8533
- }
8534
- for (const asset of trade.closedShortAssets) {
8535
- if (asset.coin)
8536
- tokens.add(asset.coin);
8537
- }
8538
- return Array.from(tokens);
8539
- };
8540
- const buildCalendarData = (tradeHistories, timeframe, rangeStart, rangeEnd, totalDays, useCustomDates) => {
8541
- const startKey = toDateKey(rangeStart);
8542
- const endKey = toDateKey(rangeEnd);
8543
- // Build day buckets for the full range
8544
- const buckets = new Map();
8545
- for (let i = 0; i < totalDays; i++) {
8546
- const d = new Date(rangeStart);
8547
- d.setDate(rangeStart.getDate() + i);
8548
- buckets.set(toDateKey(d), {
8549
- pnl: 0,
8550
- volume: 0,
8551
- positionsClosed: 0,
8552
- tokens: new Set(),
8553
- });
8554
- }
8555
- // Populate buckets from trade histories
8556
- for (const trade of tradeHistories) {
8557
- if (!trade.createdAt)
8558
- continue;
8559
- const date = new Date(trade.createdAt);
8560
- if (isNaN(date.getTime()))
8561
- continue;
8562
- const dateKey = toDateKey(date);
8563
- if (dateKey < startKey || dateKey > endKey)
8564
- continue;
8565
- const bucket = buckets.get(dateKey);
8566
- if (!bucket)
8567
- continue;
8568
- const pnl = trade.realizedPnl;
8569
- bucket.pnl += isFinite(pnl) ? pnl : 0;
8570
- const vol = trade.totalValue;
8571
- bucket.volume += isFinite(vol) ? vol : 0;
8572
- bucket.positionsClosed += 1;
8573
- for (const token of extractTokens(trade)) {
8574
- bucket.tokens.add(token);
8575
- }
8576
- }
8577
- // Build day objects
8578
- const allDays = [];
8579
- const sortedKeys = Array.from(buckets.keys()).sort();
8580
- for (const key of sortedKeys) {
8581
- const bucket = buckets.get(key);
8582
- const roundedPnl = round2(bucket.pnl);
8583
- const result = roundedPnl > 0 ? 'profit' : roundedPnl < 0 ? 'loss' : 'breakeven';
8584
- allDays.push({
8585
- date: key,
8586
- totalPnl: roundedPnl,
8587
- volume: round2(bucket.volume),
8588
- positionsClosed: bucket.positionsClosed,
8589
- result,
8590
- tokens: Array.from(bucket.tokens),
8591
- });
8592
- }
8593
- // Group into periods
8594
- let weeks = [];
8595
- let months = [];
8596
- const useWeekGrouping = useCustomDates
8597
- ? totalDays <= 28
8598
- : isWeekTimeframe(timeframe);
8599
- if (useWeekGrouping) {
8600
- const weekMap = new Map();
8601
- for (const day of allDays) {
8602
- const date = new Date(day.date + 'T00:00:00');
8603
- const monday = getMonday(date);
8604
- const mondayKey = toDateKey(monday);
8605
- if (!weekMap.has(mondayKey)) {
8606
- weekMap.set(mondayKey, []);
8607
- }
8608
- weekMap.get(mondayKey).push(day);
8609
- }
8610
- const sortedWeekKeys = Array.from(weekMap.keys()).sort();
8611
- weeks = sortedWeekKeys.map((mondayKey) => {
8612
- const days = weekMap.get(mondayKey);
8613
- const monday = new Date(mondayKey + 'T00:00:00');
8614
- const sunday = new Date(monday);
8615
- sunday.setDate(monday.getDate() + 6);
8616
- return {
8617
- weekStart: mondayKey,
8618
- weekEnd: toDateKey(sunday),
8619
- days,
8620
- summary: buildSummary(days),
8621
- };
8622
- });
8623
- }
8624
- else {
8625
- const monthMap = new Map();
8626
- for (const day of allDays) {
8627
- const date = new Date(day.date + 'T00:00:00');
8628
- const mk = toMonthKey(date);
8629
- if (!monthMap.has(mk)) {
8630
- monthMap.set(mk, { days: [], label: formatMonthLabel(date) });
8631
- }
8632
- monthMap.get(mk).days.push(day);
8633
- }
8634
- const sortedMonthKeys = Array.from(monthMap.keys()).sort();
8635
- months = sortedMonthKeys.map((mk) => {
8636
- const { days, label } = monthMap.get(mk);
8637
- return {
8638
- month: mk,
8639
- label,
8640
- days,
8641
- summary: buildSummary(days),
8642
- };
8643
- });
8644
- }
8645
- return {
8646
- timeframe,
8647
- weeks,
8648
- months,
8649
- overall: buildSummary(allDays),
8650
- isLoading: false,
8651
- };
8652
- };
8653
- // ─── hook ───────────────────────────────────────────────────────
8654
- function usePnlCalendar(options) {
8655
- var _a;
8656
- const opts = typeof options === 'string'
8657
- ? { timeframe: options }
8658
- : options !== null && options !== void 0 ? options : {};
8659
- const timeframe = (_a = opts.timeframe) !== null && _a !== void 0 ? _a : '2W';
8660
- const customStart = opts.startDate;
8661
- const customEnd = opts.endDate;
8662
- const context = useContext(PearHyperliquidContext);
8663
- if (!context) {
8664
- throw new Error('usePnlCalendar must be used within a PearHyperliquidProvider');
8665
- }
8666
- const { apiBaseUrl } = context;
8667
- const isAuthenticated = useUserData((state) => state.isAuthenticated);
8668
- const [trades, setTrades] = useState(null);
8669
- const [isLoading, setIsLoading] = useState(false);
8670
- const [error, setError] = useState(null);
8671
- const mountedRef = useRef(true);
8672
- useEffect(() => {
8673
- mountedRef.current = true;
8674
- return () => { mountedRef.current = false; };
8675
- }, []);
8676
- // Compute the date range
8677
- const useCustomDates = !!(customStart && customEnd);
8678
- let rangeStart;
8679
- let rangeEnd;
8680
- let totalDays;
8681
- if (useCustomDates) {
8682
- rangeStart = toLocalMidnight(customStart);
8683
- rangeEnd = toLocalMidnight(customEnd);
8684
- totalDays = diffDays(rangeStart, rangeEnd);
8685
- }
8686
- else {
8687
- totalDays = getTimeframeDays(timeframe);
8688
- rangeEnd = new Date();
8689
- rangeEnd.setHours(0, 0, 0, 0);
8690
- rangeStart = new Date(rangeEnd);
8691
- rangeStart.setDate(rangeEnd.getDate() - totalDays + 1);
8692
- }
8693
- const startIso = toISODateString(rangeStart);
8694
- const endIso = toISODateString(rangeEnd);
8695
- const fetchData = useCallback(async () => {
8696
- if (!isAuthenticated)
8697
- return;
8698
- setIsLoading(true);
8699
- setError(null);
8700
- try {
8701
- const response = await getTradeHistory(apiBaseUrl, {
8702
- startDate: startIso,
8703
- endDate: endIso,
8704
- limit: totalDays * 50,
8705
- });
8706
- if (!mountedRef.current)
8707
- return;
8708
- setTrades(response.data);
8709
- }
8710
- catch (err) {
8711
- if (!mountedRef.current)
8712
- return;
8713
- setError(err instanceof Error ? err.message : 'Failed to fetch trade history');
8714
- setTrades(null);
8715
- }
8716
- finally {
8717
- if (mountedRef.current)
8718
- setIsLoading(false);
8719
- }
8720
- }, [apiBaseUrl, isAuthenticated, startIso, endIso, totalDays]);
8721
- useEffect(() => {
8722
- fetchData();
8723
- }, [fetchData]);
8724
- const result = useMemo(() => {
8725
- const empty = {
8726
- timeframe,
8727
- weeks: [],
8728
- months: [],
8729
- overall: EMPTY_SUMMARY,
8730
- isLoading: true,
8731
- };
8732
- if (!trades)
8733
- return empty;
8734
- if (totalDays <= 0)
8735
- return empty;
8736
- return buildCalendarData(trades, timeframe, rangeStart, rangeEnd, totalDays, useCustomDates);
8737
- }, [trades, timeframe, startIso, endIso]);
8738
- return { ...result, isLoading, error, refetch: fetchData };
8739
- }
8740
-
8741
8425
  const PearHyperliquidContext = createContext(undefined);
8742
8426
  /**
8743
8427
  * React Provider for PearHyperliquidClient
@@ -9089,4 +8773,4 @@ function getOrderTrailingInfo(order) {
9089
8773
  return undefined;
9090
8774
  }
9091
8775
 
9092
- 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, usePnlCalendar, usePortfolio, usePosition, useSpotOrder, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWatchlist, validateMaxAssetsPerLeg, validateMinimumAssetSize, validatePositionSize };
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 };
package/dist/types.d.ts CHANGED
@@ -314,6 +314,7 @@ 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';
317
318
  export type OrderDirection = 'MORE_THAN' | 'LESS_THAN';
318
319
  /**
319
320
  * Market order parameters
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pear-protocol/hyperliquid-sdk",
3
- "version": "0.1.19.2-pnl",
3
+ "version": "0.1.21.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",
@@ -1,7 +0,0 @@
1
- import type { ApiResponse, TradeHistoryDataDto } from '../types';
2
- export interface GetTradeHistoryParams {
3
- startDate?: string;
4
- endDate?: string;
5
- limit?: number;
6
- }
7
- export declare function getTradeHistory(baseUrl: string, params?: GetTradeHistoryParams): Promise<ApiResponse<TradeHistoryDataDto[]>>;
@@ -1,45 +0,0 @@
1
- export type PnlCalendarTimeframe = '2W' | '3W' | '2M' | '3M';
2
- export interface PnlCalendarOptions {
3
- timeframe?: PnlCalendarTimeframe;
4
- startDate?: Date | string;
5
- endDate?: Date | string;
6
- }
7
- export interface PnlCalendarDay {
8
- date: string;
9
- totalPnl: number;
10
- volume: number;
11
- positionsClosed: number;
12
- result: 'profit' | 'loss' | 'breakeven';
13
- tokens: string[];
14
- }
15
- export interface PeriodSummary {
16
- pnl: number;
17
- volume: number;
18
- winRate: number;
19
- wins: number;
20
- losses: number;
21
- totalProfit: number;
22
- totalLoss: number;
23
- }
24
- export interface PnlCalendarWeek {
25
- weekStart: string;
26
- weekEnd: string;
27
- days: PnlCalendarDay[];
28
- summary: PeriodSummary;
29
- }
30
- export interface PnlCalendarMonth {
31
- month: string;
32
- label: string;
33
- days: PnlCalendarDay[];
34
- summary: PeriodSummary;
35
- }
36
- export interface UsePnlCalendarResult {
37
- timeframe: PnlCalendarTimeframe;
38
- weeks: PnlCalendarWeek[];
39
- months: PnlCalendarMonth[];
40
- overall: PeriodSummary;
41
- isLoading: boolean;
42
- error: string | null;
43
- refetch: () => void;
44
- }
45
- export declare function usePnlCalendar(options?: PnlCalendarTimeframe | PnlCalendarOptions): UsePnlCalendarResult;