@orderly.network/hooks 0.0.24 → 0.0.26

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.mjs CHANGED
@@ -89,7 +89,7 @@ var useQuery = (query, options) => {
89
89
  );
90
90
  };
91
91
  var useAccountInstance = () => {
92
- const { configStore, keyStore, walletAdapter } = useContext(OrderlyContext);
92
+ const { configStore, keyStore, contractManager, walletAdapter } = useContext(OrderlyContext);
93
93
  if (!configStore)
94
94
  throw new Error("configStore is not defined, please use OrderlyProvider");
95
95
  if (!keyStore) {
@@ -100,7 +100,12 @@ var useAccountInstance = () => {
100
100
  const account5 = useConstant(() => {
101
101
  let account6 = SimpleDI.get("account");
102
102
  if (!account6) {
103
- account6 = new Account(configStore, keyStore, walletAdapter);
103
+ account6 = new Account(
104
+ configStore,
105
+ keyStore,
106
+ contractManager,
107
+ walletAdapter
108
+ );
104
109
  SimpleDI.registerByName("account", account6);
105
110
  }
106
111
  return account6;
@@ -199,6 +204,7 @@ var useAccount = () => {
199
204
  configStore,
200
205
  keyStore,
201
206
  walletAdapter,
207
+ contractManager,
202
208
  onWalletConnect,
203
209
  onWalletDisconnect,
204
210
  onSetChain
@@ -210,14 +216,7 @@ var useAccount = () => {
210
216
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
211
217
  );
212
218
  }
213
- const account5 = useConstant(() => {
214
- let account6 = SimpleDI.get("account");
215
- if (!account6) {
216
- account6 = new Account(configStore, keyStore, walletAdapter);
217
- SimpleDI.registerByName("account", account6);
218
- }
219
- return account6;
220
- });
219
+ const account5 = useAccountInstance();
221
220
  const [state, setState] = useState(account5.stateValue);
222
221
  const statusChangeHandler = (nextState) => {
223
222
  setState(() => nextState);
@@ -526,17 +525,93 @@ var useMarkPrice = (symbol) => {
526
525
  });
527
526
  };
528
527
 
528
+ // src/utils/createGetter.ts
529
+ function createGetter(data, depth = 2) {
530
+ return new Proxy(data || {}, {
531
+ get(target, property, receiver) {
532
+ if (depth === 1) {
533
+ return (defaultValue) => {
534
+ var _a;
535
+ if (!target)
536
+ return defaultValue;
537
+ return (_a = target[property]) != null ? _a : defaultValue;
538
+ };
539
+ }
540
+ return (key, defaultValue) => {
541
+ var _a, _b;
542
+ if (key) {
543
+ return (_b = (_a = target[property]) == null ? void 0 : _a[key]) != null ? _b : defaultValue;
544
+ } else {
545
+ return target[property];
546
+ }
547
+ };
548
+ }
549
+ });
550
+ }
551
+ var useSymbolsInfo = () => {
552
+ const { data = {} } = useQuery(`/v1/public/info`, {
553
+ focusThrottleInterval: 1e3 * 60 * 60 * 24,
554
+ revalidateOnFocus: false,
555
+ formatter(data2) {
556
+ var _a;
557
+ if (!(data2 == null ? void 0 : data2.rows) || !((_a = data2 == null ? void 0 : data2.rows) == null ? void 0 : _a.length)) {
558
+ return {};
559
+ }
560
+ const obj = /* @__PURE__ */ Object.create(null);
561
+ for (let index = 0; index < data2.rows.length; index++) {
562
+ const item = data2.rows[index];
563
+ const arr = item.symbol.split("_");
564
+ const base_dp = getPrecisionByNumber(item.base_tick);
565
+ const quote_dp = getPrecisionByNumber(item.quote_tick);
566
+ obj[item.symbol] = __spreadProps(__spreadValues({}, item), {
567
+ base_dp,
568
+ quote_dp,
569
+ base: arr[1],
570
+ quote: arr[2],
571
+ type: arr[0],
572
+ name: `${arr[1]}-${arr[0]}`
573
+ });
574
+ }
575
+ return obj;
576
+ }
577
+ });
578
+ return createGetter(data);
579
+ };
580
+
529
581
  // src/orderly/useOrderbookStream.ts
530
582
  var paddingFn = (len) => Array(len).fill([Number.NaN, Number.NaN, Number.NaN]);
531
583
  var asksSortFn = (a, b) => a[0] - b[0];
532
584
  var bidsSortFn = (a, b) => b[0] - a[0];
533
- var reduceItems = (depth, level, data) => {
585
+ var reduceItems = (depth, level, data, asks = false) => {
534
586
  if (!Array.isArray(data) || data.length === 0) {
535
587
  return [];
536
588
  }
589
+ let newData = [...data];
537
590
  const result = [];
538
- for (let i = 0; i < data.length; i++) {
539
- const [price, quantity] = data[i];
591
+ if (typeof depth !== "undefined") {
592
+ const prices = /* @__PURE__ */ new Map();
593
+ for (let i = 0; i < data.length; i++) {
594
+ const [price, quantity] = data[i];
595
+ if (isNaN(price) || isNaN(quantity))
596
+ continue;
597
+ let priceKey;
598
+ if (asks) {
599
+ priceKey = Math.ceil(price / depth) * depth;
600
+ } else {
601
+ priceKey = Math.floor(price / depth) * depth;
602
+ }
603
+ if (prices.has(priceKey)) {
604
+ const item = prices.get(priceKey);
605
+ const itemPrice = item[1] + quantity;
606
+ prices.set(priceKey, [priceKey, itemPrice]);
607
+ } else {
608
+ prices.set(priceKey, [priceKey, quantity]);
609
+ }
610
+ }
611
+ newData = Array.from(prices.values());
612
+ }
613
+ for (let i = 0; i < newData.length; i++) {
614
+ const [price, quantity] = newData[i];
540
615
  if (isNaN(price) || isNaN(quantity))
541
616
  continue;
542
617
  result.push([
@@ -551,7 +626,7 @@ var reduceItems = (depth, level, data) => {
551
626
  return result;
552
627
  };
553
628
  var reduceOrderbook = (depth, level, data) => {
554
- const asks = reduceItems(depth, level, data.asks).reverse();
629
+ const asks = reduceItems(depth, level, data.asks, true).reverse();
555
630
  const bids = reduceItems(depth, level, data.bids);
556
631
  return {
557
632
  asks: asks.length < level ? paddingFn(level - asks.length).concat(asks) : asks,
@@ -565,10 +640,6 @@ var mergeItems = (data, update) => {
565
640
  const item = update.shift();
566
641
  if (item) {
567
642
  const [price, quantity] = item;
568
- if (price < data[0][0] && quantity > 0) {
569
- data.unshift(item);
570
- continue;
571
- }
572
643
  const index = data.findIndex(([p], index2) => p === price);
573
644
  if (index === -1) {
574
645
  data.push(item);
@@ -576,8 +647,9 @@ var mergeItems = (data, update) => {
576
647
  if (quantity === 0) {
577
648
  data.splice(index, 1);
578
649
  continue;
650
+ } else {
651
+ data[index] = item;
579
652
  }
580
- data[index] = item;
581
653
  }
582
654
  }
583
655
  }
@@ -596,11 +668,19 @@ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) =>
596
668
  const [requestData, setRequestData] = useState(null);
597
669
  const [data, setData] = useState(initial);
598
670
  const [isLoading, setIsLoading] = useState(true);
599
- const [depth, setDepth] = useState(1e-3);
600
671
  const [level, setLevel] = useState(() => {
601
672
  var _a;
602
673
  return (_a = options == null ? void 0 : options.level) != null ? _a : 10;
603
674
  });
675
+ const config = useSymbolsInfo()[symbol];
676
+ const [depth, setDepth] = useState();
677
+ const depths = useMemo(() => {
678
+ const tick = config("quote_tick");
679
+ return [tick, tick * 10, tick * 100, tick * 1e3];
680
+ }, [config("quote_tick")]);
681
+ useEffect(() => {
682
+ setDepth(config("quote_tick"));
683
+ }, [config("quote_tick")]);
604
684
  const ws = useWS();
605
685
  const ticker = useTickerStream(symbol);
606
686
  const eventEmitter = useEventEmitter();
@@ -615,7 +695,6 @@ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) =>
615
695
  },
616
696
  {
617
697
  onMessage: (message) => {
618
- console.log("orderbook request message", message);
619
698
  if (!!message) {
620
699
  const reduceOrderbookData = reduceOrderbook(depth, level, message);
621
700
  setRequestData(reduceOrderbookData);
@@ -628,7 +707,7 @@ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) =>
628
707
  return () => {
629
708
  setRequestData(null);
630
709
  };
631
- }, [symbol]);
710
+ }, [symbol, depth]);
632
711
  const { data: markPrice } = useMarkPrice(symbol);
633
712
  useEffect(() => {
634
713
  if (!requestData)
@@ -656,7 +735,7 @@ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) =>
656
735
  eventEmitter.emit("orderbook:item:click", item);
657
736
  }, []);
658
737
  const onDepthChange = useCallback((depth2) => {
659
- console.log("Orderbook depth has changed:", depth2);
738
+ setDepth(() => depth2);
660
739
  }, []);
661
740
  const middlePrice = useMemo(() => {
662
741
  let asksFrist = 0, bidsFirst = 0;
@@ -672,63 +751,10 @@ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) =>
672
751
  }, [ticker, data]);
673
752
  return [
674
753
  __spreadProps(__spreadValues({}, data), { markPrice, middlePrice }),
675
- { onDepthChange, depth, isLoading, onItemClick }
754
+ { onDepthChange, depth, allDepths: depths, isLoading, onItemClick }
676
755
  ];
677
756
  };
678
757
 
679
- // src/utils/createGetter.ts
680
- function createGetter(data, depth = 2) {
681
- return new Proxy(data || {}, {
682
- get(target, property, receiver) {
683
- if (depth === 1) {
684
- return (defaultValue) => {
685
- var _a;
686
- if (!target)
687
- return defaultValue;
688
- return (_a = target[property]) != null ? _a : defaultValue;
689
- };
690
- }
691
- return (key, defaultValue) => {
692
- var _a, _b;
693
- if (key) {
694
- return (_b = (_a = target[property]) == null ? void 0 : _a[key]) != null ? _b : defaultValue;
695
- } else {
696
- return target[property];
697
- }
698
- };
699
- }
700
- });
701
- }
702
- var useSymbolsInfo = () => {
703
- const { data = {} } = useQuery(`/v1/public/info`, {
704
- focusThrottleInterval: 1e3 * 60 * 60 * 24,
705
- revalidateOnFocus: false,
706
- formatter(data2) {
707
- var _a;
708
- if (!(data2 == null ? void 0 : data2.rows) || !((_a = data2 == null ? void 0 : data2.rows) == null ? void 0 : _a.length)) {
709
- return {};
710
- }
711
- const obj = /* @__PURE__ */ Object.create(null);
712
- for (let index = 0; index < data2.rows.length; index++) {
713
- const item = data2.rows[index];
714
- const arr = item.symbol.split("_");
715
- const base_dp = getPrecisionByNumber(item.base_tick);
716
- const quote_dp = getPrecisionByNumber(item.quote_tick);
717
- obj[item.symbol] = __spreadProps(__spreadValues({}, item), {
718
- base_dp,
719
- quote_dp,
720
- base: arr[1],
721
- quote: arr[2],
722
- type: arr[0],
723
- name: `${arr[1]}-${arr[0]}`
724
- });
725
- }
726
- return obj;
727
- }
728
- });
729
- return createGetter(data);
730
- };
731
-
732
758
  // src/orderly/useTokenInfo.ts
733
759
  var useTokenInfo = () => {
734
760
  const { data = {} } = useQuery(
@@ -986,10 +1012,7 @@ var usePositionStream = (symbol, options) => {
986
1012
  item.symbol,
987
1013
  markPrices
988
1014
  );
989
- const notional = positions.notional(
990
- item.position_qty,
991
- item.average_open_price
992
- );
1015
+ const notional = positions.notional(item.position_qty, price);
993
1016
  const unrealPnl = positions.unrealizedPnL({
994
1017
  qty: item.position_qty,
995
1018
  openPrice: item.average_open_price,
@@ -1659,6 +1682,7 @@ var useOrderStream = ({
1659
1682
  side,
1660
1683
  size = 100
1661
1684
  } = {}) => {
1685
+ const ee = useEventEmitter();
1662
1686
  const { data: markPrices = {} } = useMarkPricesStream();
1663
1687
  const [doCancelOrder] = useMutation("/v1/order", "DELETE");
1664
1688
  const [doUpdateOrder] = useMutation("/v1/order", "PUT");
@@ -1699,6 +1723,13 @@ var useOrderStream = ({
1699
1723
  });
1700
1724
  });
1701
1725
  }, [ordersResponse.data, markPrices]);
1726
+ useEffect(() => {
1727
+ const handler = () => ordersResponse.mutate();
1728
+ ee.on("orders:changed", handler);
1729
+ return () => {
1730
+ ee.off("orders:changed", handler);
1731
+ };
1732
+ }, []);
1702
1733
  const cancelAllOrders = useCallback(() => {
1703
1734
  }, [ordersResponse.data]);
1704
1735
  const updateOrder = useCallback((orderId, order2) => {
@@ -1732,38 +1763,31 @@ var useMarketTradeStream = (symbol, options = {}) => {
1732
1763
  if (!symbol) {
1733
1764
  throw new Error("useTradeStream: symbol is required");
1734
1765
  }
1735
- useState([]);
1766
+ const [trades, setTrades] = useState([]);
1736
1767
  const { level = 20 } = options;
1737
- const { data, isLoading } = useQuery(
1738
- `/v1/public/market_trades?symbol=${symbol}&limit=${level}`
1739
- // {
1740
- // onSuccess: (data) => {
1741
- // // console.log("trades ^^^^^^", data);
1742
- // if (Array.isArray(data)) {
1743
- // setTrades(data);
1744
- // }
1745
- // return data;
1746
- // },
1747
- // }
1768
+ const { isLoading } = useQuery(
1769
+ `/v1/public/market_trades?symbol=${symbol}&limit=${level}`,
1770
+ {
1771
+ onSuccess: (data) => {
1772
+ if (Array.isArray(data)) {
1773
+ setTrades(() => data);
1774
+ }
1775
+ return data;
1776
+ }
1777
+ }
1748
1778
  );
1749
1779
  const ws = useWS();
1750
1780
  useEffect(() => {
1751
1781
  const unsubscript = ws.subscribe(`@${symbol}/@trade`, {
1752
- onMessage: (data2) => {
1753
- console.log("trade", data2);
1782
+ onMessage: (data) => {
1783
+ console.log("ws: trade", data);
1754
1784
  }
1755
1785
  });
1756
1786
  return () => {
1757
1787
  unsubscript == null ? void 0 : unsubscript();
1758
1788
  };
1759
1789
  }, []);
1760
- return { data, isLoading };
1761
- };
1762
-
1763
- // src/orderly/useTrades.tsx
1764
- var useTradeStream = () => {
1765
- const { data, isLoading } = usePrivateQuery("/v1/trades");
1766
- return [data, { isLoading }];
1790
+ return { data: trades, isLoading };
1767
1791
  };
1768
1792
  var useMarginRatio = () => {
1769
1793
  const [{ rows }] = usePositionStream();
@@ -1844,12 +1868,12 @@ var useBalance = () => {
1844
1868
  var usePrivateDataObserver = () => {
1845
1869
  const ws = useWS();
1846
1870
  const { mutate: mutate2 } = useSWRConfig();
1871
+ const ee = useEventEmitter();
1847
1872
  useEffect(() => {
1848
1873
  console.log("subscribe: executionreport");
1849
1874
  const unsubscribe = ws.privateSubscribe("executionreport", {
1850
1875
  onMessage: (data) => {
1851
- console.info("refresh orders");
1852
- console.log(data);
1876
+ ee.emit("orders:changed");
1853
1877
  }
1854
1878
  });
1855
1879
  return () => unsubscribe == null ? void 0 : unsubscribe();
@@ -1910,6 +1934,6 @@ var useFundingRateBySymbol = (symbol) => {
1910
1934
  return useQuery(`/public/funding_rate/${symbol}`);
1911
1935
  };
1912
1936
 
1913
- export { DataSourceProvider, OrderStatus, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useAccountInfo, useAccountInstance, useAppState, useBalance, useChains, useCollateral, useEventEmitter, useExecutionReport, useFetures, useFundingRate, useHolding, useLeverage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePreLoadData, usePrivateDataObserver, usePrivateObserve, usePrivateQuery, useQuery, useRunOnce, useSessionStorage, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradeStream, useTradingView, useWS };
1937
+ export { DataSourceProvider, OrderStatus, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useAccountInfo, useAccountInstance, useAppState, useBalance, useChains, useCollateral, useEventEmitter, useExecutionReport, useFetures, useFundingRate, useHolding, useLeverage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePreLoadData, usePrivateDataObserver, usePrivateObserve, usePrivateQuery, useQuery, useRunOnce, useSessionStorage, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradingView, useWS };
1914
1938
  //# sourceMappingURL=out.js.map
1915
1939
  //# sourceMappingURL=index.mjs.map