@orderly.network/hooks 3.0.0-beta.1 → 3.0.0-beta.10

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
@@ -1,11 +1,11 @@
1
+ import React, { createContext, createElement, useContext, useCallback, useState, useEffect, useMemo, useRef, useId, useLayoutEffect } from 'react';
1
2
  import { get, WS, mutate as mutate$1 } from '@orderly.network/net';
2
- import React, { createContext, useContext, useCallback, useState, useEffect, useMemo, useRef, useId, useLayoutEffect } from 'react';
3
3
  import useSWR5__default, { mutate } from 'swr';
4
4
  import * as useSWR5 from 'swr';
5
5
  export { useSWR5 as swr };
6
6
  export { unstable_serialize, default as useSWR, useSWRConfig } from 'swr';
7
7
  import { usePluginScope } from '@orderly.network/plugin-core';
8
- import { TesnetTokenFallback, ArbitrumSepoliaTokenInfo, SolanaDevnetTokenInfo, OrderType, OrderSide, MarginMode, SDKError, TrackerEventName, AccountStatusEnum, AlgoOrderType, AlgoOrderRootType, OrderStatus, ArbitrumSepoliaChainInfo, SolanaDevnetChainInfo, EMPTY_LIST, EMPTY_OBJECT, isNativeTokenChecker, nativeTokenAddress, ChainKey, chainsInfoMap, ARBITRUM_TESTNET_CHAINID, ARBITRUM_MAINNET_CHAINID, ChainNamespace, MaxUint256, DEPOSIT_FEE_RATE, ETHEREUM_MAINNET_CHAINID, LedgerWalletKey, SOLANA_TESTNET_CHAINID, MONAD_TESTNET_CHAINID, ABSTRACT_TESTNET_CHAINID, BSC_TESTNET_CHAINID, SolanaChains, PositionType, DistributionType, TriggerPriceType } from '@orderly.network/types';
8
+ import { TesnetTokenFallback, ArbitrumSepoliaTokenInfo, SolanaDevnetTokenInfo, MarginMode, OrderType, OrderSide, SDKError, TrackerEventName, AccountStatusEnum, AlgoOrderType, AlgoOrderRootType, OrderStatus, ArbitrumSepoliaChainInfo, SolanaDevnetChainInfo, EMPTY_LIST, EMPTY_OBJECT, isNativeTokenChecker, nativeTokenAddress, ChainKey, chainsInfoMap, ARBITRUM_TESTNET_CHAINID, ARBITRUM_MAINNET_CHAINID, ChainNamespace, MaxUint256, DEPOSIT_FEE_RATE, ETHEREUM_MAINNET_CHAINID, LedgerWalletKey, SOLANA_TESTNET_CHAINID, MONAD_TESTNET_CHAINID, ABSTRACT_TESTNET_CHAINID, BSC_TESTNET_CHAINID, SolanaChains, PositionType, DistributionType, TriggerPriceType } from '@orderly.network/types';
9
9
  import { zero, windowGuard, getTimestamp, getGlobalObject, Decimal, timeConvertString, isTestnet, getPrecisionByNumber, getBBOType, camelCaseToUnderscoreCase, commify, todpIfNeed, getTPSLDirection } from '@orderly.network/utils';
10
10
  import useSWRMutation from 'swr/mutation';
11
11
  import useConstant from 'use-constant';
@@ -35,13 +35,24 @@ var __export = (target, all) => {
35
35
  for (var name in all)
36
36
  __defProp(target, name, { get: all[name], enumerable: true });
37
37
  };
38
+ var MarketCategoriesConfigContext = createContext(void 0);
39
+ var MarketCategoriesConfigProvider = ({ value, children }) => {
40
+ return createElement(
41
+ MarketCategoriesConfigContext.Provider,
42
+ { value },
43
+ children
44
+ );
45
+ };
46
+ function useMarketCategoriesConfig() {
47
+ return useContext(MarketCategoriesConfigContext);
48
+ }
38
49
 
39
50
  // src/version.ts
40
51
  if (typeof window !== "undefined") {
41
52
  window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};
42
- window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "3.0.0-beta.1";
53
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "3.0.0-beta.10";
43
54
  }
44
- var version_default = "3.0.0-beta.1";
55
+ var version_default = "3.0.0-beta.10";
45
56
  var fetcher = (url, init2 = {}, queryOptions) => get(url, init2, queryOptions?.formatter);
46
57
  var noCacheConfig = {
47
58
  dedupingInterval: 0,
@@ -570,6 +581,20 @@ var useAudioPlayer = (src, options = {}) => {
570
581
  const el = getOrderFilledAudio();
571
582
  el.volume = Math.max(0, Math.min(1, volume));
572
583
  }, [volume]);
584
+ useEffect(() => {
585
+ const handleVisibilityChange = () => {
586
+ if (document.visibilityState === "visible") {
587
+ const el = getOrderFilledAudio();
588
+ el.pause();
589
+ el.removeAttribute("src");
590
+ el.load();
591
+ }
592
+ };
593
+ document.addEventListener("visibilitychange", handleVisibilityChange);
594
+ return () => {
595
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
596
+ };
597
+ }, []);
573
598
  const play = useCallback(() => {
574
599
  const currentSrc = srcRef.current;
575
600
  const currentEnabled = enabledRef.current;
@@ -1279,7 +1304,7 @@ function checkTPSLOrderTypeIsMarket(key, values) {
1279
1304
  }
1280
1305
  function tpslCalculateHelper(key, inputs, options = {}) {
1281
1306
  const { symbol } = options;
1282
- if (key !== "quantity" && key !== "tp_trigger_price" && key !== "sl_trigger_price" && key !== "tp_pnl" && key !== "sl_pnl" && key !== "tp_offset" && key !== "sl_offset" && key !== "tp_offset_percentage" && key !== "sl_offset_percentage" && key !== "tp_order_price" && key !== "sl_order_price" && key !== "tp_order_type" && key !== "sl_order_type") {
1307
+ if (key !== "quantity" && key !== "tp_trigger_price" && key !== "sl_trigger_price" && key !== "tp_pnl" && key !== "sl_pnl" && key !== "tp_offset" && key !== "sl_offset" && key !== "tp_offset_percentage" && key !== "sl_offset_percentage" && key !== "tp_offset_from_mark" && key !== "sl_offset_from_mark" && key !== "tp_offset_percentage_from_mark" && key !== "sl_offset_percentage_from_mark" && key !== "tp_order_price" && key !== "sl_order_price" && key !== "tp_order_type" && key !== "sl_order_type") {
1283
1308
  return {
1284
1309
  [key]: inputs.value
1285
1310
  };
@@ -1287,6 +1312,7 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1287
1312
  const orderType = key.startsWith("tp_") ? AlgoOrderType.TAKE_PROFIT : AlgoOrderType.STOP_LOSS;
1288
1313
  const keyPrefix = key.slice(0, 3);
1289
1314
  const qty = Number(key === "quantity" ? inputs.value : inputs.qty);
1315
+ const markPrice = inputs.markPrice ?? inputs.entryPrice;
1290
1316
  if (qty === 0 && (key === "tp_pnl" || key === "sl_pnl" || key === "tp_trigger_price" || key === "sl_trigger_price")) {
1291
1317
  return {
1292
1318
  // [`${keyPrefix}trigger_price`]: "",
@@ -1297,7 +1323,7 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1297
1323
  [key]: inputs.value
1298
1324
  };
1299
1325
  }
1300
- let trigger_price, offset, offset_percentage, pnl, order_price, tpsl_order_type = inputs.values[`${keyPrefix}order_type`] ?? OrderType.MARKET;
1326
+ let trigger_price, offset, offset_percentage, offset_from_mark, offset_percentage_from_mark, pnl, order_price, tpsl_order_type = inputs.values[`${keyPrefix}order_type`] ?? OrderType.MARKET;
1301
1327
  const entryPrice = new Decimal(inputs.entryPrice).todp(options.symbol?.quote_dp ?? 2, Decimal.ROUND_UP).toNumber();
1302
1328
  switch (key) {
1303
1329
  case "tp_trigger_price":
@@ -1309,6 +1335,8 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1309
1335
  [`${keyPrefix}trigger_price`]: trigger_price,
1310
1336
  [`${keyPrefix}offset`]: "",
1311
1337
  [`${keyPrefix}offset_percentage`]: "",
1338
+ [`${keyPrefix}offset_from_mark`]: "",
1339
+ [`${keyPrefix}offset_percentage_from_mark`]: "",
1312
1340
  [`${keyPrefix}pnl`]: "",
1313
1341
  [`${keyPrefix}ROI`]: ""
1314
1342
  };
@@ -1318,31 +1346,6 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1318
1346
  }
1319
1347
  break;
1320
1348
  }
1321
- // case "tp_enable":
1322
- // case "sl_enable": {
1323
- // return {
1324
- // [`${keyPrefix}enable`]: inputs.value,
1325
- // [`${keyPrefix}order_type`]: OrderType.MARKET,
1326
- // [`${keyPrefix}trigger_price`]: "",
1327
- // [`${keyPrefix}order_price`]: "",
1328
- // [`${keyPrefix}offset`]: "",
1329
- // [`${keyPrefix}offset_percentage`]: "",
1330
- // [`${keyPrefix}pnl`]: "",
1331
- // [`${keyPrefix}ROI`]: "",
1332
- // };
1333
- // }
1334
- // case 'tp_pnl':{
1335
- // if (inputs.values.tp_order_type !== OrderType.MARKET) {
1336
- // pnl = inputs.value;
1337
- // trigger_price = pnlToPrice({
1338
- // qty,
1339
- // pnl: Number(inputs.value),
1340
- // entryPrice,
1341
- // orderSide: inputs.orderSide,
1342
- // orderType,
1343
- // })
1344
- // }
1345
- // }
1346
1349
  case "tp_pnl":
1347
1350
  case "sl_pnl": {
1348
1351
  pnl = inputs.value;
@@ -1389,6 +1392,30 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1389
1392
  }
1390
1393
  break;
1391
1394
  }
1395
+ case "tp_offset_from_mark":
1396
+ case "sl_offset_from_mark": {
1397
+ offset_from_mark = inputs.value;
1398
+ if (!checkTPSLOrderTypeIsMarket(key, inputs.values)) {
1399
+ order_price = offsetToPrice({
1400
+ qty,
1401
+ offset: Number(inputs.value),
1402
+ entryPrice: markPrice,
1403
+ orderSide: inputs.orderSide,
1404
+ orderType: key === "tp_offset_from_mark" ? AlgoOrderType.TAKE_PROFIT : AlgoOrderType.STOP_LOSS
1405
+ });
1406
+ trigger_price = inputs.values[`${keyPrefix}trigger_price`] ?? order_price;
1407
+ } else {
1408
+ trigger_price = offsetToPrice({
1409
+ qty,
1410
+ offset: Number(inputs.value),
1411
+ // entryPrice,
1412
+ entryPrice: markPrice,
1413
+ orderSide: inputs.orderSide,
1414
+ orderType: key === "tp_offset_from_mark" ? AlgoOrderType.TAKE_PROFIT : AlgoOrderType.STOP_LOSS
1415
+ });
1416
+ }
1417
+ break;
1418
+ }
1392
1419
  case "tp_order_price":
1393
1420
  case "sl_order_price": {
1394
1421
  order_price = inputs.value;
@@ -1429,12 +1456,38 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1429
1456
  }
1430
1457
  break;
1431
1458
  }
1459
+ case "tp_offset_percentage_from_mark":
1460
+ case "sl_offset_percentage_from_mark": {
1461
+ offset_percentage_from_mark = inputs.value;
1462
+ const markBase = Number(markPrice);
1463
+ if (!checkTPSLOrderTypeIsMarket(key, inputs.values)) {
1464
+ order_price = offsetPercentageToPrice({
1465
+ qty,
1466
+ percentage: Number(`${inputs.value}`.replace(/\.0{0,2}$/, "")),
1467
+ entryPrice: markBase,
1468
+ orderSide: inputs.orderSide,
1469
+ orderType
1470
+ });
1471
+ trigger_price = inputs.values[`${keyPrefix}trigger_price`] ?? order_price;
1472
+ } else {
1473
+ trigger_price = offsetPercentageToPrice({
1474
+ qty,
1475
+ percentage: Number(`${inputs.value}`.replace(/\.0{0,2}$/, "")),
1476
+ entryPrice: markBase,
1477
+ orderSide: inputs.orderSide,
1478
+ orderType
1479
+ });
1480
+ }
1481
+ break;
1482
+ }
1432
1483
  }
1433
1484
  if (!trigger_price && checkTPSLOrderTypeIsMarket(key, inputs.values)) {
1434
1485
  return {
1435
1486
  [`${keyPrefix}trigger_price`]: "",
1436
1487
  [`${keyPrefix}offset`]: "",
1437
1488
  [`${keyPrefix}offset_percentage`]: "",
1489
+ [`${keyPrefix}offset_from_mark`]: "",
1490
+ [`${keyPrefix}offset_percentage_from_mark`]: "",
1438
1491
  [`${keyPrefix}pnl`]: "",
1439
1492
  [`${keyPrefix}ROI`]: "",
1440
1493
  [key]: inputs.value
@@ -1479,6 +1532,8 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1479
1532
  [`${keyPrefix}order_price`]: order_price ? todpIfNeed(order_price, symbol?.quote_dp ?? 2) : "",
1480
1533
  [`${keyPrefix}offset`]: offset ?? "",
1481
1534
  [`${keyPrefix}offset_percentage`]: offset_percentage ?? "",
1535
+ [`${keyPrefix}offset_from_mark`]: offset_from_mark ?? inputs.values[`${keyPrefix}offset_from_mark`] ?? "",
1536
+ [`${keyPrefix}offset_percentage_from_mark`]: offset_percentage_from_mark ?? inputs.values[`${keyPrefix}offset_percentage_from_mark`] ?? "",
1482
1537
  [`${keyPrefix}pnl`]: pnl ?? ""
1483
1538
  // [`${keyPrefix}ROI`]: calcROI({
1484
1539
  // pnl: Number(pnl ?? 0),
@@ -1666,6 +1721,7 @@ function tpslInputHandle(inputs) {
1666
1721
  // order price or mark price
1667
1722
  qty: values.side === OrderSide.BUY ? Number(values.order_quantity) : Number(values.order_quantity) * -1,
1668
1723
  orderSide: values.side,
1724
+ markPrice,
1669
1725
  // values: newValues,
1670
1726
  values
1671
1727
  },
@@ -1701,6 +1757,10 @@ var getCalculateHandler = (fieldName) => {
1701
1757
  case "sl_offset":
1702
1758
  case "tp_offset_percentage":
1703
1759
  case "sl_offset_percentage":
1760
+ case "tp_offset_from_mark":
1761
+ case "sl_offset_from_mark":
1762
+ case "tp_offset_percentage_from_mark":
1763
+ case "sl_offset_percentage_from_mark":
1704
1764
  case "tp_order_price":
1705
1765
  case "tp_order_type":
1706
1766
  case "sl_order_type":
@@ -2584,16 +2644,12 @@ var createDataStore = (config) => {
2584
2644
  const brokerIdQuery = typeof options?.brokerId === "string" && options?.brokerId !== "orderly" ? `?broker_id=${options?.brokerId}` : "";
2585
2645
  const url = `${dynamicBaseUrl || baseUrl || ""}${endpoint}${brokerIdQuery}`;
2586
2646
  const data = await fetcher(url, {}, { formatter });
2587
- const dataWithBrokerId = data.map((item) => ({
2588
- ...item,
2589
- broker_id: options?.brokerId
2590
- }));
2591
2647
  set({
2592
- data: dataWithBrokerId,
2648
+ data,
2593
2649
  loading: false,
2594
2650
  error: null
2595
2651
  });
2596
- return dataWithBrokerId;
2652
+ return data;
2597
2653
  } catch (error) {
2598
2654
  set({ error, loading: false });
2599
2655
  return null;
@@ -3129,7 +3185,9 @@ var DEFAULT_SYMBOL_DEPTHS = {
3129
3185
  };
3130
3186
  var DEFAULT_SYMBOL_DISPLAY_NAMES = {
3131
3187
  PERP_XAU_USDC: "XAU (Gold) ",
3132
- PERP_XAG_USDC: "XAG (Silver)"
3188
+ PERP_XAG_USDC: "XAG (Silver)",
3189
+ PERP_CL_USDC: "CL (WTI Crude Oil)",
3190
+ PERP_BZ_USDC: "BZ (Brent Crude Oil)"
3133
3191
  };
3134
3192
  var ProxyConfigStore = class {
3135
3193
  constructor(_originConfigStore) {
@@ -3412,7 +3470,10 @@ var useGetRwaSymbolOpenTimeInterval = (symbol, thresholdMinutes = 30) => {
3412
3470
  };
3413
3471
  var useSymbolsInfo = () => {
3414
3472
  const symbolsInfo = useAppStore((state) => state.symbolsInfo);
3415
- return useMemo(() => createGetter({ ...symbolsInfo }), [symbolsInfo]);
3473
+ return useMemo(
3474
+ () => createGetter(symbolsInfo ? { ...symbolsInfo } : symbolsInfo),
3475
+ [symbolsInfo]
3476
+ );
3416
3477
  };
3417
3478
  var useSymbolsInfoStore = () => {
3418
3479
  return useAppStore((state) => state.symbolsInfo);
@@ -3425,6 +3486,7 @@ var MarketsType = /* @__PURE__ */ ((MarketsType2) => {
3425
3486
  MarketsType2[MarketsType2["ALL"] = 2] = "ALL";
3426
3487
  MarketsType2[MarketsType2["RWA"] = 3] = "RWA";
3427
3488
  MarketsType2[MarketsType2["NEW_LISTING"] = 4] = "NEW_LISTING";
3489
+ MarketsType2[MarketsType2["COMMUNITY"] = 5] = "COMMUNITY";
3428
3490
  return MarketsType2;
3429
3491
  })(MarketsType || {});
3430
3492
  var MarketsStorageKey = "orderly_markets";
@@ -3594,6 +3656,8 @@ var addFieldToMarkets = (futures, symbolsInfo, rwaSymbolsInfo) => {
3594
3656
  const rwaInfo = !rwaSymbolsInfo.isNil ? rwaSymbolsInfo[item.symbol]() : null;
3595
3657
  return {
3596
3658
  ...item,
3659
+ broker_id: item.broker_id,
3660
+ display_symbol_name: item.display_symbol_name,
3597
3661
  quote_dp: info("quote_dp"),
3598
3662
  created_time: info("created_time"),
3599
3663
  displayName: info("displayName"),
@@ -3615,7 +3679,7 @@ var addFieldToMarkets = (futures, symbolsInfo, rwaSymbolsInfo) => {
3615
3679
  var filterMarkets = (params) => {
3616
3680
  const { markets, favorites, recent, newListing, type } = params;
3617
3681
  let curData = [];
3618
- if (type === 2 /* ALL */) {
3682
+ if (type === 2 /* ALL */ || type === 5 /* COMMUNITY */) {
3619
3683
  curData = markets;
3620
3684
  } else if (type === 3 /* RWA */) {
3621
3685
  curData = markets.filter((item) => item.isRwa);
@@ -4537,7 +4601,7 @@ var useMarket = (type) => {
4537
4601
  const getData = (type2) => {
4538
4602
  const localData = type2 === 0 /* FAVORITES */ ? [...favorites] : [...recent];
4539
4603
  const keys = localData.map((item) => item.name);
4540
- const filter = type2 == 2 /* ALL */ ? marketsList : marketsList?.filter((item) => keys.includes(item.symbol));
4604
+ const filter = type2 == 2 /* ALL */ || type2 == 4 /* COMMUNITY */ ? marketsList : marketsList?.filter((item) => keys.includes(item.symbol));
4541
4605
  const favoritesData = [...favorites];
4542
4606
  const favoriteKeys = favoritesData.map((item) => item.name);
4543
4607
  if (filter) {
@@ -4736,6 +4800,80 @@ var useSymbolLeverageMap = () => {
4736
4800
  refresh: mutate6
4737
4801
  };
4738
4802
  };
4803
+
4804
+ // src/trading-rewards/useAllBrokers.ts
4805
+ var useAllBrokers = () => {
4806
+ const { data } = useQuery("/v1/public/broker/name", {
4807
+ formatter: (res) => {
4808
+ const { rows } = res;
4809
+ return rows?.map((item) => ({ [item.broker_id]: item.broker_name })).reduce((acc, curr) => ({ ...acc, ...curr }), {});
4810
+ },
4811
+ revalidateOnFocus: false
4812
+ });
4813
+ return [data];
4814
+ };
4815
+
4816
+ // src/useBadgeBySymbol.ts
4817
+ function brokerNameBaseFromRaw(rawBrokerName) {
4818
+ if (!rawBrokerName) return void 0;
4819
+ const first = rawBrokerName.trim().split(/[ _-]/, 1)[0]?.trim() ?? "";
4820
+ return first.length > 0 ? first : void 0;
4821
+ }
4822
+ var useBadgeBySymbol = (symbol) => {
4823
+ const symbolsInfo = useSymbolsInfo();
4824
+ const [brokers] = useAllBrokers();
4825
+ return useMemo(() => {
4826
+ if (!symbol || symbolsInfo.isNil) {
4827
+ return {
4828
+ displayName: symbol ?? "",
4829
+ brokerId: void 0,
4830
+ brokerName: void 0,
4831
+ brokerNameRaw: void 0
4832
+ };
4833
+ }
4834
+ const getter = symbolsInfo[symbol];
4835
+ const info = typeof getter === "function" ? getter() : void 0;
4836
+ const displayName = info?.displayName ?? info?.display_symbol_name ?? symbol;
4837
+ const brokerId = info?.broker_id ?? void 0;
4838
+ const rawBrokerName = brokerId ? brokers?.[brokerId] : void 0;
4839
+ const base = brokerNameBaseFromRaw(rawBrokerName);
4840
+ const brokerName = base ? base.length > 7 ? `${base.slice(0, 7)}...` : base : void 0;
4841
+ return {
4842
+ displayName,
4843
+ brokerId,
4844
+ brokerName,
4845
+ brokerNameRaw: rawBrokerName
4846
+ };
4847
+ }, [brokers, symbolsInfo, symbol]);
4848
+ };
4849
+ function formatSymbolWithBroker(symbol, symbolsInfo, brokers) {
4850
+ if (!symbol) return "";
4851
+ let brokerNameBase;
4852
+ if (!symbolsInfo.isNil) {
4853
+ const getter = symbolsInfo[symbol];
4854
+ const info = typeof getter === "function" ? getter() : void 0;
4855
+ const brokerId = info?.broker_id ?? void 0;
4856
+ const rawBrokerName = brokerId ? brokers?.[brokerId] : void 0;
4857
+ brokerNameBase = brokerNameBaseFromRaw(rawBrokerName);
4858
+ }
4859
+ const parts = symbol.split("_");
4860
+ const base = parts.length >= 3 ? parts[1] ?? "" : symbol.match(/^([A-Za-z]+)/)?.[1] ?? symbol;
4861
+ const hasBrokerSuffix = symbol.includes("-") || symbol.split("_").length > 3;
4862
+ if (brokerNameBase && hasBrokerSuffix) {
4863
+ return `${base}-${brokerNameBase}`;
4864
+ }
4865
+ return base;
4866
+ }
4867
+ var useSymbolWithBroker = (symbol) => {
4868
+ const symbolsInfo = useSymbolsInfo();
4869
+ const [brokers] = useAllBrokers();
4870
+ return useMemo(
4871
+ () => formatSymbolWithBroker(symbol, symbolsInfo, brokers),
4872
+ [brokers, symbolsInfo, symbol]
4873
+ );
4874
+ };
4875
+
4876
+ // src/orderly/useMarginModes.ts
4739
4877
  var useMarginModes = () => {
4740
4878
  const { data, error, isLoading, mutate: mutate6 } = usePrivateQuery("/v1/client/margin_modes", {
4741
4879
  revalidateOnFocus: false,
@@ -4777,22 +4915,28 @@ var useMarginModes = () => {
4777
4915
  };
4778
4916
  var useMarginModeBySymbol = (symbol, fallback = MarginMode.CROSS) => {
4779
4917
  const { marginModes, isLoading, error, refresh, updateMarginMode } = useMarginModes();
4780
- const marginMode = fallback === null ? marginModes[symbol] : marginModes[symbol] ?? fallback;
4918
+ const { brokerId } = useBadgeBySymbol(symbol);
4919
+ const marginMode = useMemo(() => {
4920
+ if (brokerId) return MarginMode.ISOLATED;
4921
+ return fallback === null ? marginModes[symbol] : marginModes[symbol] ?? fallback;
4922
+ }, [brokerId, fallback, marginModes, symbol]);
4781
4923
  const update = useCallback(
4782
4924
  async (mode) => {
4925
+ if (brokerId) mode = MarginMode.ISOLATED;
4783
4926
  return updateMarginMode({
4784
4927
  symbol_list: [symbol],
4785
4928
  default_margin_mode: mode
4786
4929
  });
4787
4930
  },
4788
- [symbol, updateMarginMode]
4931
+ [brokerId, symbol, updateMarginMode]
4789
4932
  );
4790
4933
  return {
4791
4934
  marginMode,
4792
4935
  isLoading,
4793
4936
  error,
4794
4937
  refresh,
4795
- update
4938
+ update,
4939
+ isPermissionlessListing: !!brokerId
4796
4940
  };
4797
4941
  };
4798
4942
 
@@ -5031,6 +5175,11 @@ var MarkPriceCalculator = class extends BaseCalculator {
5031
5175
 
5032
5176
  // src/orderly/calculator/calculatorContext.ts
5033
5177
  var CalculatorContext = class _CalculatorContext {
5178
+ // holding: API.Holding[];
5179
+ // portfolio — dynamic getter to always read the latest output from PortfolioCalculator
5180
+ get portfolio() {
5181
+ return this.output["portfolio"] || useAppStore.getState().portfolio;
5182
+ }
5034
5183
  static get instance() {
5035
5184
  return this._instance;
5036
5185
  }
@@ -5049,7 +5198,6 @@ var CalculatorContext = class _CalculatorContext {
5049
5198
  update(scope, data) {
5050
5199
  this.setCtxData();
5051
5200
  this.markPrices = scope === "markPrice" /* MARK_PRICE */ ? data : this.output[MarketCalculatorName];
5052
- this.portfolio = this.output["portfolio"] || useAppStore.getState().portfolio;
5053
5201
  return this;
5054
5202
  }
5055
5203
  setCtxData() {
@@ -5067,7 +5215,6 @@ var CalculatorContext = class _CalculatorContext {
5067
5215
  clearCache() {
5068
5216
  this.output = {};
5069
5217
  this.accountInfo = void 0;
5070
- this.portfolio = void 0;
5071
5218
  }
5072
5219
  deleteByName(name) {
5073
5220
  delete this.output[name];
@@ -5435,7 +5582,7 @@ var PositionCalculator = class extends BaseCalculator {
5435
5582
  if (!accountInfo || !fundingRates || !symbolsInfo) {
5436
5583
  return data;
5437
5584
  }
5438
- let unrealPnL_total = zero, unrealPnL_total_index = zero, notional_total = zero, unsettlementPnL_total = zero;
5585
+ let unrealPnL_total = zero, unrealPnL_total_index = zero, notional_total = zero, unsettlementPnL_total = zero, totalUnsettledIsolatedPnl = zero, totalUnsettledCrossPnl = zero;
5439
5586
  let rows = data.rows.map((item) => {
5440
5587
  const info = symbolsInfo[item.symbol];
5441
5588
  const sum_unitary_funding = fundingRates?.[item.symbol]?.["sum_unitary_funding"] ?? 0;
@@ -5498,6 +5645,12 @@ var PositionCalculator = class extends BaseCalculator {
5498
5645
  unrealPnL_total_index = unrealPnL_total_index.add(unrealPnl_index);
5499
5646
  notional_total = notional_total.add(notional);
5500
5647
  unsettlementPnL_total = unsettlementPnL_total.add(unsettlementPnL2);
5648
+ if (item.margin_mode === MarginMode.CROSS) {
5649
+ totalUnsettledCrossPnl = totalUnsettledCrossPnl.add(unsettlementPnL2);
5650
+ }
5651
+ if (item.margin_mode === MarginMode.ISOLATED) {
5652
+ totalUnsettledIsolatedPnl = totalUnsettledIsolatedPnl.add(unsettlementPnL2);
5653
+ }
5501
5654
  const fundingFee = new Decimal(sum_unitary_funding).sub(item.last_sum_unitary_funding).mul(item.position_qty).negated().toNumber();
5502
5655
  return {
5503
5656
  ...item,
@@ -5513,7 +5666,8 @@ var PositionCalculator = class extends BaseCalculator {
5513
5666
  unrealized_pnl: unrealPnl,
5514
5667
  unrealized_pnl_index: unrealPnl_index,
5515
5668
  unrealized_pnl_ROI: unrealPnlROI,
5516
- unrealized_pnl_ROI_index: unrealPnlROI_index
5669
+ unrealized_pnl_ROI_index: unrealPnlROI_index,
5670
+ unsettled_pnl: unsettlementPnL2
5517
5671
  };
5518
5672
  });
5519
5673
  const totalUnrealPnl = unrealPnL_total.toNumber();
@@ -5525,18 +5679,34 @@ var PositionCalculator = class extends BaseCalculator {
5525
5679
  rows = rows.map((item) => {
5526
5680
  const info = symbolsInfo[item.symbol];
5527
5681
  const totalCollateral = item.margin_mode === MarginMode.ISOLATED ? new Decimal(item.margin ?? 0).add(item.unsettlement_pnl ?? 0).toNumber() : crossMarginCollateral.toNumber();
5528
- const est_liq_price = positions.liqPrice({
5529
- symbol: item.symbol,
5530
- markPrice: item.mark_price,
5531
- totalCollateral,
5532
- positionQty: item.position_qty,
5533
- positions: rows,
5534
- MMR: item.mmr,
5535
- baseMMR: info?.["base_mmr"],
5536
- baseIMR: info?.["base_imr"],
5537
- IMRFactor: accountInfo.imr_factor[item.symbol],
5538
- costPosition: item.cost_position
5539
- });
5682
+ let est_liq_price;
5683
+ if (item.margin_mode === MarginMode.ISOLATED) {
5684
+ est_liq_price = positions.liquidationPriceIsolated({
5685
+ isolatedPositionMargin: item.margin ?? 0,
5686
+ costPosition: item.cost_position ?? 0,
5687
+ positionQty: item.position_qty ?? 0,
5688
+ sumUnitaryFunding: fundingRates?.[item.symbol]?.["sum_unitary_funding"] ?? 0,
5689
+ lastSumUnitaryFunding: item.last_sum_unitary_funding ?? 0,
5690
+ baseMMR: info?.["base_mmr"] ?? 0,
5691
+ baseIMR: info?.["base_imr"] ?? 0,
5692
+ IMRFactor: accountInfo.imr_factor[item.symbol],
5693
+ referencePrice: item.mark_price,
5694
+ leverage: item.leverage ?? 0
5695
+ });
5696
+ } else {
5697
+ est_liq_price = positions.liqPrice({
5698
+ symbol: item.symbol,
5699
+ markPrice: item.mark_price,
5700
+ totalCollateral,
5701
+ positionQty: item.position_qty,
5702
+ positions: rows,
5703
+ MMR: item.mmr,
5704
+ baseMMR: info?.["base_mmr"],
5705
+ baseIMR: info?.["base_imr"],
5706
+ IMRFactor: accountInfo.imr_factor[item.symbol],
5707
+ costPosition: item.cost_position
5708
+ });
5709
+ }
5540
5710
  return {
5541
5711
  ...item,
5542
5712
  est_liq_price
@@ -5563,6 +5733,8 @@ var PositionCalculator = class extends BaseCalculator {
5563
5733
  total_unsettled_pnl: unsettlementPnL,
5564
5734
  unrealPnlROI: totalUnrealizedROI,
5565
5735
  unrealPnlROI_index: totalUnrealizedROI_index,
5736
+ total_unsettled_cross_pnl: totalUnsettledCrossPnl.toNumber(),
5737
+ total_unsettled_isolated_pnl: totalUnsettledIsolatedPnl.toNumber(),
5566
5738
  rows
5567
5739
  };
5568
5740
  }
@@ -5725,13 +5897,9 @@ var PortfolioCalculator = class extends BaseCalculator {
5725
5897
  if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !indexPrices || !accountInfo) {
5726
5898
  return null;
5727
5899
  }
5728
- const totallCrossUnsettledPnL = positions3.rows.reduce(
5729
- (sum, pos) => pos.margin_mode === MarginMode.ISOLATED ? sum : sum + (pos.unsettled_pnl ?? 0),
5730
- 0
5731
- );
5732
- const totalUnsettlementPnL = positions3.rows.reduce(
5733
- (sum, pos) => sum + (pos.unsettled_pnl ?? 0),
5734
- 0
5900
+ const unsettledPnL = pathOr(0, ["total_unsettled_pnl"])(positions3);
5901
+ const unsettledCrossPnL = pathOr(0, ["total_unsettled_cross_pnl"])(
5902
+ positions3
5735
5903
  );
5736
5904
  const unrealizedPnL = pathOr(0, ["total_unreal_pnl"])(positions3);
5737
5905
  const [USDC_holding, nonUSDC] = parseHolding(
@@ -5743,7 +5911,7 @@ var PortfolioCalculator = class extends BaseCalculator {
5743
5911
  const totalCollateral = account.totalCollateral({
5744
5912
  USDCHolding: USDC_holding,
5745
5913
  nonUSDCHolding: nonUSDC,
5746
- unsettlementPnL: totallCrossUnsettledPnL,
5914
+ unsettlementPnL: unsettledCrossPnL,
5747
5915
  usdcBalancePendingShortQty: usdc?.pending_short ?? 0,
5748
5916
  usdcBalanceIsolatedOrderFrozen: usdc?.isolated_order_frozen ?? 0
5749
5917
  });
@@ -5754,7 +5922,7 @@ var PortfolioCalculator = class extends BaseCalculator {
5754
5922
  return acc.add(curr.margin ?? 0);
5755
5923
  }, zero);
5756
5924
  const totalValue = account.totalValue({
5757
- totalUnsettlementPnL,
5925
+ totalUnsettlementPnL: unsettledPnL,
5758
5926
  USDCHolding: USDC_holding,
5759
5927
  nonUSDCHolding: nonUSDC,
5760
5928
  totalIsolatedPositionMargin: sumIsolatedMargin.toNumber()
@@ -5798,7 +5966,7 @@ var PortfolioCalculator = class extends BaseCalculator {
5798
5966
  totalUnrealizedROI,
5799
5967
  freeCollateral,
5800
5968
  availableBalance,
5801
- unsettledPnL: totalUnsettlementPnL,
5969
+ unsettledPnL,
5802
5970
  holding,
5803
5971
  usdcHolding: USDC_holding,
5804
5972
  freeCollateralUSDCOnly
@@ -5917,7 +6085,7 @@ var usePositionStream = (symbol = "all", options) => {
5917
6085
  total_unreal_pnl: total_unreal_pnl_index,
5918
6086
  unrealPnlROI: unrealPnlROI_index
5919
6087
  };
5920
- }, [calcMode]);
6088
+ }, [calcMode, formattedPositions]);
5921
6089
  let rows = formattedPositions[0];
5922
6090
  {
5923
6091
  if (!rows) {
@@ -6407,14 +6575,8 @@ function formatPortfolio(inputs) {
6407
6575
  if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !indexPrices || !accountInfo || symbolsInfo?.isNil) {
6408
6576
  return null;
6409
6577
  }
6410
- const totallCrossUnsettledPnL = positions3.rows.reduce(
6411
- (sum, pos) => pos.margin_mode === MarginMode.ISOLATED ? sum : sum + (pos.unsettled_pnl ?? 0),
6412
- 0
6413
- );
6414
- const totalUnsettlementPnL = positions3.rows.reduce(
6415
- (sum, pos) => sum + (pos.unsettled_pnl ?? 0),
6416
- 0
6417
- );
6578
+ const unsettledPnL = pathOr(0, ["total_unsettled_pnl"])(positions3);
6579
+ const unsettledCrossPnL = pathOr(0, ["total_unsettled_cross_pnl"])(positions3);
6418
6580
  const unrealizedPnL = pathOr(0, ["total_unreal_pnl"])(positions3);
6419
6581
  const [USDC_holding, nonUSDC] = parseHolding(
6420
6582
  holding,
@@ -6425,7 +6587,7 @@ function formatPortfolio(inputs) {
6425
6587
  const totalCollateral = account.totalCollateral({
6426
6588
  USDCHolding: USDC_holding,
6427
6589
  nonUSDCHolding: nonUSDC,
6428
- unsettlementPnL: totallCrossUnsettledPnL,
6590
+ unsettlementPnL: unsettledCrossPnL,
6429
6591
  usdcBalancePendingShortQty: usdc?.pending_short ?? 0,
6430
6592
  usdcBalanceIsolatedOrderFrozen: usdc?.isolated_order_frozen ?? 0
6431
6593
  });
@@ -6436,7 +6598,7 @@ function formatPortfolio(inputs) {
6436
6598
  return acc.add(curr.margin ?? 0);
6437
6599
  }, zero);
6438
6600
  const totalValue = account.totalValue({
6439
- totalUnsettlementPnL,
6601
+ totalUnsettlementPnL: unsettledPnL,
6440
6602
  USDCHolding: USDC_holding,
6441
6603
  nonUSDCHolding: nonUSDC,
6442
6604
  totalIsolatedPositionMargin: sumIsolatedMargin.toNumber()
@@ -6480,7 +6642,7 @@ function formatPortfolio(inputs) {
6480
6642
  totalUnrealizedROI,
6481
6643
  freeCollateral,
6482
6644
  availableBalance,
6483
- unsettledPnL: totalUnsettlementPnL,
6645
+ unsettledPnL,
6484
6646
  holding,
6485
6647
  freeCollateralUSDCOnly
6486
6648
  };
@@ -6489,7 +6651,7 @@ function formatPositions(data, accountInfo, symbolsInfo, fundingRates) {
6489
6651
  if (!accountInfo || !fundingRates || !symbolsInfo) {
6490
6652
  return data;
6491
6653
  }
6492
- let unrealPnL_total = zero, unrealPnL_total_index = zero, notional_total = zero, unsettlementPnL_total = zero;
6654
+ let unrealPnL_total = zero, unrealPnL_total_index = zero, notional_total = zero, unsettlementPnL_total = zero, totalUnsettledIsolatedPnl = zero, totalUnsettledCrossPnl = zero;
6493
6655
  const rows = data.rows.map((item) => {
6494
6656
  const info = symbolsInfo[item.symbol];
6495
6657
  const notional = positions.notional(item.position_qty, item.mark_price);
@@ -6551,6 +6713,12 @@ function formatPositions(data, accountInfo, symbolsInfo, fundingRates) {
6551
6713
  unrealPnL_total_index = unrealPnL_total_index.add(unrealPnl_index);
6552
6714
  notional_total = notional_total.add(notional);
6553
6715
  unsettlementPnL_total = unsettlementPnL_total.add(unsettlementPnL2);
6716
+ if (item.margin_mode === MarginMode.CROSS) {
6717
+ totalUnsettledCrossPnl = totalUnsettledCrossPnl.add(unsettlementPnL2);
6718
+ }
6719
+ if (item.margin_mode === MarginMode.ISOLATED) {
6720
+ totalUnsettledIsolatedPnl = totalUnsettledIsolatedPnl.add(unsettlementPnL2);
6721
+ }
6554
6722
  return {
6555
6723
  ...item,
6556
6724
  mm: positions.maintenanceMargin({
@@ -6564,7 +6732,8 @@ function formatPositions(data, accountInfo, symbolsInfo, fundingRates) {
6564
6732
  unrealized_pnl: unrealPnl,
6565
6733
  unrealized_pnl_index: unrealPnl_index,
6566
6734
  unrealized_pnl_ROI: unrealPnlROI,
6567
- unrealized_pnl_ROI_index: unrealPnlROI_index
6735
+ unrealized_pnl_ROI_index: unrealPnlROI_index,
6736
+ unsettled_pnl: unsettlementPnL2
6568
6737
  };
6569
6738
  });
6570
6739
  const totalUnrealPnl = unrealPnL_total.toNumber();
@@ -6578,6 +6747,8 @@ function formatPositions(data, accountInfo, symbolsInfo, fundingRates) {
6578
6747
  notional: notional_total.toNumber(),
6579
6748
  unsettledPnL: unsettlementPnL,
6580
6749
  total_unsettled_pnl: unsettlementPnL,
6750
+ total_unsettled_cross_pnl: totalUnsettledCrossPnl.toNumber(),
6751
+ total_unsettled_isolated_pnl: totalUnsettledIsolatedPnl.toNumber(),
6581
6752
  rows
6582
6753
  };
6583
6754
  }
@@ -7960,7 +8131,9 @@ var useDeposit = (options) => {
7960
8131
  const depositPromise = isNativeToken ? account9.assetsManager.depositNativeToken(inputs) : account9.assetsManager.deposit(inputs);
7961
8132
  return depositPromise.then((result) => {
7962
8133
  updateAllowanceWhenTxSuccess(result.hash);
7963
- setBalance((value) => new Decimal(value).sub(quantity).toString());
8134
+ setBalance(
8135
+ (value) => value ? new Decimal(value).sub(quantity).toString() : "0"
8136
+ );
7964
8137
  track2(TrackerEventName.depositSuccess, {
7965
8138
  wallet: state?.connectWallet?.name,
7966
8139
  network: targetChain?.network_infos.name,
@@ -8012,16 +8185,16 @@ var useDeposit = (options) => {
8012
8185
  };
8013
8186
  function useBalance(options) {
8014
8187
  const { srcToken, address, decimals, account: account9, status } = options;
8015
- const [balance, setBalance] = useState("0");
8188
+ const [balance, setBalance] = useState(null);
8016
8189
  const fetchBalance = useCallback(
8017
8190
  async (address2, decimals2) => {
8018
8191
  try {
8019
8192
  if (isNativeTokenChecker(address2)) {
8020
- return account9.assetsManager.getNativeBalance({
8193
+ return await account9.assetsManager.getNativeBalance({
8021
8194
  decimals: decimals2
8022
8195
  });
8023
8196
  }
8024
- return account9.assetsManager.getBalance(address2, {
8197
+ return await account9.assetsManager.getBalance(address2, {
8025
8198
  decimals: decimals2
8026
8199
  });
8027
8200
  } catch (err) {
@@ -8070,11 +8243,13 @@ function useBalance(options) {
8070
8243
  useEffect(() => {
8071
8244
  if (swrBalance !== void 0) {
8072
8245
  setBalance(swrBalance || "0");
8246
+ } else {
8247
+ setBalance(null);
8073
8248
  }
8074
- }, [swrBalance]);
8249
+ }, [swrBalance, address]);
8075
8250
  return {
8076
8251
  balance,
8077
- balanceRevalidating,
8252
+ balanceRevalidating: balanceRevalidating || balance === null,
8078
8253
  setBalance,
8079
8254
  fetchBalance,
8080
8255
  fetchBalances
@@ -9604,6 +9779,9 @@ var PriceValidationStrategy = class {
9604
9779
  }
9605
9780
  const price = new Decimal(order_price);
9606
9781
  const { symbol } = config;
9782
+ if (!symbol) {
9783
+ return;
9784
+ }
9607
9785
  const { quote_max, quote_min, quote_dp, price_range, price_scope } = symbol;
9608
9786
  const maxPriceNumber = order.maxPrice(config.markPrice, price_range);
9609
9787
  const minPriceNumber = order.minPrice(config.markPrice, price_range);
@@ -9650,6 +9828,9 @@ var TriggerPriceValidationStrategy = class {
9650
9828
  validate(values, config) {
9651
9829
  const { trigger_price } = values;
9652
9830
  const { symbol } = config;
9831
+ if (!symbol) {
9832
+ return;
9833
+ }
9653
9834
  const { quote_max, quote_min } = symbol;
9654
9835
  if (!trigger_price) {
9655
9836
  return OrderValidation.required("trigger_price");
@@ -9696,6 +9877,9 @@ var QuantityValidationStrategy = class {
9696
9877
  validate(values, config) {
9697
9878
  let { order_quantity, total, order_price } = values;
9698
9879
  const { maxQty, symbol } = config;
9880
+ if (!symbol) {
9881
+ return;
9882
+ }
9699
9883
  const { base_min, base_dp, quote_dp } = symbol;
9700
9884
  if (!order_quantity && total && order_price) {
9701
9885
  const totalNumber = new Decimal(total);
@@ -10896,7 +11080,11 @@ var tpslFields = [
10896
11080
  "tp_offset",
10897
11081
  "sl_offset",
10898
11082
  "tp_offset_percentage",
10899
- "sl_offset_percentage"
11083
+ "sl_offset_percentage",
11084
+ "tp_offset_from_mark",
11085
+ "sl_offset_from_mark",
11086
+ "tp_offset_percentage_from_mark",
11087
+ "sl_offset_percentage_from_mark"
10900
11088
  ];
10901
11089
  var isBracketOrder = (order) => {
10902
11090
  return !!order.tp_trigger_price || !!order.sl_trigger_price;
@@ -10951,7 +11139,7 @@ var calcEstLiqPrice = (order$1, askAndBid, inputs) => {
10951
11139
  totalCollateral,
10952
11140
  futures_taker_fee_rate,
10953
11141
  positions: positions3,
10954
- // leverage,
11142
+ symbolLeverage,
10955
11143
  sumUnitaryFunding
10956
11144
  } = inputs;
10957
11145
  const orderFee = order.orderFee({
@@ -10976,7 +11164,7 @@ var calcEstLiqPrice = (order$1, askAndBid, inputs) => {
10976
11164
  }
10977
11165
  });
10978
11166
  } else {
10979
- let isolatedPositionMargin = 0, costPosition = 0, positionQty = 0, lastSumUnitaryFunding = 0, leverage = 1;
11167
+ let isolatedPositionMargin = 0, costPosition = 0, positionQty = 0, lastSumUnitaryFunding = 0, leverage = symbolLeverage ?? 1;
10980
11168
  if (positions3) {
10981
11169
  const position = positions3.find(
10982
11170
  (p) => p.symbol === symbol && p.margin_mode === MarginMode.ISOLATED
@@ -11112,6 +11300,8 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
11112
11300
  entryPrice: position.average_open_price,
11113
11301
  qty: side === OrderSide.BUY ? Number(prev.quantity) : -Number(prev.quantity),
11114
11302
  orderSide: side,
11303
+ markPrice: markPrice ?? position.average_open_price,
11304
+ // use mark price as the default value
11115
11305
  values: prev
11116
11306
  },
11117
11307
  {
@@ -12666,6 +12856,12 @@ var DataPaint = class extends BasePaint {
12666
12856
  this.DEFAULT_LOSS_COLOR = "rgb(255,103,194)";
12667
12857
  this.transformTop = 0;
12668
12858
  this.QRCODE_SIZE = 56;
12859
+ this.BROKER_BADGE_HEIGHT = 18;
12860
+ this.BROKER_BADGE_PADDING_X = 8;
12861
+ this.BROKER_BADGE_RADIUS = 4;
12862
+ }
12863
+ formatMarginMode(marginMode) {
12864
+ return marginMode === MarginMode.ISOLATED ? "Isolated" : "Cross";
12669
12865
  }
12670
12866
  async draw(options) {
12671
12867
  const needDrawDetails = Array.isArray(options.data?.position?.informations) && (options.data?.position?.informations?.length ?? 0) > 0;
@@ -12752,6 +12948,49 @@ var DataPaint = class extends BasePaint {
12752
12948
  fontSize: this._ratio(fontSize),
12753
12949
  fontFamily: options.fontFamily
12754
12950
  });
12951
+ const brokerName = options.data?.position.brokerName?.trim();
12952
+ if (brokerName) {
12953
+ left += (prevElementBoundingBox.width ?? 0) + this._ratio(10);
12954
+ const badgeHeight = this._ratio(this.BROKER_BADGE_HEIGHT);
12955
+ const badgePaddingX = this._ratio(this.BROKER_BADGE_PADDING_X);
12956
+ const badgeRadius = this._ratio(this.BROKER_BADGE_RADIUS);
12957
+ const badgeFontSize = this._ratio(12);
12958
+ const badgeFontWeight = 600;
12959
+ const textMetrics = this._drawText(
12960
+ brokerName,
12961
+ {
12962
+ left: 0,
12963
+ top: 0,
12964
+ fontSize: badgeFontSize,
12965
+ fontWeight: badgeFontWeight,
12966
+ fontFamily: options.fontFamily
12967
+ },
12968
+ true
12969
+ );
12970
+ const badgeWidth = (textMetrics.width ?? 0) + badgePaddingX * 2;
12971
+ const badgeTop = this._ratio(top) - badgeHeight / 2;
12972
+ this._fillRoundedRect(
12973
+ left,
12974
+ badgeTop,
12975
+ badgeWidth,
12976
+ badgeHeight,
12977
+ badgeRadius,
12978
+ "rgba(255,255,255,0.06)"
12979
+ );
12980
+ this._drawText(brokerName, {
12981
+ color: "rgba(255,255,255,0.36)",
12982
+ left: left + badgePaddingX,
12983
+ top: badgeTop + badgeHeight / 2,
12984
+ fontSize: badgeFontSize,
12985
+ fontWeight: badgeFontWeight,
12986
+ fontFamily: options.fontFamily,
12987
+ textBaseline: "middle"
12988
+ });
12989
+ prevElementBoundingBox = {
12990
+ ...prevElementBoundingBox,
12991
+ width: badgeWidth
12992
+ };
12993
+ }
12755
12994
  }
12756
12995
  const marginMode = options.data?.position.marginMode;
12757
12996
  if (marginMode) {
@@ -12766,7 +13005,7 @@ var DataPaint = class extends BasePaint {
12766
13005
  });
12767
13006
  }
12768
13007
  left += (prevElementBoundingBox.width ?? 0) + this._ratio(7);
12769
- const marginModeText = marginMode.charAt(0).toUpperCase() + marginMode.slice(1);
13008
+ const marginModeText = this.formatMarginMode(marginMode);
12770
13009
  prevElementBoundingBox = this._drawText(marginModeText, {
12771
13010
  color: layout.color,
12772
13011
  left,
@@ -12799,6 +13038,20 @@ var DataPaint = class extends BasePaint {
12799
13038
  );
12800
13039
  }
12801
13040
  }
13041
+ _fillRoundedRect(x, y, width, height, radius, color) {
13042
+ const r = Math.min(radius, width / 2, height / 2);
13043
+ this.ctx.save();
13044
+ this.ctx.fillStyle = color;
13045
+ this.ctx.beginPath();
13046
+ this.ctx.moveTo(x + r, y);
13047
+ this.ctx.arcTo(x + width, y, x + width, y + height, r);
13048
+ this.ctx.arcTo(x + width, y + height, x, y + height, r);
13049
+ this.ctx.arcTo(x, y + height, x, y, r);
13050
+ this.ctx.arcTo(x, y, x + width, y, r);
13051
+ this.ctx.closePath();
13052
+ this.ctx.fill();
13053
+ this.ctx.restore();
13054
+ }
12802
13055
  drawUnrealizedPnL(options, offsetTop = 0) {
12803
13056
  const layout = path(
12804
13057
  ["layout", "unrealizedPnl"],
@@ -13252,18 +13505,6 @@ var useEpochInfo = (type) => {
13252
13505
  }, [epochInfo]);
13253
13506
  return [epochInfo, { isLoading, curEpochInfo, isNotStared, refresh }];
13254
13507
  };
13255
-
13256
- // src/trading-rewards/useAllBrokers.ts
13257
- var useAllBrokers = () => {
13258
- const { data } = useQuery("/v1/public/broker/name", {
13259
- formatter: (res) => {
13260
- const { rows } = res;
13261
- return rows?.map((item) => ({ [item.broker_id]: item.broker_name })).reduce((acc, curr) => ({ ...acc, ...curr }), {});
13262
- },
13263
- revalidateOnFocus: false
13264
- });
13265
- return [data];
13266
- };
13267
13508
  var useCurEpochEstimate = (type) => {
13268
13509
  const [data, setData] = useState(void 0);
13269
13510
  const { account: account9 } = useAccount();
@@ -18399,108 +18640,69 @@ var initialOrderState = {
18399
18640
  tp_trigger_price: "",
18400
18641
  sl_trigger_price: "",
18401
18642
  total: "",
18402
- symbol: ""
18643
+ symbol: "",
18644
+ side: OrderSide.BUY,
18645
+ order_type: OrderType.LIMIT,
18646
+ margin_mode: MarginMode.CROSS
18403
18647
  };
18404
- var useOrderStore = create()(
18405
- immer((set, get3) => ({
18406
- entry: {
18407
- side: OrderSide.BUY,
18408
- order_type: OrderType.LIMIT,
18409
- ...initialOrderState
18410
- },
18411
- estLeverage: null,
18412
- estLiquidationPrice: null,
18413
- errors: {},
18414
- actions: {
18415
- initOrder: (symbol, options) => {
18416
- set((state) => {
18417
- state.entry = {
18418
- ...initialOrderState,
18419
- symbol,
18420
- side: options?.side ?? OrderSide.BUY,
18421
- order_type: options?.order_type ?? OrderType.LIMIT,
18422
- margin_mode: options?.margin_mode ?? MarginMode.CROSS
18423
- };
18424
- state.estLeverage = null;
18425
- state.estLiquidationPrice = null;
18426
- state.errors = {};
18648
+ var useOrderEntryNextInternal = (symbol, options = {}) => {
18649
+ const { symbolInfo, symbolLeverage } = options;
18650
+ const [orderEntity, setOrderEntity] = useState(
18651
+ () => ({
18652
+ ...initialOrderState,
18653
+ ...options.initialOrder,
18654
+ symbol
18655
+ })
18656
+ );
18657
+ const actions = useMemo(
18658
+ () => ({
18659
+ initOrder: (sym, opts) => {
18660
+ setOrderEntity({
18661
+ ...initialOrderState,
18662
+ symbol: sym,
18663
+ side: opts?.side ?? OrderSide.BUY,
18664
+ order_type: opts?.order_type ?? OrderType.LIMIT,
18665
+ margin_mode: opts?.margin_mode ?? MarginMode.CROSS
18427
18666
  });
18428
18667
  },
18429
- hasTP_SL: () => {
18430
- const order = get3().entry;
18431
- return typeof order.tp_trigger_price !== "undefined" || typeof order.sl_trigger_price !== "undefined";
18432
- },
18433
- updateOrderComputed: (data) => {
18434
- set(
18435
- (state) => {
18436
- state.estLeverage = data.estLeverage;
18437
- state.estLiquidationPrice = data.estLiquidationPrice;
18438
- },
18439
- false
18440
- // "updateOrderComputed"
18441
- );
18442
- },
18443
18668
  updateOrder: (order) => {
18444
- set(
18445
- (state) => {
18446
- state.entry = {
18447
- ...state.entry,
18448
- ...order
18449
- };
18450
- },
18451
- false
18452
- // "updateOrder"
18453
- );
18669
+ setOrderEntity((prev) => ({ ...prev, ...order }));
18454
18670
  },
18455
18671
  updateOrderByKey: (key, value) => {
18456
- set(
18457
- (state) => {
18458
- state.entry[key] = value;
18459
- },
18460
- false
18461
- // "updateOrderByKey"
18462
- );
18463
- },
18464
- restoreOrder: (order) => {
18465
- set(
18466
- (state) => {
18467
- state.entry = order;
18468
- },
18469
- false
18470
- // "restoreOrder"
18471
- );
18672
+ setOrderEntity((prev) => ({ ...prev, [key]: value }));
18472
18673
  },
18473
18674
  resetOrder: (_order) => {
18474
- set(
18475
- (state) => {
18476
- state.entry.order_price = "";
18477
- state.entry.order_quantity = "";
18478
- state.entry.trigger_price = "";
18479
- state.entry.total = "";
18480
- state.entry.tp_trigger_price = "";
18481
- state.entry.tp_pnl = "";
18482
- state.entry.tp_offset = "";
18483
- state.entry.tp_offset_percentage = "";
18484
- state.entry.sl_trigger_price = "";
18485
- state.entry.sl_pnl = "";
18486
- state.entry.sl_offset = "";
18487
- state.entry.sl_offset_percentage = "";
18488
- },
18489
- true
18490
- // "resetOrder"
18491
- );
18675
+ setOrderEntity((prev) => ({
18676
+ ...prev,
18677
+ order_price: "",
18678
+ order_quantity: "",
18679
+ trigger_price: "",
18680
+ total: "",
18681
+ tp_trigger_price: "",
18682
+ tp_pnl: "",
18683
+ tp_offset: "",
18684
+ tp_offset_percentage: "",
18685
+ tp_offset_from_mark: "",
18686
+ tp_offset_percentage_from_mark: "",
18687
+ sl_trigger_price: "",
18688
+ sl_pnl: "",
18689
+ sl_offset: "",
18690
+ sl_offset_percentage: "",
18691
+ sl_offset_from_mark: "",
18692
+ sl_offset_percentage_from_mark: ""
18693
+ }));
18694
+ },
18695
+ hasTP_SL: () => {
18696
+ const order = orderEntity;
18697
+ return typeof order.tp_trigger_price !== "undefined" || typeof order.sl_trigger_price !== "undefined";
18492
18698
  }
18493
- }
18494
- }))
18495
- );
18496
- var useOrderEntryNextInternal = (symbol, options = {}) => {
18497
- const { symbolInfo, symbolLeverage } = options;
18498
- const orderEntity = useOrderStore((state) => state.entry);
18499
- const orderEntryActions = useOrderStore((state) => state.actions);
18699
+ }),
18700
+ [orderEntity]
18701
+ );
18500
18702
  useEffect(() => {
18501
- orderEntryActions.initOrder(symbol, options.initialOrder);
18703
+ actions.initOrder(symbol, options.initialOrder);
18502
18704
  if (options.initialOrder) {
18503
- orderEntryActions.updateOrder(options.initialOrder);
18705
+ actions.updateOrder(options.initialOrder);
18504
18706
  }
18505
18707
  }, [symbol]);
18506
18708
  const calculate2 = useCallback(
@@ -18518,10 +18720,10 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18518
18720
  );
18519
18721
  const setValue = (key, value, additional) => {
18520
18722
  if (!symbolInfo) {
18521
- orderEntryActions.updateOrderByKey(key, value);
18723
+ actions.updateOrderByKey(key, value);
18522
18724
  return;
18523
18725
  }
18524
- const currentEntry = useOrderStore.getState().entry;
18726
+ const currentEntry = orderEntity;
18525
18727
  const { markPrice } = additional ?? { markPrice: 0 };
18526
18728
  let newValues = calculate2(
18527
18729
  { ...currentEntry },
@@ -18555,7 +18757,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18555
18757
  if (sl_ROI) {
18556
18758
  newValues.sl_ROI = sl_ROI;
18557
18759
  }
18558
- orderEntryActions.updateOrder(newValues);
18760
+ actions.updateOrder(newValues);
18559
18761
  return newValues;
18560
18762
  };
18561
18763
  const calculateTPSL = (key, newValues, markPrice, symbolInfo2) => {
@@ -18578,6 +18780,42 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18578
18780
  symbolInfo2
18579
18781
  );
18580
18782
  }
18783
+ if (newValues.tp_offset_from_mark !== void 0 && newValues.tp_offset_from_mark !== "") {
18784
+ newValues = calculate2(
18785
+ newValues,
18786
+ "tp_offset_from_mark",
18787
+ newValues.tp_offset_from_mark,
18788
+ markPrice,
18789
+ symbolInfo2
18790
+ );
18791
+ }
18792
+ if (newValues.tp_offset_percentage_from_mark !== void 0 && newValues.tp_offset_percentage_from_mark !== "") {
18793
+ newValues = calculate2(
18794
+ newValues,
18795
+ "tp_offset_percentage_from_mark",
18796
+ newValues.tp_offset_percentage_from_mark,
18797
+ markPrice,
18798
+ symbolInfo2
18799
+ );
18800
+ }
18801
+ if (newValues.sl_offset_from_mark !== void 0 && newValues.sl_offset_from_mark !== "") {
18802
+ newValues = calculate2(
18803
+ newValues,
18804
+ "sl_offset_from_mark",
18805
+ newValues.sl_offset_from_mark,
18806
+ markPrice,
18807
+ symbolInfo2
18808
+ );
18809
+ }
18810
+ if (newValues.sl_offset_percentage_from_mark !== void 0 && newValues.sl_offset_percentage_from_mark !== "") {
18811
+ newValues = calculate2(
18812
+ newValues,
18813
+ "sl_offset_percentage_from_mark",
18814
+ newValues.sl_offset_percentage_from_mark,
18815
+ markPrice,
18816
+ symbolInfo2
18817
+ );
18818
+ }
18581
18819
  } else {
18582
18820
  if (typeof newValues.tp_trigger_price !== "undefined") {
18583
18821
  newValues = calculate2(
@@ -18597,16 +18835,51 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18597
18835
  symbolInfo2
18598
18836
  );
18599
18837
  }
18838
+ if (newValues.tp_offset_from_mark !== void 0 && newValues.tp_offset_from_mark !== "") {
18839
+ newValues = calculate2(
18840
+ newValues,
18841
+ "tp_offset_from_mark",
18842
+ newValues.tp_offset_from_mark,
18843
+ markPrice,
18844
+ symbolInfo2
18845
+ );
18846
+ }
18847
+ if (newValues.tp_offset_percentage_from_mark !== void 0 && newValues.tp_offset_percentage_from_mark !== "") {
18848
+ newValues = calculate2(
18849
+ newValues,
18850
+ "tp_offset_percentage_from_mark",
18851
+ newValues.tp_offset_percentage_from_mark,
18852
+ markPrice,
18853
+ symbolInfo2
18854
+ );
18855
+ }
18856
+ if (newValues.sl_offset_from_mark !== void 0 && newValues.sl_offset_from_mark !== "") {
18857
+ newValues = calculate2(
18858
+ newValues,
18859
+ "sl_offset_from_mark",
18860
+ newValues.sl_offset_from_mark,
18861
+ markPrice,
18862
+ symbolInfo2
18863
+ );
18864
+ }
18865
+ if (newValues.sl_offset_percentage_from_mark !== void 0 && newValues.sl_offset_percentage_from_mark !== "") {
18866
+ newValues = calculate2(
18867
+ newValues,
18868
+ "sl_offset_percentage_from_mark",
18869
+ newValues.sl_offset_percentage_from_mark,
18870
+ markPrice,
18871
+ symbolInfo2
18872
+ );
18873
+ }
18600
18874
  }
18601
18875
  return newValues;
18602
18876
  };
18603
18877
  const setValues = (values, additional) => {
18604
18878
  if (!symbolInfo) {
18605
- orderEntryActions.updateOrder(values);
18879
+ actions.updateOrder(values);
18606
18880
  return;
18607
18881
  }
18608
- const currentEntry = useOrderStore.getState().entry;
18609
- let newValues = { ...currentEntry };
18882
+ let newValues = { ...orderEntity };
18610
18883
  Object.keys(values).forEach((key) => {
18611
18884
  newValues = calculate2(
18612
18885
  newValues,
@@ -18616,17 +18889,28 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18616
18889
  symbolInfo
18617
18890
  );
18618
18891
  });
18619
- orderEntryActions.updateOrder(newValues);
18892
+ actions.updateOrder(newValues);
18893
+ return newValues;
18894
+ };
18895
+ const setValuesRaw = (values) => {
18896
+ if (!symbolInfo) {
18897
+ actions.updateOrder(values);
18898
+ return;
18899
+ }
18900
+ const newValues = {
18901
+ ...orderEntity,
18902
+ ...values
18903
+ };
18904
+ actions.updateOrder(newValues);
18620
18905
  return newValues;
18621
18906
  };
18622
18907
  const onMarkPriceUpdated = useCallback(
18623
18908
  (markPrice, baseOn = []) => {
18624
18909
  if (!options.symbolInfo) return;
18625
- const currentEntry = useOrderStore.getState().entry;
18626
- let newValues = { ...currentEntry };
18910
+ let newValues = { ...orderEntity };
18627
18911
  if (baseOn.length === 0) {
18628
18912
  newValues = calculate2(
18629
- { ...currentEntry },
18913
+ { ...orderEntity },
18630
18914
  "order_price",
18631
18915
  markPrice,
18632
18916
  markPrice,
@@ -18637,7 +18921,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18637
18921
  newValues = calculate2(
18638
18922
  { ...newValues },
18639
18923
  key,
18640
- currentEntry[key],
18924
+ orderEntity[key],
18641
18925
  markPrice,
18642
18926
  options.symbolInfo
18643
18927
  );
@@ -18656,9 +18940,9 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18656
18940
  newValues.sl_ROI = sl_ROI;
18657
18941
  }
18658
18942
  }
18659
- orderEntryActions.updateOrder(newValues);
18943
+ actions.updateOrder(newValues);
18660
18944
  },
18661
- [calculate2, options.symbolInfo, orderEntryActions]
18945
+ [calculate2, options.symbolInfo, symbolLeverage, orderEntity]
18662
18946
  );
18663
18947
  const validate = (order, creator, options2) => {
18664
18948
  return creator?.validate(order, {
@@ -18676,12 +18960,13 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18676
18960
  const submitOrder = useCallback(() => {
18677
18961
  }, [orderEntity]);
18678
18962
  const resetOrder = (order) => {
18679
- orderEntryActions.resetOrder(order);
18963
+ actions.resetOrder(order);
18680
18964
  };
18681
18965
  return {
18682
18966
  formattedOrder: orderEntity,
18683
18967
  setValue,
18684
18968
  setValues,
18969
+ setValuesRaw,
18685
18970
  submit: submitOrder,
18686
18971
  reset: resetOrder,
18687
18972
  generateOrder,
@@ -18697,6 +18982,8 @@ var useOrderEntry2 = (symbol, options = {}) => {
18697
18982
  }
18698
18983
  const ee = useEventEmitter();
18699
18984
  const { track: track2 } = useTrack();
18985
+ const apiBaseUrl = useConfig("apiBaseUrl");
18986
+ const fetchSymbols = useSymbolStore((state) => state.fetchData);
18700
18987
  const [meta, setMeta] = useState({
18701
18988
  dirty: {},
18702
18989
  submitted: false,
@@ -18716,8 +19003,7 @@ var useOrderEntry2 = (symbol, options = {}) => {
18716
19003
  const symbolConfig = useSymbolsInfo();
18717
19004
  const accountInfo = useAccountInfo();
18718
19005
  const positions3 = usePositions();
18719
- const entry = useOrderStore((s) => s.entry);
18720
- const effectiveMarginMode = options?.initialOrder?.margin_mode ?? entry?.margin_mode ?? MarginMode.CROSS;
19006
+ const effectiveMarginMode = options?.initialOrder?.margin_mode ?? MarginMode.CROSS;
18721
19007
  const symbolLeverage = useLeverageBySymbol(symbol, effectiveMarginMode);
18722
19008
  const symbolInfo = symbolConfig[symbol]();
18723
19009
  const markPrice = actions.getMarkPriceBySymbol(symbol);
@@ -18726,6 +19012,7 @@ var useOrderEntry2 = (symbol, options = {}) => {
18726
19012
  formattedOrder,
18727
19013
  setValue: setValueInternal,
18728
19014
  setValues: setValuesInternal,
19015
+ setValuesRaw: setValuesRawInternal,
18729
19016
  validate,
18730
19017
  generateOrder,
18731
19018
  reset,
@@ -18950,6 +19237,21 @@ var useOrderEntry2 = (symbol, options = {}) => {
18950
19237
  interactiveValidate(newValues);
18951
19238
  }
18952
19239
  };
19240
+ const setValuesRaw = (values) => {
19241
+ if (!Object.keys(values).every(
19242
+ (key) => canSetTPSLPrice(
19243
+ key,
19244
+ values[key],
19245
+ formattedOrder.order_type
19246
+ )
19247
+ )) {
19248
+ return;
19249
+ }
19250
+ const newValues = setValuesRawInternal(values);
19251
+ if (newValues) {
19252
+ interactiveValidate(newValues);
19253
+ }
19254
+ };
18953
19255
  async function validateFunc(order) {
18954
19256
  const creator = getOrderCreator(order);
18955
19257
  return validate(order, creator, prepareData());
@@ -19004,11 +19306,12 @@ var useOrderEntry2 = (symbol, options = {}) => {
19004
19306
  markPrice: markPrice2,
19005
19307
  totalCollateral,
19006
19308
  futures_taker_fee_rate: accountInfo.futures_taker_fee_rate,
19007
- imr_factor: accountInfo.imr_factor[symbol],
19309
+ imr_factor: accountInfo.imr_factor?.[symbol] ?? 0,
19008
19310
  symbol,
19009
19311
  positions: positions3,
19010
19312
  symbolInfo,
19011
- sumUnitaryFunding
19313
+ sumUnitaryFunding,
19314
+ symbolLeverage
19012
19315
  });
19013
19316
  return estLiqPrice2;
19014
19317
  }, [
@@ -19019,7 +19322,8 @@ var useOrderEntry2 = (symbol, options = {}) => {
19019
19322
  symbol,
19020
19323
  maxQty,
19021
19324
  symbolInfo,
19022
- fundingRates
19325
+ fundingRates,
19326
+ symbolLeverage
19023
19327
  ]);
19024
19328
  const estLiqPriceDistance = useMemo(() => {
19025
19329
  if (!estLiqPrice) {
@@ -19091,6 +19395,9 @@ var useOrderEntry2 = (symbol, options = {}) => {
19091
19395
  orders: appendOrderMetadata(order.orders, orderMetadata)
19092
19396
  } : appendOrderMetadata(order, orderMetadata);
19093
19397
  const result = await doCreateOrder(params);
19398
+ if (!result.success && (order.order_type === OrderType.MARKET || order.order_type === OrderType.STOP_MARKET)) {
19399
+ void fetchSymbols(apiBaseUrl);
19400
+ }
19094
19401
  if (result.success) {
19095
19402
  let trackParams = {
19096
19403
  side: order.side,
@@ -19158,6 +19465,7 @@ var useOrderEntry2 = (symbol, options = {}) => {
19158
19465
  freeCollateral: effectiveMarginMode === MarginMode.ISOLATED ? freeCollateralUSDCOnly : freeCollateral,
19159
19466
  setValue: useMemoizedFn(setValue),
19160
19467
  setValues: useMemoizedFn(setValues),
19468
+ setValuesRaw: useMemoizedFn(setValuesRaw),
19161
19469
  symbolInfo: symbolInfo || EMPTY_OBJECT,
19162
19470
  metaState: meta,
19163
19471
  isMutating,
@@ -19165,6 +19473,107 @@ var useOrderEntry2 = (symbol, options = {}) => {
19165
19473
  symbolLeverage
19166
19474
  };
19167
19475
  };
19476
+ var initialOrderState2 = {
19477
+ order_price: "",
19478
+ order_quantity: "",
19479
+ trigger_price: "",
19480
+ tp_trigger_price: "",
19481
+ sl_trigger_price: "",
19482
+ total: "",
19483
+ symbol: ""
19484
+ };
19485
+ var useOrderStore = create()(
19486
+ immer((set, get3) => ({
19487
+ entry: {
19488
+ side: OrderSide.BUY,
19489
+ order_type: OrderType.LIMIT,
19490
+ ...initialOrderState2
19491
+ },
19492
+ estLeverage: null,
19493
+ estLiquidationPrice: null,
19494
+ errors: {},
19495
+ actions: {
19496
+ initOrder: (symbol, options) => {
19497
+ set((state) => {
19498
+ state.entry = {
19499
+ ...initialOrderState2,
19500
+ symbol,
19501
+ side: options?.side ?? OrderSide.BUY,
19502
+ order_type: options?.order_type ?? OrderType.LIMIT,
19503
+ margin_mode: options?.margin_mode ?? MarginMode.CROSS
19504
+ };
19505
+ state.estLeverage = null;
19506
+ state.estLiquidationPrice = null;
19507
+ state.errors = {};
19508
+ });
19509
+ },
19510
+ hasTP_SL: () => {
19511
+ const order = get3().entry;
19512
+ return typeof order.tp_trigger_price !== "undefined" || typeof order.sl_trigger_price !== "undefined";
19513
+ },
19514
+ updateOrderComputed: (data) => {
19515
+ set(
19516
+ (state) => {
19517
+ state.estLeverage = data.estLeverage;
19518
+ state.estLiquidationPrice = data.estLiquidationPrice;
19519
+ },
19520
+ false
19521
+ // "updateOrderComputed"
19522
+ );
19523
+ },
19524
+ updateOrder: (order) => {
19525
+ set(
19526
+ (state) => {
19527
+ state.entry = {
19528
+ ...state.entry,
19529
+ ...order
19530
+ };
19531
+ },
19532
+ false
19533
+ // "updateOrder"
19534
+ );
19535
+ },
19536
+ updateOrderByKey: (key, value) => {
19537
+ set(
19538
+ (state) => {
19539
+ state.entry[key] = value;
19540
+ },
19541
+ false
19542
+ // "updateOrderByKey"
19543
+ );
19544
+ },
19545
+ restoreOrder: (order) => {
19546
+ set(
19547
+ (state) => {
19548
+ state.entry = order;
19549
+ },
19550
+ false
19551
+ // "restoreOrder"
19552
+ );
19553
+ },
19554
+ resetOrder: (_order) => {
19555
+ set(
19556
+ (state) => {
19557
+ state.entry.order_price = "";
19558
+ state.entry.order_quantity = "";
19559
+ state.entry.trigger_price = "";
19560
+ state.entry.total = "";
19561
+ state.entry.tp_trigger_price = "";
19562
+ state.entry.tp_pnl = "";
19563
+ state.entry.tp_offset = "";
19564
+ state.entry.tp_offset_percentage = "";
19565
+ state.entry.sl_trigger_price = "";
19566
+ state.entry.sl_pnl = "";
19567
+ state.entry.sl_offset = "";
19568
+ state.entry.sl_offset_percentage = "";
19569
+ },
19570
+ true
19571
+ // "resetOrder"
19572
+ );
19573
+ }
19574
+ }
19575
+ }))
19576
+ );
19168
19577
  var useOrderEntity = (order, options) => {
19169
19578
  const { symbol } = order;
19170
19579
  const { maxQty } = options || {};
@@ -19441,6 +19850,7 @@ var useTpslPriceChecker = (params) => {
19441
19850
  slPrice,
19442
19851
  liqPrice,
19443
19852
  side,
19853
+ markPrice,
19444
19854
  currentPosition,
19445
19855
  orderQuantity
19446
19856
  } = params;
@@ -19496,6 +19906,17 @@ var useTpslPriceChecker = (params) => {
19496
19906
  if (slPrice === void 0 || liqPrice === void 0 || side === void 0 || liqPrice === null) {
19497
19907
  return null;
19498
19908
  }
19909
+ if (markPrice != null && Number.isFinite(markPrice) && markPrice > 0) {
19910
+ if (side === OrderSide.BUY && liqPrice > markPrice) {
19911
+ return null;
19912
+ }
19913
+ if (side === OrderSide.SELL && liqPrice < markPrice) {
19914
+ return null;
19915
+ }
19916
+ }
19917
+ if (typeof liqPrice === "number" && (!Number.isFinite(liqPrice) || liqPrice <= 0)) {
19918
+ return null;
19919
+ }
19499
19920
  let slPriceDecimal;
19500
19921
  let liqPriceDecimal;
19501
19922
  try {
@@ -19522,6 +19943,7 @@ var useTpslPriceChecker = (params) => {
19522
19943
  slPrice,
19523
19944
  liqPrice,
19524
19945
  side,
19946
+ markPrice,
19525
19947
  warning_threshold,
19526
19948
  currentPosition,
19527
19949
  orderQuantity
@@ -19614,6 +20036,6 @@ var FlagKeys = /* @__PURE__ */ ((FlagKeys2) => {
19614
20036
  return FlagKeys2;
19615
20037
  })(FlagKeys || {});
19616
20038
 
19617
- export { DefaultLayoutConfig, DistributionId, ENVType2 as ENVType, ERROR_MSG_CODES, EpochStatus, ExtendedConfigStore, FlagKeys, MaintenanceStatus, MarketsStorageKey, MarketsType, ORDERLY_ORDERBOOK_DEPTH_KEY, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, StatusProvider, TWType, WalletConnectorContext, WsNetworkStatus, checkNotional, cleanStringStyle, fetcher, findPositionTPSLFromOrders, findTPSLFromOrder, findTPSLOrderPriceFromOrder, getMinNotional, getPriceKey, indexedDBManager, initializeAppDatabase, isCurrentlyClosed, isCurrentlyTrading, noCacheConfig, parseJSON, persistIndexedDB, resetTimestampOffsetState, timestampWaitingMiddleware, useAccount, useAccountInfo2 as useAccountInfo, useAccountInstance, useAccountRewardsHistory, useAllBrokers, useApiKeyManager, useAppStore, useAssetsHistory, useAudioPlayer, useBalanceSubscription, useBalanceTopic, useBoolean, useChain, useChainInfo, useChains, useCheckReferralCode, useCollateral, useCommission, useComputedLTV, useConfig, useConvert, useCurEpochEstimate, useDaily, useDeposit, useDistribution, useDistributionHistory, useEpochInfo, useEstLiqPriceBySymbol, useEventEmitter, useFeatureFlag, useFeeState, useFundingDetails, useFundingFeeHistory, useFundingRate, useFundingRateBySymbol, useFundingRateHistory, useFundingRates, useFundingRatesStore, useGetClaimed, useGetEnv, useGetEstLiqPrice, useGetReferralCode, useGetRwaSymbolCloseTimeInterval, useGetRwaSymbolInfo, useGetRwaSymbolOpenStatus, useGetRwaSymbolOpenTimeInterval, useHoldingStream, useIndexPrice, useIndexPricesStream, useInfiniteQuery, useInitRwaSymbolsRuntime, useInternalTransfer, useKeyStore, useLazyQuery, useLeverage, useLeverageBySymbol, useLocalStorage, useMainTokenStore, useMainnetChainsStore, useMaintenanceStatus, useMarginModeBySymbol, useMarginModes, useMarginRatio, useMarkPrice, useMarkPriceBySymbol, useMarkPricesStream, useMarket, useMarketList, useMarketMap, useMarketTradeStream, useMarkets, useMarketsStore, useMarketsStream, useMaxLeverage, useMaxQty, useMaxWithdrawal, useMediaQuery, useMemoizedFn, useMutation, useNetworkInfo, useOdosQuote, useOrderEntity, useOrderEntry2 as useOrderEntry, useOrderEntry as useOrderEntry_deprecated, useOrderStore, useOrderStream, useOrderbookStream, useOrderlyContext, usePortfolio, usePositionActions, usePositionClose, usePositionStream, usePositions, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, useRefereeHistory, useRefereeInfo, useRefereeRebateSummary, useReferralInfo, useReferralRebateSummary, useRestrictedInfo, useRwaSymbolsInfo, useRwaSymbolsInfoStore, useSessionStorage, useSettleSubscription, useSimpleDI, useStatisticsDaily, useStorageChain, useStorageLedgerAddress, useSubAccountAlgoOrderStream, useSubAccountDataObserver, useSubAccountMaxWithdrawal, useSubAccountMutation, useSubAccountQuery, useSubAccountWS, useSwapSupportStore, useSymbolInfo, useSymbolLeverage, useSymbolLeverageMap, useSymbolPriceRange, useSymbolsInfo, useSymbolsInfoStore, useTPSLOrder, useTestTokenStore, useTestnetChainsStore, useTickerStream, useTokenInfo, useTokensInfo, useTpslPriceChecker, useTrack, useTrackingInstance, useTradingRewardsStatus, useTransfer, useTransferHistory, useUpdatedRef, useUserStatistics, useVaultsHistory, useWS, useWalletConnector, useWalletRewardsHistory, useWalletSubscription, useWalletTopic, useWithdraw, useWsStatus, utils_exports as utils, version_default as version };
20039
+ export { DefaultLayoutConfig, DistributionId, ENVType2 as ENVType, ERROR_MSG_CODES, EpochStatus, ExtendedConfigStore, FlagKeys, MaintenanceStatus, MarketCategoriesConfigProvider, MarketsStorageKey, MarketsType, ORDERLY_ORDERBOOK_DEPTH_KEY, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, StatusProvider, TWType, WalletConnectorContext, WsNetworkStatus, checkNotional, cleanStringStyle, fetcher, findPositionTPSLFromOrders, findTPSLFromOrder, findTPSLOrderPriceFromOrder, formatSymbolWithBroker, getMinNotional, getPriceKey, indexedDBManager, initializeAppDatabase, isCurrentlyClosed, isCurrentlyTrading, noCacheConfig, parseJSON, persistIndexedDB, resetTimestampOffsetState, timestampWaitingMiddleware, useAccount, useAccountInfo2 as useAccountInfo, useAccountInstance, useAccountRewardsHistory, useAllBrokers, useApiKeyManager, useAppStore, useAssetsHistory, useAudioPlayer, useBadgeBySymbol, useBalanceSubscription, useBalanceTopic, useBoolean, useChain, useChainInfo, useChains, useCheckReferralCode, useCollateral, useCommission, useComputedLTV, useConfig, useConvert, useCurEpochEstimate, useDaily, useDeposit, useDistribution, useDistributionHistory, useEpochInfo, useEstLiqPriceBySymbol, useEventEmitter, useFeatureFlag, useFeeState, useFundingDetails, useFundingFeeHistory, useFundingRate, useFundingRateBySymbol, useFundingRateHistory, useFundingRates, useFundingRatesStore, useGetClaimed, useGetEnv, useGetEstLiqPrice, useGetReferralCode, useGetRwaSymbolCloseTimeInterval, useGetRwaSymbolInfo, useGetRwaSymbolOpenStatus, useGetRwaSymbolOpenTimeInterval, useHoldingStream, useIndexPrice, useIndexPricesStream, useInfiniteQuery, useInitRwaSymbolsRuntime, useInternalTransfer, useKeyStore, useLazyQuery, useLeverage, useLeverageBySymbol, useLocalStorage, useMainTokenStore, useMainnetChainsStore, useMaintenanceStatus, useMarginModeBySymbol, useMarginModes, useMarginRatio, useMarkPrice, useMarkPriceBySymbol, useMarkPricesStream, useMarket, useMarketCategoriesConfig, useMarketList, useMarketMap, useMarketTradeStream, useMarkets, useMarketsStore, useMarketsStream, useMaxLeverage, useMaxQty, useMaxWithdrawal, useMediaQuery, useMemoizedFn, useMutation, useNetworkInfo, useOdosQuote, useOrderEntity, useOrderEntry2 as useOrderEntry, useOrderEntry as useOrderEntry_deprecated, useOrderStore, useOrderStream, useOrderbookStream, useOrderlyContext, usePortfolio, usePositionActions, usePositionClose, usePositionStream, usePositions, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, useRefereeHistory, useRefereeInfo, useRefereeRebateSummary, useReferralInfo, useReferralRebateSummary, useRestrictedInfo, useRwaSymbolsInfo, useRwaSymbolsInfoStore, useSessionStorage, useSettleSubscription, useSimpleDI, useStatisticsDaily, useStorageChain, useStorageLedgerAddress, useSubAccountAlgoOrderStream, useSubAccountDataObserver, useSubAccountMaxWithdrawal, useSubAccountMutation, useSubAccountQuery, useSubAccountWS, useSwapSupportStore, useSymbolInfo, useSymbolLeverage, useSymbolLeverageMap, useSymbolPriceRange, useSymbolWithBroker, useSymbolsInfo, useSymbolsInfoStore, useTPSLOrder, useTestTokenStore, useTestnetChainsStore, useTickerStream, useTokenInfo, useTokensInfo, useTpslPriceChecker, useTrack, useTrackingInstance, useTradingRewardsStatus, useTransfer, useTransferHistory, useUpdatedRef, useUserStatistics, useVaultsHistory, useWS, useWalletConnector, useWalletRewardsHistory, useWalletSubscription, useWalletTopic, useWithdraw, useWsStatus, utils_exports as utils, version_default as version };
19618
20040
  //# sourceMappingURL=index.mjs.map
19619
20041
  //# sourceMappingURL=index.mjs.map