@pear-protocol/hyperliquid-sdk 0.1.31 → 0.1.32
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/dist/index.d.ts +7 -1
- package/dist/index.js +94 -117
- package/dist/types.d.ts +1 -0
- package/dist/utils/symbol-aliases.d.ts +4 -0
- package/package.json +1 -1
- package/dist/utils/quote-assets.d.ts +0 -6
package/dist/index.d.ts
CHANGED
|
@@ -812,6 +812,7 @@ interface ActiveAssetData {
|
|
|
812
812
|
interface TokenMetadata {
|
|
813
813
|
assetName: string;
|
|
814
814
|
symbolName: string;
|
|
815
|
+
displayName: string;
|
|
815
816
|
marketName: string;
|
|
816
817
|
isAtOiCaps: boolean;
|
|
817
818
|
currentPrice: number;
|
|
@@ -1877,6 +1878,11 @@ declare function getOrderTrailingInfo(order: OpenLimitOrderDto): {
|
|
|
1877
1878
|
trailingActivationValue?: number;
|
|
1878
1879
|
} | undefined;
|
|
1879
1880
|
|
|
1881
|
+
declare const SYMBOL_DISPLAY_ALIASES: Record<string, string>;
|
|
1882
|
+
declare function toDisplaySymbol(symbol: string, market?: string): string;
|
|
1883
|
+
declare function toHlSymbol(displayOrSymbol: string, market?: string): string;
|
|
1884
|
+
declare function matchesSymbolOrAlias(symbol: string, term: string, market?: string): boolean;
|
|
1885
|
+
|
|
1880
1886
|
interface MarketDataState {
|
|
1881
1887
|
marketData: ActiveAssetsResponse | null;
|
|
1882
1888
|
setMarketData: (value: ActiveAssetsResponse | null) => void;
|
|
@@ -1884,5 +1890,5 @@ interface MarketDataState {
|
|
|
1884
1890
|
}
|
|
1885
1891
|
declare const useMarketData: zustand.UseBoundStore<zustand.StoreApi<MarketDataState>>;
|
|
1886
1892
|
|
|
1887
|
-
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 };
|
|
1893
|
+
export { ClosePositionValidationError, ConflictDetector, MAX_ASSETS_PER_LEG, MINIMUM_ASSET_USD_VALUE, MaxAssetsPerLegError, MinimumPositionSizeError, PearHyperliquidProvider, ReadyState, SYMBOL_DISPLAY_ALIASES, 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, matchesSymbolOrAlias, toDisplaySymbol, toHlSymbol, 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 };
|
|
1888
1894
|
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, EIP712AuthDetailsRequest, ExecutionType, ExternalFillDto, ExternalLiquidationDto, ExtraAgent, GetAgentWalletResponseDto, GetEIP712MessageRequest, 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
|
@@ -334,6 +334,53 @@ const getMarketInfoFromSymbol = (symbol) => {
|
|
|
334
334
|
return { symbolName: symbol, marketName: '' };
|
|
335
335
|
};
|
|
336
336
|
|
|
337
|
+
// Display-only aliases for HL symbols. Keys are HL canonical full names —
|
|
338
|
+
// `<symbol>` for plain HL perps and `<market>:<symbol>` for HIP-3 markets.
|
|
339
|
+
// The value is the display symbol only (no prefix; the market tag is rendered
|
|
340
|
+
// separately by the UI). Aliases are scoped: `'xyz:TSLA': 'FOO'` will not
|
|
341
|
+
// affect a hypothetical `flx:TSLA`.
|
|
342
|
+
//
|
|
343
|
+
// Use these helpers only at display/URL boundaries — API/asset-index work
|
|
344
|
+
// must keep using the canonical symbol.
|
|
345
|
+
const SYMBOL_DISPLAY_ALIASES = {
|
|
346
|
+
CL: 'WTIOIL',
|
|
347
|
+
};
|
|
348
|
+
const REVERSE_ALIASES = Object.entries(SYMBOL_DISPLAY_ALIASES).reduce((acc, [hlFullName, displaySymbol]) => {
|
|
349
|
+
const market = hlFullName.includes(':')
|
|
350
|
+
? hlFullName.split(':')[0]
|
|
351
|
+
: '';
|
|
352
|
+
const reverseKey = market
|
|
353
|
+
? `${market}:${displaySymbol.toUpperCase()}`
|
|
354
|
+
: displaySymbol.toUpperCase();
|
|
355
|
+
acc[reverseKey] = hlFullName;
|
|
356
|
+
return acc;
|
|
357
|
+
}, {});
|
|
358
|
+
function aliasKey(symbol, market) {
|
|
359
|
+
return market ? `${market}:${symbol}` : symbol;
|
|
360
|
+
}
|
|
361
|
+
function toDisplaySymbol(symbol, market = '') {
|
|
362
|
+
var _a;
|
|
363
|
+
return (_a = SYMBOL_DISPLAY_ALIASES[aliasKey(symbol, market)]) !== null && _a !== void 0 ? _a : symbol;
|
|
364
|
+
}
|
|
365
|
+
// Reverse lookup. Returns the HL canonical symbol (without prefix); callers
|
|
366
|
+
// already know the market from context.
|
|
367
|
+
function toHlSymbol(displayOrSymbol, market = '') {
|
|
368
|
+
const key = aliasKey(displayOrSymbol.toUpperCase(), market);
|
|
369
|
+
const fullCanonical = REVERSE_ALIASES[key];
|
|
370
|
+
if (!fullCanonical)
|
|
371
|
+
return displayOrSymbol;
|
|
372
|
+
return fullCanonical.includes(':')
|
|
373
|
+
? fullCanonical.split(':').slice(1).join(':')
|
|
374
|
+
: fullCanonical;
|
|
375
|
+
}
|
|
376
|
+
function matchesSymbolOrAlias(symbol, term, market = '') {
|
|
377
|
+
if (!term)
|
|
378
|
+
return true;
|
|
379
|
+
const lowerTerm = term.toLowerCase();
|
|
380
|
+
return (symbol.toLowerCase().includes(lowerTerm) ||
|
|
381
|
+
toDisplaySymbol(symbol, market).toLowerCase().includes(lowerTerm));
|
|
382
|
+
}
|
|
383
|
+
|
|
337
384
|
/**
|
|
338
385
|
* Check if two symbols match, handling kPEPE/KPEPE variations
|
|
339
386
|
* Returns true if symbols match (case-insensitive for k-prefix tokens)
|
|
@@ -425,6 +472,7 @@ class TokenMetadataExtractor {
|
|
|
425
472
|
return {
|
|
426
473
|
assetName: foundAsset.name,
|
|
427
474
|
symbolName,
|
|
475
|
+
displayName: toDisplaySymbol(symbolName, marketName),
|
|
428
476
|
marketName,
|
|
429
477
|
isAtOiCaps: finalAtOICaps ? finalAtOICaps.includes(symbol) : false,
|
|
430
478
|
currentPrice,
|
|
@@ -456,6 +504,7 @@ const applyMetadataContext = (symbol, metadata, oiCapSet) => {
|
|
|
456
504
|
return {
|
|
457
505
|
...metadata,
|
|
458
506
|
symbolName,
|
|
507
|
+
displayName: toDisplaySymbol(symbolName, marketName),
|
|
459
508
|
marketName,
|
|
460
509
|
isAtOiCaps: isAtOiCaps(symbol, oiCapSet),
|
|
461
510
|
};
|
|
@@ -972,23 +1021,6 @@ const useUserSelection$1 = create((set, get) => ({
|
|
|
972
1021
|
resetToDefaults: () => set((prev) => ({ ...prev, ...DEFAULT_STATE })),
|
|
973
1022
|
}));
|
|
974
1023
|
|
|
975
|
-
const STABLE_QUOTE_SYMBOLS = new Set([
|
|
976
|
-
'USDC',
|
|
977
|
-
'USDH',
|
|
978
|
-
'USDE',
|
|
979
|
-
'USDT',
|
|
980
|
-
'USDT0',
|
|
981
|
-
]);
|
|
982
|
-
const isStableQuoteSymbol = (symbol) => STABLE_QUOTE_SYMBOLS.has(symbol.toUpperCase());
|
|
983
|
-
const hasNonStableTokens = (tokens) => tokens.some((token) => !isStableQuoteSymbol(token.symbol));
|
|
984
|
-
const isStableOnlySide = (tokens) => tokens.length === 0 || tokens.every((token) => isStableQuoteSymbol(token.symbol));
|
|
985
|
-
const isSingleAssetSideAgainstStableQuote = (longTokens, shortTokens) => {
|
|
986
|
-
const longHasNonStable = hasNonStableTokens(longTokens);
|
|
987
|
-
const shortHasNonStable = hasNonStableTokens(shortTokens);
|
|
988
|
-
return ((longHasNonStable && isStableOnlySide(shortTokens)) ||
|
|
989
|
-
(shortHasNonStable && isStableOnlySide(longTokens)));
|
|
990
|
-
};
|
|
991
|
-
|
|
992
1024
|
const CANDLE_STALE_WARNING_MS = 90000;
|
|
993
1025
|
const getCandleSubscriptionKey = (coin, interval) => `${coin}:${interval}`;
|
|
994
1026
|
const debugHyperliquidWs = (message, payload) => {
|
|
@@ -1010,9 +1042,7 @@ const useHyperliquidNativeWebSocket = ({ address, enabled = true, onUserFills, }
|
|
|
1010
1042
|
const userSummary = useUserData((state) => state.accountSummary);
|
|
1011
1043
|
const longTokens = useUserSelection$1((s) => s.longTokens);
|
|
1012
1044
|
const shortTokens = useUserSelection$1((s) => s.shortTokens);
|
|
1013
|
-
const selectedTokenSymbols = useMemo(() => [...longTokens, ...shortTokens]
|
|
1014
|
-
.map((t) => t.symbol)
|
|
1015
|
-
.filter((symbol) => !isStableQuoteSymbol(symbol)), [longTokens, shortTokens]);
|
|
1045
|
+
const selectedTokenSymbols = useMemo(() => [...longTokens, ...shortTokens].map((t) => t.symbol), [longTokens, shortTokens]);
|
|
1016
1046
|
const [lastError, setLastError] = useState(null);
|
|
1017
1047
|
const [subscribedAddress, setSubscribedAddress] = useState(null);
|
|
1018
1048
|
const [subscribedTokens, setSubscribedTokens] = useState([]);
|
|
@@ -1923,7 +1953,7 @@ const useTokenSelectionMetadataStore = create((set) => ({
|
|
|
1923
1953
|
...longTokensMetadata,
|
|
1924
1954
|
...shortTokensMetadata,
|
|
1925
1955
|
};
|
|
1926
|
-
return allTokens.some((token) => !
|
|
1956
|
+
return allTokens.some((token) => !allMetadata[token.symbol]);
|
|
1927
1957
|
})();
|
|
1928
1958
|
// Open interest and volume (from market data for matching asset basket)
|
|
1929
1959
|
const { openInterest, volume } = (() => {
|
|
@@ -1946,15 +1976,9 @@ const useTokenSelectionMetadataStore = create((set) => ({
|
|
|
1946
1976
|
? { openInterest: match.openInterest, volume: match.volume }
|
|
1947
1977
|
: empty;
|
|
1948
1978
|
})();
|
|
1949
|
-
const getPrice = (metadata, symbol, field) => {
|
|
1950
|
-
var _a;
|
|
1951
|
-
if (isStableQuoteSymbol(symbol))
|
|
1952
|
-
return 1;
|
|
1953
|
-
return (_a = metadata === null || metadata === void 0 ? void 0 : metadata[field]) !== null && _a !== void 0 ? _a : 0;
|
|
1954
|
-
};
|
|
1955
|
-
const shouldUseAbsoluteQuoteRatio = isSingleAssetSideAgainstStableQuote(longTokens, shortTokens);
|
|
1956
1979
|
// Price ratio (only when exactly one long and one short)
|
|
1957
1980
|
const { priceRatio, priceRatio24h } = (() => {
|
|
1981
|
+
var _a, _b, _c, _d;
|
|
1958
1982
|
if (longTokens.length !== 1 || shortTokens.length !== 1) {
|
|
1959
1983
|
return { priceRatio: 1, priceRatio24h: 1 };
|
|
1960
1984
|
}
|
|
@@ -1962,22 +1986,10 @@ const useTokenSelectionMetadataStore = create((set) => ({
|
|
|
1962
1986
|
const shortSymbol = shortTokens[0].symbol;
|
|
1963
1987
|
const longMeta = longTokensMetadata[longSymbol];
|
|
1964
1988
|
const shortMeta = shortTokensMetadata[shortSymbol];
|
|
1965
|
-
const currentLong =
|
|
1966
|
-
const currentShort =
|
|
1967
|
-
const prevLong =
|
|
1968
|
-
const prevShort =
|
|
1969
|
-
if (isStableQuoteSymbol(longSymbol) && !isStableQuoteSymbol(shortSymbol)) {
|
|
1970
|
-
return {
|
|
1971
|
-
priceRatio: currentShort || 1,
|
|
1972
|
-
priceRatio24h: prevShort || 1,
|
|
1973
|
-
};
|
|
1974
|
-
}
|
|
1975
|
-
if (isStableQuoteSymbol(shortSymbol) && !isStableQuoteSymbol(longSymbol)) {
|
|
1976
|
-
return {
|
|
1977
|
-
priceRatio: currentLong || 1,
|
|
1978
|
-
priceRatio24h: prevLong || 1,
|
|
1979
|
-
};
|
|
1980
|
-
}
|
|
1989
|
+
const currentLong = (_a = longMeta === null || longMeta === void 0 ? void 0 : longMeta.currentPrice) !== null && _a !== void 0 ? _a : 0;
|
|
1990
|
+
const currentShort = (_b = shortMeta === null || shortMeta === void 0 ? void 0 : shortMeta.currentPrice) !== null && _b !== void 0 ? _b : 0;
|
|
1991
|
+
const prevLong = (_c = longMeta === null || longMeta === void 0 ? void 0 : longMeta.prevDayPrice) !== null && _c !== void 0 ? _c : 0;
|
|
1992
|
+
const prevShort = (_d = shortMeta === null || shortMeta === void 0 ? void 0 : shortMeta.prevDayPrice) !== null && _d !== void 0 ? _d : 0;
|
|
1981
1993
|
const ratio = currentShort !== 0 ? currentLong / currentShort : 1;
|
|
1982
1994
|
const ratio24h = prevShort !== 0 ? prevLong / prevShort : 1;
|
|
1983
1995
|
return { priceRatio: ratio, priceRatio24h: ratio24h };
|
|
@@ -1988,20 +2000,16 @@ const useTokenSelectionMetadataStore = create((set) => ({
|
|
|
1988
2000
|
let shortProduct = 1;
|
|
1989
2001
|
longTokens.forEach((token) => {
|
|
1990
2002
|
const metadata = longTokensMetadata[token.symbol];
|
|
1991
|
-
|
|
1992
|
-
if (price && token.weight > 0) {
|
|
2003
|
+
if ((metadata === null || metadata === void 0 ? void 0 : metadata.currentPrice) && token.weight > 0) {
|
|
1993
2004
|
const weightFactor = token.weight / 100;
|
|
1994
|
-
longProduct *= Math.pow(
|
|
2005
|
+
longProduct *= Math.pow(metadata.currentPrice, weightFactor);
|
|
1995
2006
|
}
|
|
1996
2007
|
});
|
|
1997
2008
|
shortTokens.forEach((token) => {
|
|
1998
2009
|
const metadata = shortTokensMetadata[token.symbol];
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
? token.weight / 100
|
|
2003
|
-
: -(token.weight / 100);
|
|
2004
|
-
shortProduct *= Math.pow(price, weightFactor);
|
|
2010
|
+
if ((metadata === null || metadata === void 0 ? void 0 : metadata.currentPrice) && token.weight > 0) {
|
|
2011
|
+
const weightFactor = token.weight / 100;
|
|
2012
|
+
shortProduct *= Math.pow(metadata.currentPrice, -weightFactor);
|
|
2005
2013
|
}
|
|
2006
2014
|
});
|
|
2007
2015
|
return longProduct * shortProduct;
|
|
@@ -2012,20 +2020,16 @@ const useTokenSelectionMetadataStore = create((set) => ({
|
|
|
2012
2020
|
let shortProduct = 1;
|
|
2013
2021
|
longTokens.forEach((token) => {
|
|
2014
2022
|
const metadata = longTokensMetadata[token.symbol];
|
|
2015
|
-
|
|
2016
|
-
if (price && token.weight > 0) {
|
|
2023
|
+
if ((metadata === null || metadata === void 0 ? void 0 : metadata.prevDayPrice) && token.weight > 0) {
|
|
2017
2024
|
const weightFactor = token.weight / 100;
|
|
2018
|
-
longProduct *= Math.pow(
|
|
2025
|
+
longProduct *= Math.pow(metadata.prevDayPrice, weightFactor);
|
|
2019
2026
|
}
|
|
2020
2027
|
});
|
|
2021
2028
|
shortTokens.forEach((token) => {
|
|
2022
2029
|
const metadata = shortTokensMetadata[token.symbol];
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
? token.weight / 100
|
|
2027
|
-
: -(token.weight / 100);
|
|
2028
|
-
shortProduct *= Math.pow(price, weightFactor);
|
|
2030
|
+
if ((metadata === null || metadata === void 0 ? void 0 : metadata.prevDayPrice) && token.weight > 0) {
|
|
2031
|
+
const weightFactor = token.weight / 100;
|
|
2032
|
+
shortProduct *= Math.pow(metadata.prevDayPrice, -weightFactor);
|
|
2029
2033
|
}
|
|
2030
2034
|
});
|
|
2031
2035
|
return longProduct * shortProduct;
|
|
@@ -6485,7 +6489,7 @@ const useHistoricalPriceData = () => {
|
|
|
6485
6489
|
const prevIntervalRef = useRef(null);
|
|
6486
6490
|
// Get all tokens from long and short selections
|
|
6487
6491
|
const getAllTokens = useCallback(() => {
|
|
6488
|
-
return [...longTokens, ...shortTokens]
|
|
6492
|
+
return [...longTokens, ...shortTokens];
|
|
6489
6493
|
}, [longTokens, shortTokens]);
|
|
6490
6494
|
// Track token and interval changes and manage cache accordingly
|
|
6491
6495
|
useEffect(() => {
|
|
@@ -6623,10 +6627,10 @@ const createCandleLookups = (tokenCandles) => {
|
|
|
6623
6627
|
const calculateWeightedRatio = (longTokens, shortTokens, candleLookups, timestamp, priceType) => {
|
|
6624
6628
|
let longProduct = 1;
|
|
6625
6629
|
let shortProduct = 1;
|
|
6626
|
-
const shouldUseAbsoluteQuoteRatio = isSingleAssetSideAgainstStableQuote(longTokens, shortTokens);
|
|
6627
6630
|
// Long side: PRICE^(WEIGHT/100)
|
|
6628
6631
|
for (const token of longTokens) {
|
|
6629
|
-
const
|
|
6632
|
+
const lookup = candleLookups[token.symbol];
|
|
6633
|
+
const candle = lookup === null || lookup === void 0 ? void 0 : lookup.get(timestamp);
|
|
6630
6634
|
if (candle) {
|
|
6631
6635
|
const price = candle[priceType];
|
|
6632
6636
|
if (price > 0) {
|
|
@@ -6640,14 +6644,13 @@ const calculateWeightedRatio = (longTokens, shortTokens, candleLookups, timestam
|
|
|
6640
6644
|
}
|
|
6641
6645
|
// Short side: PRICE^-(WEIGHT/100)
|
|
6642
6646
|
for (const token of shortTokens) {
|
|
6643
|
-
const
|
|
6647
|
+
const lookup = candleLookups[token.symbol];
|
|
6648
|
+
const candle = lookup === null || lookup === void 0 ? void 0 : lookup.get(timestamp);
|
|
6644
6649
|
if (candle) {
|
|
6645
6650
|
const price = candle[priceType];
|
|
6646
6651
|
if (price > 0) {
|
|
6647
|
-
const weightFactor =
|
|
6648
|
-
|
|
6649
|
-
: -(token.weight / 100);
|
|
6650
|
-
shortProduct *= Math.pow(price, weightFactor);
|
|
6652
|
+
const weightFactor = token.weight / 100;
|
|
6653
|
+
shortProduct *= Math.pow(price, -weightFactor);
|
|
6651
6654
|
}
|
|
6652
6655
|
}
|
|
6653
6656
|
else {
|
|
@@ -6700,37 +6703,19 @@ const getCompleteTimestamps = (candleLookups, requiredSymbols) => {
|
|
|
6700
6703
|
result.sort((a, b) => a - b);
|
|
6701
6704
|
return result;
|
|
6702
6705
|
};
|
|
6703
|
-
const getRequiredSymbols = (longTokens, shortTokens) => [...longTokens, ...shortTokens]
|
|
6704
|
-
.map((token) => token.symbol)
|
|
6705
|
-
.filter((symbol) => !isStableQuoteSymbol(symbol));
|
|
6706
|
-
const getCandleOrStableQuote = (candleLookups, symbol, timestamp) => {
|
|
6707
|
-
var _a, _b;
|
|
6708
|
-
if (isStableQuoteSymbol(symbol)) {
|
|
6709
|
-
return {
|
|
6710
|
-
s: symbol,
|
|
6711
|
-
t: timestamp,
|
|
6712
|
-
T: timestamp,
|
|
6713
|
-
o: 1,
|
|
6714
|
-
h: 1,
|
|
6715
|
-
l: 1,
|
|
6716
|
-
c: 1,
|
|
6717
|
-
};
|
|
6718
|
-
}
|
|
6719
|
-
return (_b = (_a = candleLookups[symbol]) === null || _a === void 0 ? void 0 : _a.get(timestamp)) !== null && _b !== void 0 ? _b : null;
|
|
6720
|
-
};
|
|
6721
6706
|
/**
|
|
6722
6707
|
* Compute basket candles from individual token candles using weighted ratios
|
|
6723
6708
|
* Optimized version that creates lookup maps once and reuses them
|
|
6724
6709
|
*/
|
|
6725
6710
|
const computeBasketCandles = (longTokens, shortTokens, tokenCandles) => {
|
|
6711
|
+
var _a, _b;
|
|
6726
6712
|
if (longTokens.length === 0 && shortTokens.length === 0) {
|
|
6727
6713
|
return [];
|
|
6728
6714
|
}
|
|
6729
6715
|
// Create efficient lookup maps once
|
|
6730
6716
|
const candleLookups = createCandleLookups(tokenCandles);
|
|
6731
|
-
const allSymbols =
|
|
6717
|
+
const allSymbols = [...longTokens, ...shortTokens].map(t => t.symbol);
|
|
6732
6718
|
const completeTimestamps = getCompleteTimestamps(candleLookups, allSymbols);
|
|
6733
|
-
const shouldUseAbsoluteQuoteRatio = isSingleAssetSideAgainstStableQuote(longTokens, shortTokens);
|
|
6734
6719
|
const basketCandles = [];
|
|
6735
6720
|
for (const timestamp of completeTimestamps) {
|
|
6736
6721
|
// Compute all OHLC products in a single pass per side
|
|
@@ -6740,7 +6725,7 @@ const computeBasketCandles = (longTokens, shortTokens, tokenCandles) => {
|
|
|
6740
6725
|
let missing = false;
|
|
6741
6726
|
// Accumulate volume/trades and compute long side contributions
|
|
6742
6727
|
for (const token of longTokens) {
|
|
6743
|
-
const candle =
|
|
6728
|
+
const candle = (_a = candleLookups[token.symbol]) === null || _a === void 0 ? void 0 : _a.get(timestamp);
|
|
6744
6729
|
if (!candle) {
|
|
6745
6730
|
missing = true;
|
|
6746
6731
|
break;
|
|
@@ -6765,14 +6750,12 @@ const computeBasketCandles = (longTokens, shortTokens, tokenCandles) => {
|
|
|
6765
6750
|
continue;
|
|
6766
6751
|
// Short side contributions (negative exponent)
|
|
6767
6752
|
for (const token of shortTokens) {
|
|
6768
|
-
const candle =
|
|
6753
|
+
const candle = (_b = candleLookups[token.symbol]) === null || _b === void 0 ? void 0 : _b.get(timestamp);
|
|
6769
6754
|
if (!candle) {
|
|
6770
6755
|
missing = true;
|
|
6771
6756
|
break;
|
|
6772
6757
|
}
|
|
6773
|
-
const weightFactor =
|
|
6774
|
-
? token.weight / 100
|
|
6775
|
-
: -(token.weight / 100);
|
|
6758
|
+
const weightFactor = -(token.weight / 100);
|
|
6776
6759
|
const o = candle.o;
|
|
6777
6760
|
const h = candle.h;
|
|
6778
6761
|
const l = candle.l;
|
|
@@ -6846,7 +6829,7 @@ const useBasketCandles = () => {
|
|
|
6846
6829
|
const fetchOverallPerformanceCandles = useCallback(async (startTime, endTime, interval) => {
|
|
6847
6830
|
await fetchHistoricalPriceData(startTime, endTime, interval);
|
|
6848
6831
|
const allCandles = await getAllHistoricalPriceData();
|
|
6849
|
-
const allTokens = [...longTokens, ...shortTokens]
|
|
6832
|
+
const allTokens = [...longTokens, ...shortTokens];
|
|
6850
6833
|
if (allTokens.length === 0)
|
|
6851
6834
|
return [];
|
|
6852
6835
|
const symbolsData = {};
|
|
@@ -6946,8 +6929,6 @@ const useBasketCandles = () => {
|
|
|
6946
6929
|
let t = null;
|
|
6947
6930
|
let T = null;
|
|
6948
6931
|
for (const symbol of symbolSet) {
|
|
6949
|
-
if (isStableQuoteSymbol(symbol))
|
|
6950
|
-
continue;
|
|
6951
6932
|
const c = candleData.get(symbol);
|
|
6952
6933
|
if (!c)
|
|
6953
6934
|
return null; // missing latest candle for symbol
|
|
@@ -6962,17 +6943,6 @@ const useBasketCandles = () => {
|
|
|
6962
6943
|
const intervalMs = CANDLE_INTERVAL_MS[candleInterval];
|
|
6963
6944
|
const maxCarryForwardMs = intervalMs * 2;
|
|
6964
6945
|
const getCandleForTargetWindow = (symbol) => {
|
|
6965
|
-
if (isStableQuoteSymbol(symbol)) {
|
|
6966
|
-
return {
|
|
6967
|
-
s: symbol,
|
|
6968
|
-
t,
|
|
6969
|
-
T,
|
|
6970
|
-
o: 1,
|
|
6971
|
-
h: 1,
|
|
6972
|
-
l: 1,
|
|
6973
|
-
c: 1,
|
|
6974
|
-
};
|
|
6975
|
-
}
|
|
6976
6946
|
const c = snapshot[symbol];
|
|
6977
6947
|
if (c.t === t)
|
|
6978
6948
|
return c;
|
|
@@ -6994,7 +6964,6 @@ const useBasketCandles = () => {
|
|
|
6994
6964
|
// Compute weighted OHLC similar to computeBasketCandles
|
|
6995
6965
|
let longOpen = 1, longHigh = 1, longLow = 1, longClose = 1;
|
|
6996
6966
|
let shortOpen = 1, shortHigh = 1, shortLow = 1, shortClose = 1;
|
|
6997
|
-
const shouldUseAbsoluteQuoteRatio = isSingleAssetSideAgainstStableQuote(longTokens, shortTokens);
|
|
6998
6967
|
for (const token of longTokens) {
|
|
6999
6968
|
const c = getCandleForTargetWindow(token.symbol);
|
|
7000
6969
|
if (!c)
|
|
@@ -7012,9 +6981,7 @@ const useBasketCandles = () => {
|
|
|
7012
6981
|
const c = getCandleForTargetWindow(token.symbol);
|
|
7013
6982
|
if (!c)
|
|
7014
6983
|
return null;
|
|
7015
|
-
const w =
|
|
7016
|
-
? token.weight / 100
|
|
7017
|
-
: -(token.weight / 100);
|
|
6984
|
+
const w = -(token.weight / 100);
|
|
7018
6985
|
const o = c.o, h = c.h, l = c.l, cl = c.c;
|
|
7019
6986
|
if (!(o > 0 && h > 0 && l > 0 && cl > 0))
|
|
7020
6987
|
return null;
|
|
@@ -7373,7 +7340,9 @@ const calculatePositionAsset = (asset, currentPrice, totalInitialPositionSize, t
|
|
|
7373
7340
|
};
|
|
7374
7341
|
};
|
|
7375
7342
|
const buildPositionValue = (rawPositions, clearinghouseState, getAssetByName) => {
|
|
7376
|
-
|
|
7343
|
+
const ifHip4Position = (position) => position.longAssets.some((a) => a.coin.startsWith("#")) ||
|
|
7344
|
+
position.shortAssets.some((a) => a.coin.startsWith("#"));
|
|
7345
|
+
return rawPositions.filter((p) => !ifHip4Position(p)).map((position) => {
|
|
7377
7346
|
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
7378
7347
|
let mappedPosition = {
|
|
7379
7348
|
positionId: position.positionId,
|
|
@@ -7516,7 +7485,12 @@ function usePosition() {
|
|
|
7516
7485
|
Object.keys(tokenMetadata).length === 0)
|
|
7517
7486
|
return null;
|
|
7518
7487
|
return buildPositionValue(userOpenPositions, aggregatedClearingHouseState, getAssetByName);
|
|
7519
|
-
}, [
|
|
7488
|
+
}, [
|
|
7489
|
+
userOpenPositions,
|
|
7490
|
+
aggregatedClearingHouseState,
|
|
7491
|
+
tokenMetadata,
|
|
7492
|
+
getAssetByName,
|
|
7493
|
+
]);
|
|
7520
7494
|
const planRebalance = (positionId, targetWeights) => {
|
|
7521
7495
|
var _a;
|
|
7522
7496
|
if (!openPositions) {
|
|
@@ -7529,7 +7503,10 @@ function usePosition() {
|
|
|
7529
7503
|
const assets = [];
|
|
7530
7504
|
const allAssets = [
|
|
7531
7505
|
...position.longAssets.map((a) => ({ asset: a, side: 'long' })),
|
|
7532
|
-
...position.shortAssets.map((a) => ({
|
|
7506
|
+
...position.shortAssets.map((a) => ({
|
|
7507
|
+
asset: a,
|
|
7508
|
+
side: 'short',
|
|
7509
|
+
})),
|
|
7533
7510
|
];
|
|
7534
7511
|
const totalValue = allAssets.reduce((sum, { asset }) => sum + asset.positionValue, 0);
|
|
7535
7512
|
for (const { asset, side } of allAssets) {
|
|
@@ -9502,4 +9479,4 @@ function getOrderTrailingInfo(order) {
|
|
|
9502
9479
|
return undefined;
|
|
9503
9480
|
}
|
|
9504
9481
|
|
|
9505
|
-
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 };
|
|
9482
|
+
export { ClosePositionValidationError, ConflictDetector, MAX_ASSETS_PER_LEG, MINIMUM_ASSET_USD_VALUE, MaxAssetsPerLegError, MinimumPositionSizeError, PearHyperliquidProvider, SYMBOL_DISPLAY_ALIASES, 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, matchesSymbolOrAlias, toDisplaySymbol, toHlSymbol, 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/dist/types.d.ts
CHANGED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare const SYMBOL_DISPLAY_ALIASES: Record<string, string>;
|
|
2
|
+
export declare function toDisplaySymbol(symbol: string, market?: string): string;
|
|
3
|
+
export declare function toHlSymbol(displayOrSymbol: string, market?: string): string;
|
|
4
|
+
export declare function matchesSymbolOrAlias(symbol: string, term: string, market?: string): boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import type { TokenSelection } from '../types';
|
|
2
|
-
export declare const STABLE_QUOTE_SYMBOLS: Set<string>;
|
|
3
|
-
export declare const isStableQuoteSymbol: (symbol: string) => boolean;
|
|
4
|
-
export declare const hasNonStableTokens: (tokens: TokenSelection[]) => boolean;
|
|
5
|
-
export declare const isStableOnlySide: (tokens: TokenSelection[]) => boolean;
|
|
6
|
-
export declare const isSingleAssetSideAgainstStableQuote: (longTokens: TokenSelection[], shortTokens: TokenSelection[]) => boolean;
|