@pear-protocol/hyperliquid-sdk 0.1.22 → 0.1.24

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.
@@ -0,0 +1,7 @@
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[]>>;
@@ -18,3 +18,5 @@ export * from './usePortfolio';
18
18
  export * from './useAuth';
19
19
  export * from './useAllUserBalances';
20
20
  export * from './useHyperliquidUserFills';
21
+ export * from './usePnlCalendar';
22
+ export * from './usePnlHeatmap';
@@ -0,0 +1,61 @@
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 PnlCalendarAsset {
8
+ coin: string;
9
+ symbol: string;
10
+ assetName: string;
11
+ marketPrefix: string;
12
+ percentage: number;
13
+ collateralToken: string;
14
+ }
15
+ export interface PnlCalendarTrade {
16
+ tradeHistoryId: string;
17
+ realizedPnl: number;
18
+ result: 'profit' | 'loss' | 'breakeven';
19
+ collateralTypes: string[];
20
+ closedLongAssets: PnlCalendarAsset[];
21
+ closedShortAssets: PnlCalendarAsset[];
22
+ }
23
+ export interface PnlCalendarDay {
24
+ date: string;
25
+ totalPnl: number;
26
+ volume: number;
27
+ positionsClosed: number;
28
+ result: 'profit' | 'loss' | 'breakeven';
29
+ trades: PnlCalendarTrade[];
30
+ }
31
+ export interface PeriodSummary {
32
+ pnl: number;
33
+ volume: number;
34
+ winRate: number;
35
+ wins: number;
36
+ losses: number;
37
+ totalProfit: number;
38
+ totalLoss: number;
39
+ }
40
+ export interface PnlCalendarWeek {
41
+ weekStart: string;
42
+ weekEnd: string;
43
+ days: PnlCalendarDay[];
44
+ summary: PeriodSummary;
45
+ }
46
+ export interface PnlCalendarMonth {
47
+ month: string;
48
+ label: string;
49
+ days: PnlCalendarDay[];
50
+ summary: PeriodSummary;
51
+ }
52
+ export interface UsePnlCalendarResult {
53
+ timeframe: PnlCalendarTimeframe;
54
+ weeks: PnlCalendarWeek[];
55
+ months: PnlCalendarMonth[];
56
+ overall: PeriodSummary;
57
+ isLoading: boolean;
58
+ error: string | null;
59
+ refetch: () => void;
60
+ }
61
+ export declare function usePnlCalendar(options?: PnlCalendarTimeframe | PnlCalendarOptions): UsePnlCalendarResult;
@@ -0,0 +1,13 @@
1
+ import type { PnlCalendarTrade } from './usePnlCalendar';
2
+ export type PnlHeatmapTimeframe = 'allTime' | '100D' | '30D' | '7D';
3
+ export interface PnlHeatmapTrade extends PnlCalendarTrade {
4
+ percentage: number;
5
+ }
6
+ export interface UsePnlHeatmapResult {
7
+ timeframe: PnlHeatmapTimeframe;
8
+ trades: PnlHeatmapTrade[];
9
+ isLoading: boolean;
10
+ error: string | null;
11
+ refetch: () => void;
12
+ }
13
+ export declare function usePnlHeatmap(timeframe?: PnlHeatmapTimeframe): UsePnlHeatmapResult;
package/dist/index.d.ts CHANGED
@@ -1512,6 +1512,81 @@ interface UseHyperliquidUserFillsState {
1512
1512
  */
1513
1513
  declare function useHyperliquidUserFills(options: UseHyperliquidUserFillsOptions): UseHyperliquidUserFillsState;
1514
1514
 
1515
+ type PnlCalendarTimeframe = '2W' | '3W' | '2M' | '3M';
1516
+ interface PnlCalendarOptions {
1517
+ timeframe?: PnlCalendarTimeframe;
1518
+ startDate?: Date | string;
1519
+ endDate?: Date | string;
1520
+ }
1521
+ interface PnlCalendarAsset {
1522
+ coin: string;
1523
+ symbol: string;
1524
+ assetName: string;
1525
+ marketPrefix: string;
1526
+ percentage: number;
1527
+ collateralToken: string;
1528
+ }
1529
+ interface PnlCalendarTrade {
1530
+ tradeHistoryId: string;
1531
+ realizedPnl: number;
1532
+ result: 'profit' | 'loss' | 'breakeven';
1533
+ collateralTypes: string[];
1534
+ closedLongAssets: PnlCalendarAsset[];
1535
+ closedShortAssets: PnlCalendarAsset[];
1536
+ }
1537
+ interface PnlCalendarDay {
1538
+ date: string;
1539
+ totalPnl: number;
1540
+ volume: number;
1541
+ positionsClosed: number;
1542
+ result: 'profit' | 'loss' | 'breakeven';
1543
+ trades: PnlCalendarTrade[];
1544
+ }
1545
+ interface PeriodSummary {
1546
+ pnl: number;
1547
+ volume: number;
1548
+ winRate: number;
1549
+ wins: number;
1550
+ losses: number;
1551
+ totalProfit: number;
1552
+ totalLoss: number;
1553
+ }
1554
+ interface PnlCalendarWeek {
1555
+ weekStart: string;
1556
+ weekEnd: string;
1557
+ days: PnlCalendarDay[];
1558
+ summary: PeriodSummary;
1559
+ }
1560
+ interface PnlCalendarMonth {
1561
+ month: string;
1562
+ label: string;
1563
+ days: PnlCalendarDay[];
1564
+ summary: PeriodSummary;
1565
+ }
1566
+ interface UsePnlCalendarResult {
1567
+ timeframe: PnlCalendarTimeframe;
1568
+ weeks: PnlCalendarWeek[];
1569
+ months: PnlCalendarMonth[];
1570
+ overall: PeriodSummary;
1571
+ isLoading: boolean;
1572
+ error: string | null;
1573
+ refetch: () => void;
1574
+ }
1575
+ declare function usePnlCalendar(options?: PnlCalendarTimeframe | PnlCalendarOptions): UsePnlCalendarResult;
1576
+
1577
+ type PnlHeatmapTimeframe = 'allTime' | '100D' | '30D' | '7D';
1578
+ interface PnlHeatmapTrade extends PnlCalendarTrade {
1579
+ percentage: number;
1580
+ }
1581
+ interface UsePnlHeatmapResult {
1582
+ timeframe: PnlHeatmapTimeframe;
1583
+ trades: PnlHeatmapTrade[];
1584
+ isLoading: boolean;
1585
+ error: string | null;
1586
+ refetch: () => void;
1587
+ }
1588
+ declare function usePnlHeatmap(timeframe?: PnlHeatmapTimeframe): UsePnlHeatmapResult;
1589
+
1515
1590
  /**
1516
1591
  * Mark notifications as read up to a given timestamp (ms)
1517
1592
  */
@@ -1799,5 +1874,5 @@ interface MarketDataState {
1799
1874
  }
1800
1875
  declare const useMarketData: zustand.UseBoundStore<zustand.StoreApi<MarketDataState>>;
1801
1876
 
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 };
1877
+ 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, usePnlCalendar, usePnlHeatmap, usePortfolio, usePosition, useSpotOrder, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWatchlist, validateClosePositionRequest, validateMaxAssetsPerLeg, validateMinimumAssetSize, validatePositionSize };
1878
+ 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, PeriodSummary, PerpDex, PerpDexsResponse, PerpMetaAsset, PlatformAccountSummaryResponseDto, PnlCalendarAsset, PnlCalendarDay, PnlCalendarMonth, PnlCalendarOptions, PnlCalendarTimeframe, PnlCalendarTrade, PnlCalendarWeek, PnlHeatmapTimeframe, PnlHeatmapTrade, 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, UsePnlHeatmapResult, UsePortfolioResult, UseSpotOrderResult, UseTokenSelectionMetadataReturn, UserAbstraction, UserProfile, UserSelectionState, WatchlistAssetDto, WatchlistItemDto, WebData3AssetCtx, WebData3PerpDexState, WebData3Response, WebData3UserState, WebSocketAckResponse, WebSocketChannel, WebSocketConnectionState, WebSocketDataMessage, WebSocketMessage, WebSocketSubscribeMessage, WsAllMidsData };
package/dist/index.js CHANGED
@@ -820,17 +820,8 @@ function validateClosePositionRequest(payload) {
820
820
  }
821
821
 
822
822
  const DEFAULT_STATE = {
823
- longTokens: [
824
- { symbol: "HYPE", weight: 25 },
825
- { symbol: "BTC", weight: 25 },
826
- ],
827
- shortTokens: [
828
- { symbol: "AVAX", weight: 10 },
829
- { symbol: "SEI", weight: 10 },
830
- { symbol: "ADA", weight: 10 },
831
- { symbol: "TRUMP", weight: 10 },
832
- { symbol: "SUI", weight: 10 },
833
- ],
823
+ longTokens: [],
824
+ shortTokens: [],
834
825
  openTokenSelector: false,
835
826
  selectorConfig: null,
836
827
  openConflictModal: false,
@@ -8474,6 +8465,456 @@ function useHyperliquidUserFills(options) {
8474
8465
  };
8475
8466
  }
8476
8467
 
8468
+ async function getTradeHistory(baseUrl, params) {
8469
+ const url = joinUrl(baseUrl, '/trade-history');
8470
+ try {
8471
+ const resp = await apiClient.get(url, {
8472
+ params,
8473
+ timeout: 60000,
8474
+ });
8475
+ return { data: resp.data, status: resp.status, headers: resp.headers };
8476
+ }
8477
+ catch (error) {
8478
+ throw toApiError(error);
8479
+ }
8480
+ }
8481
+
8482
+ // ─── helpers ────────────────────────────────────────────────────
8483
+ const EMPTY_SUMMARY = {
8484
+ pnl: 0,
8485
+ volume: 0,
8486
+ winRate: 0,
8487
+ wins: 0,
8488
+ losses: 0,
8489
+ totalProfit: 0,
8490
+ totalLoss: 0,
8491
+ };
8492
+ const getTimeframeDays$1 = (tf) => {
8493
+ switch (tf) {
8494
+ case '2W':
8495
+ return 14;
8496
+ case '3W':
8497
+ return 21;
8498
+ case '2M':
8499
+ return 60;
8500
+ case '3M':
8501
+ return 90;
8502
+ }
8503
+ };
8504
+ const isWeekTimeframe = (tf) => tf === '2W' || tf === '3W';
8505
+ const toDateKey = (date) => {
8506
+ const y = date.getFullYear();
8507
+ const m = String(date.getMonth() + 1).padStart(2, '0');
8508
+ const d = String(date.getDate()).padStart(2, '0');
8509
+ return `${y}-${m}-${d}`;
8510
+ };
8511
+ const toMonthKey = (date) => {
8512
+ const y = date.getFullYear();
8513
+ const m = String(date.getMonth() + 1).padStart(2, '0');
8514
+ return `${y}-${m}`;
8515
+ };
8516
+ const formatMonthLabel = (date) => date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
8517
+ const getMonday = (date) => {
8518
+ const d = new Date(date);
8519
+ const day = d.getDay(); // 0=Sun … 6=Sat
8520
+ const diff = day === 0 ? -6 : 1 - day;
8521
+ d.setDate(d.getDate() + diff);
8522
+ d.setHours(0, 0, 0, 0);
8523
+ return d;
8524
+ };
8525
+ const toLocalMidnight = (input) => {
8526
+ const d = typeof input === 'string' ? new Date(input + 'T00:00:00') : new Date(input);
8527
+ d.setHours(0, 0, 0, 0);
8528
+ return d;
8529
+ };
8530
+ const diffDays = (start, end) => {
8531
+ return Math.round((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
8532
+ };
8533
+ const toISODateString$1 = (input) => {
8534
+ const d = typeof input === 'string' ? new Date(input + 'T00:00:00') : new Date(input);
8535
+ return d.toISOString();
8536
+ };
8537
+ const round2 = (n) => Math.round(n * 100) / 100;
8538
+ const mapAsset$1 = (asset, getAssetByName) => {
8539
+ var _a, _b, _c, _d;
8540
+ const metadata = getAssetByName(asset.coin);
8541
+ const marketInfo = getMarketInfoFromSymbol(asset.coin);
8542
+ return {
8543
+ coin: asset.coin,
8544
+ symbol: (_a = metadata === null || metadata === void 0 ? void 0 : metadata.symbolName) !== null && _a !== void 0 ? _a : marketInfo.symbolName,
8545
+ assetName: (_b = metadata === null || metadata === void 0 ? void 0 : metadata.assetName) !== null && _b !== void 0 ? _b : asset.coin,
8546
+ marketPrefix: (_c = metadata === null || metadata === void 0 ? void 0 : metadata.marketName) !== null && _c !== void 0 ? _c : marketInfo.marketName,
8547
+ percentage: asset.closeWeight * 100,
8548
+ collateralToken: (_d = metadata === null || metadata === void 0 ? void 0 : metadata.collateralToken) !== null && _d !== void 0 ? _d : 'USDC',
8549
+ };
8550
+ };
8551
+ const getCollateralTypes$1 = (assets) => {
8552
+ const set = new Set();
8553
+ for (const a of assets)
8554
+ set.add(a.collateralToken);
8555
+ return set.size > 0 ? Array.from(set) : ['USDC'];
8556
+ };
8557
+ const buildSummary = (days) => {
8558
+ let pnl = 0;
8559
+ let volume = 0;
8560
+ let wins = 0;
8561
+ let losses = 0;
8562
+ let totalProfit = 0;
8563
+ let totalLoss = 0;
8564
+ for (const day of days) {
8565
+ pnl += day.totalPnl;
8566
+ volume += day.volume;
8567
+ if (day.positionsClosed === 0)
8568
+ continue;
8569
+ if (day.totalPnl > 0) {
8570
+ wins++;
8571
+ totalProfit += day.totalPnl;
8572
+ }
8573
+ else if (day.totalPnl < 0) {
8574
+ losses++;
8575
+ totalLoss += Math.abs(day.totalPnl);
8576
+ }
8577
+ }
8578
+ const total = wins + losses;
8579
+ const winRate = total > 0 ? Math.round((wins / total) * 100) : 0;
8580
+ return {
8581
+ pnl: round2(pnl),
8582
+ volume: round2(volume),
8583
+ winRate,
8584
+ wins,
8585
+ losses,
8586
+ totalProfit: round2(totalProfit),
8587
+ totalLoss: round2(totalLoss),
8588
+ };
8589
+ };
8590
+ const buildCalendarData = (tradeHistories, timeframe, rangeStart, rangeEnd, totalDays, useCustomDates, getAssetByName) => {
8591
+ const startKey = toDateKey(rangeStart);
8592
+ const endKey = toDateKey(rangeEnd);
8593
+ // Build day buckets for the full range
8594
+ const buckets = new Map();
8595
+ for (let i = 0; i < totalDays; i++) {
8596
+ const d = new Date(rangeStart);
8597
+ d.setDate(rangeStart.getDate() + i);
8598
+ buckets.set(toDateKey(d), {
8599
+ pnl: 0,
8600
+ volume: 0,
8601
+ positionsClosed: 0,
8602
+ trades: [],
8603
+ });
8604
+ }
8605
+ // Populate buckets from trade histories
8606
+ for (const trade of tradeHistories) {
8607
+ if (!trade.createdAt)
8608
+ continue;
8609
+ const date = new Date(trade.createdAt);
8610
+ if (isNaN(date.getTime()))
8611
+ continue;
8612
+ const dateKey = toDateKey(date);
8613
+ if (dateKey < startKey || dateKey > endKey)
8614
+ continue;
8615
+ const bucket = buckets.get(dateKey);
8616
+ if (!bucket)
8617
+ continue;
8618
+ const pnl = trade.realizedPnl;
8619
+ bucket.pnl += isFinite(pnl) ? pnl : 0;
8620
+ const vol = trade.totalValue;
8621
+ bucket.volume += isFinite(vol) ? vol : 0;
8622
+ bucket.positionsClosed += 1;
8623
+ const tradePnl = trade.realizedPnl;
8624
+ const longAssets = trade.closedLongAssets.map((a) => mapAsset$1(a, getAssetByName));
8625
+ const shortAssets = trade.closedShortAssets.map((a) => mapAsset$1(a, getAssetByName));
8626
+ bucket.trades.push({
8627
+ tradeHistoryId: trade.tradeHistoryId,
8628
+ realizedPnl: tradePnl,
8629
+ result: tradePnl > 0 ? 'profit' : tradePnl < 0 ? 'loss' : 'breakeven',
8630
+ collateralTypes: getCollateralTypes$1([...longAssets, ...shortAssets]),
8631
+ closedLongAssets: longAssets,
8632
+ closedShortAssets: shortAssets,
8633
+ });
8634
+ }
8635
+ // Build day objects
8636
+ const allDays = [];
8637
+ const sortedKeys = Array.from(buckets.keys()).sort();
8638
+ for (const key of sortedKeys) {
8639
+ const bucket = buckets.get(key);
8640
+ const roundedPnl = round2(bucket.pnl);
8641
+ const result = roundedPnl > 0 ? 'profit' : roundedPnl < 0 ? 'loss' : 'breakeven';
8642
+ allDays.push({
8643
+ date: key,
8644
+ totalPnl: roundedPnl,
8645
+ volume: round2(bucket.volume),
8646
+ positionsClosed: bucket.positionsClosed,
8647
+ result,
8648
+ trades: bucket.trades,
8649
+ });
8650
+ }
8651
+ // Group into periods
8652
+ let weeks = [];
8653
+ let months = [];
8654
+ const useWeekGrouping = useCustomDates
8655
+ ? totalDays <= 28
8656
+ : isWeekTimeframe(timeframe);
8657
+ if (useWeekGrouping) {
8658
+ const weekMap = new Map();
8659
+ for (const day of allDays) {
8660
+ const date = new Date(day.date + 'T00:00:00');
8661
+ const monday = getMonday(date);
8662
+ const mondayKey = toDateKey(monday);
8663
+ if (!weekMap.has(mondayKey)) {
8664
+ weekMap.set(mondayKey, []);
8665
+ }
8666
+ weekMap.get(mondayKey).push(day);
8667
+ }
8668
+ const sortedWeekKeys = Array.from(weekMap.keys()).sort();
8669
+ weeks = sortedWeekKeys.map((mondayKey) => {
8670
+ const days = weekMap.get(mondayKey);
8671
+ const monday = new Date(mondayKey + 'T00:00:00');
8672
+ const sunday = new Date(monday);
8673
+ sunday.setDate(monday.getDate() + 6);
8674
+ return {
8675
+ weekStart: mondayKey,
8676
+ weekEnd: toDateKey(sunday),
8677
+ days,
8678
+ summary: buildSummary(days),
8679
+ };
8680
+ });
8681
+ }
8682
+ else {
8683
+ const monthMap = new Map();
8684
+ for (const day of allDays) {
8685
+ const date = new Date(day.date + 'T00:00:00');
8686
+ const mk = toMonthKey(date);
8687
+ if (!monthMap.has(mk)) {
8688
+ monthMap.set(mk, { days: [], label: formatMonthLabel(date) });
8689
+ }
8690
+ monthMap.get(mk).days.push(day);
8691
+ }
8692
+ const sortedMonthKeys = Array.from(monthMap.keys()).sort();
8693
+ months = sortedMonthKeys.map((mk) => {
8694
+ const { days, label } = monthMap.get(mk);
8695
+ return {
8696
+ month: mk,
8697
+ label,
8698
+ days,
8699
+ summary: buildSummary(days),
8700
+ };
8701
+ });
8702
+ }
8703
+ return {
8704
+ timeframe,
8705
+ weeks,
8706
+ months,
8707
+ overall: buildSummary(allDays),
8708
+ isLoading: false,
8709
+ };
8710
+ };
8711
+ // ─── hook ───────────────────────────────────────────────────────
8712
+ function usePnlCalendar(options) {
8713
+ var _a;
8714
+ const opts = typeof options === 'string'
8715
+ ? { timeframe: options }
8716
+ : options !== null && options !== void 0 ? options : {};
8717
+ const timeframe = (_a = opts.timeframe) !== null && _a !== void 0 ? _a : '2W';
8718
+ const customStart = opts.startDate;
8719
+ const customEnd = opts.endDate;
8720
+ const context = useContext(PearHyperliquidContext);
8721
+ if (!context) {
8722
+ throw new Error('usePnlCalendar must be used within a PearHyperliquidProvider');
8723
+ }
8724
+ const { apiBaseUrl } = context;
8725
+ const isAuthenticated = useUserData((state) => state.isAuthenticated);
8726
+ const { getAssetByName } = useMarket();
8727
+ const [trades, setTrades] = useState(null);
8728
+ const [isLoading, setIsLoading] = useState(false);
8729
+ const [error, setError] = useState(null);
8730
+ const mountedRef = useRef(true);
8731
+ useEffect(() => {
8732
+ mountedRef.current = true;
8733
+ return () => { mountedRef.current = false; };
8734
+ }, []);
8735
+ // Compute the date range
8736
+ const useCustomDates = !!(customStart && customEnd);
8737
+ let rangeStart;
8738
+ let rangeEnd;
8739
+ let totalDays;
8740
+ if (useCustomDates) {
8741
+ rangeStart = toLocalMidnight(customStart);
8742
+ rangeEnd = toLocalMidnight(customEnd);
8743
+ totalDays = diffDays(rangeStart, rangeEnd);
8744
+ }
8745
+ else {
8746
+ totalDays = getTimeframeDays$1(timeframe);
8747
+ rangeEnd = new Date();
8748
+ rangeEnd.setHours(0, 0, 0, 0);
8749
+ rangeStart = new Date(rangeEnd);
8750
+ rangeStart.setDate(rangeEnd.getDate() - totalDays + 1);
8751
+ }
8752
+ const startIso = toISODateString$1(rangeStart);
8753
+ const endIso = toISODateString$1(rangeEnd);
8754
+ const fetchData = useCallback(async () => {
8755
+ if (!isAuthenticated)
8756
+ return;
8757
+ setIsLoading(true);
8758
+ setError(null);
8759
+ try {
8760
+ const response = await getTradeHistory(apiBaseUrl, {
8761
+ startDate: startIso,
8762
+ endDate: endIso,
8763
+ limit: totalDays * 50,
8764
+ });
8765
+ if (!mountedRef.current)
8766
+ return;
8767
+ setTrades(response.data);
8768
+ }
8769
+ catch (err) {
8770
+ if (!mountedRef.current)
8771
+ return;
8772
+ setError(err instanceof Error ? err.message : 'Failed to fetch trade history');
8773
+ setTrades(null);
8774
+ }
8775
+ finally {
8776
+ if (mountedRef.current)
8777
+ setIsLoading(false);
8778
+ }
8779
+ }, [apiBaseUrl, isAuthenticated, startIso, endIso, totalDays]);
8780
+ useEffect(() => {
8781
+ fetchData();
8782
+ }, [fetchData]);
8783
+ const result = useMemo(() => {
8784
+ const empty = {
8785
+ timeframe,
8786
+ weeks: [],
8787
+ months: [],
8788
+ overall: EMPTY_SUMMARY,
8789
+ isLoading: true,
8790
+ };
8791
+ if (!trades)
8792
+ return empty;
8793
+ if (totalDays <= 0)
8794
+ return empty;
8795
+ return buildCalendarData(trades, timeframe, rangeStart, rangeEnd, totalDays, useCustomDates, getAssetByName);
8796
+ }, [trades, timeframe, startIso, endIso, getAssetByName]);
8797
+ return { ...result, isLoading, error, refetch: fetchData };
8798
+ }
8799
+
8800
+ const HEATMAP_LIMIT = 50;
8801
+ // ─── helpers ────────────────────────────────────────────────────
8802
+ const getTimeframeDays = (tf) => {
8803
+ switch (tf) {
8804
+ case '7D':
8805
+ return 7;
8806
+ case '30D':
8807
+ return 30;
8808
+ case '100D':
8809
+ return 100;
8810
+ case 'allTime':
8811
+ return null;
8812
+ }
8813
+ };
8814
+ const toISODateString = (date) => date.toISOString();
8815
+ const mapAsset = (asset, getAssetByName) => {
8816
+ var _a, _b, _c, _d;
8817
+ const metadata = getAssetByName(asset.coin);
8818
+ const marketInfo = getMarketInfoFromSymbol(asset.coin);
8819
+ return {
8820
+ coin: asset.coin,
8821
+ symbol: (_a = metadata === null || metadata === void 0 ? void 0 : metadata.symbolName) !== null && _a !== void 0 ? _a : marketInfo.symbolName,
8822
+ assetName: (_b = metadata === null || metadata === void 0 ? void 0 : metadata.assetName) !== null && _b !== void 0 ? _b : asset.coin,
8823
+ marketPrefix: (_c = metadata === null || metadata === void 0 ? void 0 : metadata.marketName) !== null && _c !== void 0 ? _c : marketInfo.marketName,
8824
+ percentage: asset.closeWeight * 100,
8825
+ collateralToken: (_d = metadata === null || metadata === void 0 ? void 0 : metadata.collateralToken) !== null && _d !== void 0 ? _d : 'USDC',
8826
+ };
8827
+ };
8828
+ const getCollateralTypes = (assets) => {
8829
+ const set = new Set();
8830
+ for (const a of assets)
8831
+ set.add(a.collateralToken);
8832
+ return set.size > 0 ? Array.from(set) : ['USDC'];
8833
+ };
8834
+ const toCalendarTrade = (trade, getAssetByName) => {
8835
+ const pnl = trade.realizedPnl;
8836
+ const longAssets = trade.closedLongAssets.map((a) => mapAsset(a, getAssetByName));
8837
+ const shortAssets = trade.closedShortAssets.map((a) => mapAsset(a, getAssetByName));
8838
+ return {
8839
+ tradeHistoryId: trade.tradeHistoryId,
8840
+ realizedPnl: pnl,
8841
+ result: pnl > 0 ? 'profit' : pnl < 0 ? 'loss' : 'breakeven',
8842
+ collateralTypes: getCollateralTypes([...longAssets, ...shortAssets]),
8843
+ closedLongAssets: longAssets,
8844
+ closedShortAssets: shortAssets,
8845
+ };
8846
+ };
8847
+ // ─── hook ───────────────────────────────────────────────────────
8848
+ function usePnlHeatmap(timeframe = 'allTime') {
8849
+ const context = useContext(PearHyperliquidContext);
8850
+ if (!context) {
8851
+ throw new Error('usePnlHeatmap must be used within a PearHyperliquidProvider');
8852
+ }
8853
+ const { apiBaseUrl } = context;
8854
+ const isAuthenticated = useUserData((state) => state.isAuthenticated);
8855
+ const { getAssetByName } = useMarket();
8856
+ const [trades, setTrades] = useState(null);
8857
+ const [isLoading, setIsLoading] = useState(false);
8858
+ const [error, setError] = useState(null);
8859
+ const mountedRef = useRef(true);
8860
+ useEffect(() => {
8861
+ mountedRef.current = true;
8862
+ return () => { mountedRef.current = false; };
8863
+ }, []);
8864
+ const days = getTimeframeDays(timeframe);
8865
+ let startIso;
8866
+ if (days !== null) {
8867
+ const start = new Date();
8868
+ start.setHours(0, 0, 0, 0);
8869
+ start.setDate(start.getDate() - days);
8870
+ startIso = toISODateString(start);
8871
+ }
8872
+ const fetchData = useCallback(async () => {
8873
+ if (!isAuthenticated)
8874
+ return;
8875
+ setIsLoading(true);
8876
+ setError(null);
8877
+ try {
8878
+ const response = await getTradeHistory(apiBaseUrl, {
8879
+ ...(startIso ? { startDate: startIso } : {}),
8880
+ limit: 5000,
8881
+ });
8882
+ if (!mountedRef.current)
8883
+ return;
8884
+ setTrades(response.data);
8885
+ }
8886
+ catch (err) {
8887
+ if (!mountedRef.current)
8888
+ return;
8889
+ setError(err instanceof Error ? err.message : 'Failed to fetch trade history');
8890
+ setTrades(null);
8891
+ }
8892
+ finally {
8893
+ if (mountedRef.current)
8894
+ setIsLoading(false);
8895
+ }
8896
+ }, [apiBaseUrl, isAuthenticated, startIso]);
8897
+ useEffect(() => {
8898
+ fetchData();
8899
+ }, [fetchData]);
8900
+ const result = useMemo(() => {
8901
+ if (!trades)
8902
+ return [];
8903
+ const top = trades
8904
+ .slice()
8905
+ .sort((a, b) => Math.abs(b.realizedPnl) - Math.abs(a.realizedPnl))
8906
+ .slice(0, HEATMAP_LIMIT);
8907
+ const totalAbsPnl = top.reduce((sum, t) => sum + Math.abs(t.realizedPnl), 0);
8908
+ return top.map((t) => ({
8909
+ ...toCalendarTrade(t, getAssetByName),
8910
+ percentage: totalAbsPnl > 0
8911
+ ? Math.round((Math.abs(t.realizedPnl) / totalAbsPnl) * 10000) / 100
8912
+ : 0,
8913
+ }));
8914
+ }, [trades, getAssetByName]);
8915
+ return { timeframe, trades: result, isLoading, error, refetch: fetchData };
8916
+ }
8917
+
8477
8918
  const PearHyperliquidContext = createContext(undefined);
8478
8919
  /**
8479
8920
  * React Provider for PearHyperliquidClient
@@ -8825,4 +9266,4 @@ function getOrderTrailingInfo(order) {
8825
9266
  return undefined;
8826
9267
  }
8827
9268
 
8828
- 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 };
9269
+ 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, usePnlCalendar, usePnlHeatmap, usePortfolio, usePosition, useSpotOrder, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWatchlist, validateClosePositionRequest, validateMaxAssetsPerLeg, validateMinimumAssetSize, validatePositionSize };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pear-protocol/hyperliquid-sdk",
3
- "version": "0.1.22",
3
+ "version": "0.1.24",
4
4
  "description": "React SDK for Pear Protocol Hyperliquid API integration",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",