@orderly.network/hooks 3.0.0-beta.0 → 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
- 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
7
  import { usePluginScope } from '@orderly.network/plugin-core';
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.0";
53
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "3.0.0-beta.10";
43
54
  }
44
- var version_default = "3.0.0-beta.0";
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,
@@ -72,6 +83,8 @@ function useConfig(key, defaultValue) {
72
83
  }
73
84
  return configStore;
74
85
  }
86
+
87
+ // src/useQuery.ts
75
88
  var PLUGIN_ID_HEADER = "X-Orderly-Plugin-Id";
76
89
  var useQuery = (query, options) => {
77
90
  const apiBaseUrl = useConfig("apiBaseUrl");
@@ -568,6 +581,20 @@ var useAudioPlayer = (src, options = {}) => {
568
581
  const el = getOrderFilledAudio();
569
582
  el.volume = Math.max(0, Math.min(1, volume));
570
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
+ }, []);
571
598
  const play = useCallback(() => {
572
599
  const currentSrc = srcRef.current;
573
600
  const currentEnabled = enabledRef.current;
@@ -1277,7 +1304,7 @@ function checkTPSLOrderTypeIsMarket(key, values) {
1277
1304
  }
1278
1305
  function tpslCalculateHelper(key, inputs, options = {}) {
1279
1306
  const { symbol } = options;
1280
- 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") {
1281
1308
  return {
1282
1309
  [key]: inputs.value
1283
1310
  };
@@ -1285,6 +1312,7 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1285
1312
  const orderType = key.startsWith("tp_") ? AlgoOrderType.TAKE_PROFIT : AlgoOrderType.STOP_LOSS;
1286
1313
  const keyPrefix = key.slice(0, 3);
1287
1314
  const qty = Number(key === "quantity" ? inputs.value : inputs.qty);
1315
+ const markPrice = inputs.markPrice ?? inputs.entryPrice;
1288
1316
  if (qty === 0 && (key === "tp_pnl" || key === "sl_pnl" || key === "tp_trigger_price" || key === "sl_trigger_price")) {
1289
1317
  return {
1290
1318
  // [`${keyPrefix}trigger_price`]: "",
@@ -1295,7 +1323,7 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1295
1323
  [key]: inputs.value
1296
1324
  };
1297
1325
  }
1298
- 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;
1299
1327
  const entryPrice = new Decimal(inputs.entryPrice).todp(options.symbol?.quote_dp ?? 2, Decimal.ROUND_UP).toNumber();
1300
1328
  switch (key) {
1301
1329
  case "tp_trigger_price":
@@ -1307,6 +1335,8 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1307
1335
  [`${keyPrefix}trigger_price`]: trigger_price,
1308
1336
  [`${keyPrefix}offset`]: "",
1309
1337
  [`${keyPrefix}offset_percentage`]: "",
1338
+ [`${keyPrefix}offset_from_mark`]: "",
1339
+ [`${keyPrefix}offset_percentage_from_mark`]: "",
1310
1340
  [`${keyPrefix}pnl`]: "",
1311
1341
  [`${keyPrefix}ROI`]: ""
1312
1342
  };
@@ -1316,31 +1346,6 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1316
1346
  }
1317
1347
  break;
1318
1348
  }
1319
- // case "tp_enable":
1320
- // case "sl_enable": {
1321
- // return {
1322
- // [`${keyPrefix}enable`]: inputs.value,
1323
- // [`${keyPrefix}order_type`]: OrderType.MARKET,
1324
- // [`${keyPrefix}trigger_price`]: "",
1325
- // [`${keyPrefix}order_price`]: "",
1326
- // [`${keyPrefix}offset`]: "",
1327
- // [`${keyPrefix}offset_percentage`]: "",
1328
- // [`${keyPrefix}pnl`]: "",
1329
- // [`${keyPrefix}ROI`]: "",
1330
- // };
1331
- // }
1332
- // case 'tp_pnl':{
1333
- // if (inputs.values.tp_order_type !== OrderType.MARKET) {
1334
- // pnl = inputs.value;
1335
- // trigger_price = pnlToPrice({
1336
- // qty,
1337
- // pnl: Number(inputs.value),
1338
- // entryPrice,
1339
- // orderSide: inputs.orderSide,
1340
- // orderType,
1341
- // })
1342
- // }
1343
- // }
1344
1349
  case "tp_pnl":
1345
1350
  case "sl_pnl": {
1346
1351
  pnl = inputs.value;
@@ -1387,6 +1392,30 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1387
1392
  }
1388
1393
  break;
1389
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
+ }
1390
1419
  case "tp_order_price":
1391
1420
  case "sl_order_price": {
1392
1421
  order_price = inputs.value;
@@ -1427,12 +1456,38 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1427
1456
  }
1428
1457
  break;
1429
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
+ }
1430
1483
  }
1431
1484
  if (!trigger_price && checkTPSLOrderTypeIsMarket(key, inputs.values)) {
1432
1485
  return {
1433
1486
  [`${keyPrefix}trigger_price`]: "",
1434
1487
  [`${keyPrefix}offset`]: "",
1435
1488
  [`${keyPrefix}offset_percentage`]: "",
1489
+ [`${keyPrefix}offset_from_mark`]: "",
1490
+ [`${keyPrefix}offset_percentage_from_mark`]: "",
1436
1491
  [`${keyPrefix}pnl`]: "",
1437
1492
  [`${keyPrefix}ROI`]: "",
1438
1493
  [key]: inputs.value
@@ -1477,6 +1532,8 @@ function tpslCalculateHelper(key, inputs, options = {}) {
1477
1532
  [`${keyPrefix}order_price`]: order_price ? todpIfNeed(order_price, symbol?.quote_dp ?? 2) : "",
1478
1533
  [`${keyPrefix}offset`]: offset ?? "",
1479
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`] ?? "",
1480
1537
  [`${keyPrefix}pnl`]: pnl ?? ""
1481
1538
  // [`${keyPrefix}ROI`]: calcROI({
1482
1539
  // pnl: Number(pnl ?? 0),
@@ -1664,6 +1721,7 @@ function tpslInputHandle(inputs) {
1664
1721
  // order price or mark price
1665
1722
  qty: values.side === OrderSide.BUY ? Number(values.order_quantity) : Number(values.order_quantity) * -1,
1666
1723
  orderSide: values.side,
1724
+ markPrice,
1667
1725
  // values: newValues,
1668
1726
  values
1669
1727
  },
@@ -1699,6 +1757,10 @@ var getCalculateHandler = (fieldName) => {
1699
1757
  case "sl_offset":
1700
1758
  case "tp_offset_percentage":
1701
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":
1702
1764
  case "tp_order_price":
1703
1765
  case "tp_order_type":
1704
1766
  case "sl_order_type":
@@ -2582,16 +2644,12 @@ var createDataStore = (config) => {
2582
2644
  const brokerIdQuery = typeof options?.brokerId === "string" && options?.brokerId !== "orderly" ? `?broker_id=${options?.brokerId}` : "";
2583
2645
  const url = `${dynamicBaseUrl || baseUrl || ""}${endpoint}${brokerIdQuery}`;
2584
2646
  const data = await fetcher(url, {}, { formatter });
2585
- const dataWithBrokerId = data.map((item) => ({
2586
- ...item,
2587
- broker_id: options?.brokerId
2588
- }));
2589
2647
  set({
2590
- data: dataWithBrokerId,
2648
+ data,
2591
2649
  loading: false,
2592
2650
  error: null
2593
2651
  });
2594
- return dataWithBrokerId;
2652
+ return data;
2595
2653
  } catch (error) {
2596
2654
  set({ error, loading: false });
2597
2655
  return null;
@@ -3127,7 +3185,9 @@ var DEFAULT_SYMBOL_DEPTHS = {
3127
3185
  };
3128
3186
  var DEFAULT_SYMBOL_DISPLAY_NAMES = {
3129
3187
  PERP_XAU_USDC: "XAU (Gold) ",
3130
- 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)"
3131
3191
  };
3132
3192
  var ProxyConfigStore = class {
3133
3193
  constructor(_originConfigStore) {
@@ -3410,7 +3470,10 @@ var useGetRwaSymbolOpenTimeInterval = (symbol, thresholdMinutes = 30) => {
3410
3470
  };
3411
3471
  var useSymbolsInfo = () => {
3412
3472
  const symbolsInfo = useAppStore((state) => state.symbolsInfo);
3413
- return useMemo(() => createGetter({ ...symbolsInfo }), [symbolsInfo]);
3473
+ return useMemo(
3474
+ () => createGetter(symbolsInfo ? { ...symbolsInfo } : symbolsInfo),
3475
+ [symbolsInfo]
3476
+ );
3414
3477
  };
3415
3478
  var useSymbolsInfoStore = () => {
3416
3479
  return useAppStore((state) => state.symbolsInfo);
@@ -3423,6 +3486,7 @@ var MarketsType = /* @__PURE__ */ ((MarketsType2) => {
3423
3486
  MarketsType2[MarketsType2["ALL"] = 2] = "ALL";
3424
3487
  MarketsType2[MarketsType2["RWA"] = 3] = "RWA";
3425
3488
  MarketsType2[MarketsType2["NEW_LISTING"] = 4] = "NEW_LISTING";
3489
+ MarketsType2[MarketsType2["COMMUNITY"] = 5] = "COMMUNITY";
3426
3490
  return MarketsType2;
3427
3491
  })(MarketsType || {});
3428
3492
  var MarketsStorageKey = "orderly_markets";
@@ -3592,6 +3656,8 @@ var addFieldToMarkets = (futures, symbolsInfo, rwaSymbolsInfo) => {
3592
3656
  const rwaInfo = !rwaSymbolsInfo.isNil ? rwaSymbolsInfo[item.symbol]() : null;
3593
3657
  return {
3594
3658
  ...item,
3659
+ broker_id: item.broker_id,
3660
+ display_symbol_name: item.display_symbol_name,
3595
3661
  quote_dp: info("quote_dp"),
3596
3662
  created_time: info("created_time"),
3597
3663
  displayName: info("displayName"),
@@ -3613,7 +3679,7 @@ var addFieldToMarkets = (futures, symbolsInfo, rwaSymbolsInfo) => {
3613
3679
  var filterMarkets = (params) => {
3614
3680
  const { markets, favorites, recent, newListing, type } = params;
3615
3681
  let curData = [];
3616
- if (type === 2 /* ALL */) {
3682
+ if (type === 2 /* ALL */ || type === 5 /* COMMUNITY */) {
3617
3683
  curData = markets;
3618
3684
  } else if (type === 3 /* RWA */) {
3619
3685
  curData = markets.filter((item) => item.isRwa);
@@ -4535,7 +4601,7 @@ var useMarket = (type) => {
4535
4601
  const getData = (type2) => {
4536
4602
  const localData = type2 === 0 /* FAVORITES */ ? [...favorites] : [...recent];
4537
4603
  const keys = localData.map((item) => item.name);
4538
- 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));
4539
4605
  const favoritesData = [...favorites];
4540
4606
  const favoriteKeys = favoritesData.map((item) => item.name);
4541
4607
  if (filter) {
@@ -4734,6 +4800,80 @@ var useSymbolLeverageMap = () => {
4734
4800
  refresh: mutate6
4735
4801
  };
4736
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
4737
4877
  var useMarginModes = () => {
4738
4878
  const { data, error, isLoading, mutate: mutate6 } = usePrivateQuery("/v1/client/margin_modes", {
4739
4879
  revalidateOnFocus: false,
@@ -4775,22 +4915,28 @@ var useMarginModes = () => {
4775
4915
  };
4776
4916
  var useMarginModeBySymbol = (symbol, fallback = MarginMode.CROSS) => {
4777
4917
  const { marginModes, isLoading, error, refresh, updateMarginMode } = useMarginModes();
4778
- 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]);
4779
4923
  const update = useCallback(
4780
4924
  async (mode) => {
4925
+ if (brokerId) mode = MarginMode.ISOLATED;
4781
4926
  return updateMarginMode({
4782
4927
  symbol_list: [symbol],
4783
4928
  default_margin_mode: mode
4784
4929
  });
4785
4930
  },
4786
- [symbol, updateMarginMode]
4931
+ [brokerId, symbol, updateMarginMode]
4787
4932
  );
4788
4933
  return {
4789
4934
  marginMode,
4790
4935
  isLoading,
4791
4936
  error,
4792
4937
  refresh,
4793
- update
4938
+ update,
4939
+ isPermissionlessListing: !!brokerId
4794
4940
  };
4795
4941
  };
4796
4942
 
@@ -5029,6 +5175,11 @@ var MarkPriceCalculator = class extends BaseCalculator {
5029
5175
 
5030
5176
  // src/orderly/calculator/calculatorContext.ts
5031
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
+ }
5032
5183
  static get instance() {
5033
5184
  return this._instance;
5034
5185
  }
@@ -5047,7 +5198,6 @@ var CalculatorContext = class _CalculatorContext {
5047
5198
  update(scope, data) {
5048
5199
  this.setCtxData();
5049
5200
  this.markPrices = scope === "markPrice" /* MARK_PRICE */ ? data : this.output[MarketCalculatorName];
5050
- this.portfolio = this.output["portfolio"] || useAppStore.getState().portfolio;
5051
5201
  return this;
5052
5202
  }
5053
5203
  setCtxData() {
@@ -5065,7 +5215,6 @@ var CalculatorContext = class _CalculatorContext {
5065
5215
  clearCache() {
5066
5216
  this.output = {};
5067
5217
  this.accountInfo = void 0;
5068
- this.portfolio = void 0;
5069
5218
  }
5070
5219
  deleteByName(name) {
5071
5220
  delete this.output[name];
@@ -5433,7 +5582,7 @@ var PositionCalculator = class extends BaseCalculator {
5433
5582
  if (!accountInfo || !fundingRates || !symbolsInfo) {
5434
5583
  return data;
5435
5584
  }
5436
- 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;
5437
5586
  let rows = data.rows.map((item) => {
5438
5587
  const info = symbolsInfo[item.symbol];
5439
5588
  const sum_unitary_funding = fundingRates?.[item.symbol]?.["sum_unitary_funding"] ?? 0;
@@ -5496,6 +5645,12 @@ var PositionCalculator = class extends BaseCalculator {
5496
5645
  unrealPnL_total_index = unrealPnL_total_index.add(unrealPnl_index);
5497
5646
  notional_total = notional_total.add(notional);
5498
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
+ }
5499
5654
  const fundingFee = new Decimal(sum_unitary_funding).sub(item.last_sum_unitary_funding).mul(item.position_qty).negated().toNumber();
5500
5655
  return {
5501
5656
  ...item,
@@ -5511,7 +5666,8 @@ var PositionCalculator = class extends BaseCalculator {
5511
5666
  unrealized_pnl: unrealPnl,
5512
5667
  unrealized_pnl_index: unrealPnl_index,
5513
5668
  unrealized_pnl_ROI: unrealPnlROI,
5514
- unrealized_pnl_ROI_index: unrealPnlROI_index
5669
+ unrealized_pnl_ROI_index: unrealPnlROI_index,
5670
+ unsettled_pnl: unsettlementPnL2
5515
5671
  };
5516
5672
  });
5517
5673
  const totalUnrealPnl = unrealPnL_total.toNumber();
@@ -5523,18 +5679,34 @@ var PositionCalculator = class extends BaseCalculator {
5523
5679
  rows = rows.map((item) => {
5524
5680
  const info = symbolsInfo[item.symbol];
5525
5681
  const totalCollateral = item.margin_mode === MarginMode.ISOLATED ? new Decimal(item.margin ?? 0).add(item.unsettlement_pnl ?? 0).toNumber() : crossMarginCollateral.toNumber();
5526
- const est_liq_price = positions.liqPrice({
5527
- symbol: item.symbol,
5528
- markPrice: item.mark_price,
5529
- totalCollateral,
5530
- positionQty: item.position_qty,
5531
- positions: rows,
5532
- MMR: item.mmr,
5533
- baseMMR: info?.["base_mmr"],
5534
- baseIMR: info?.["base_imr"],
5535
- IMRFactor: accountInfo.imr_factor[item.symbol],
5536
- costPosition: item.cost_position
5537
- });
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
+ }
5538
5710
  return {
5539
5711
  ...item,
5540
5712
  est_liq_price
@@ -5561,6 +5733,8 @@ var PositionCalculator = class extends BaseCalculator {
5561
5733
  total_unsettled_pnl: unsettlementPnL,
5562
5734
  unrealPnlROI: totalUnrealizedROI,
5563
5735
  unrealPnlROI_index: totalUnrealizedROI_index,
5736
+ total_unsettled_cross_pnl: totalUnsettledCrossPnl.toNumber(),
5737
+ total_unsettled_isolated_pnl: totalUnsettledIsolatedPnl.toNumber(),
5564
5738
  rows
5565
5739
  };
5566
5740
  }
@@ -5723,13 +5897,9 @@ var PortfolioCalculator = class extends BaseCalculator {
5723
5897
  if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !indexPrices || !accountInfo) {
5724
5898
  return null;
5725
5899
  }
5726
- const totallCrossUnsettledPnL = positions3.rows.reduce(
5727
- (sum, pos) => pos.margin_mode === MarginMode.ISOLATED ? sum : sum + (pos.unsettled_pnl ?? 0),
5728
- 0
5729
- );
5730
- const totalUnsettlementPnL = positions3.rows.reduce(
5731
- (sum, pos) => sum + (pos.unsettled_pnl ?? 0),
5732
- 0
5900
+ const unsettledPnL = pathOr(0, ["total_unsettled_pnl"])(positions3);
5901
+ const unsettledCrossPnL = pathOr(0, ["total_unsettled_cross_pnl"])(
5902
+ positions3
5733
5903
  );
5734
5904
  const unrealizedPnL = pathOr(0, ["total_unreal_pnl"])(positions3);
5735
5905
  const [USDC_holding, nonUSDC] = parseHolding(
@@ -5741,7 +5911,7 @@ var PortfolioCalculator = class extends BaseCalculator {
5741
5911
  const totalCollateral = account.totalCollateral({
5742
5912
  USDCHolding: USDC_holding,
5743
5913
  nonUSDCHolding: nonUSDC,
5744
- unsettlementPnL: totallCrossUnsettledPnL,
5914
+ unsettlementPnL: unsettledCrossPnL,
5745
5915
  usdcBalancePendingShortQty: usdc?.pending_short ?? 0,
5746
5916
  usdcBalanceIsolatedOrderFrozen: usdc?.isolated_order_frozen ?? 0
5747
5917
  });
@@ -5752,7 +5922,7 @@ var PortfolioCalculator = class extends BaseCalculator {
5752
5922
  return acc.add(curr.margin ?? 0);
5753
5923
  }, zero);
5754
5924
  const totalValue = account.totalValue({
5755
- totalUnsettlementPnL,
5925
+ totalUnsettlementPnL: unsettledPnL,
5756
5926
  USDCHolding: USDC_holding,
5757
5927
  nonUSDCHolding: nonUSDC,
5758
5928
  totalIsolatedPositionMargin: sumIsolatedMargin.toNumber()
@@ -5796,7 +5966,7 @@ var PortfolioCalculator = class extends BaseCalculator {
5796
5966
  totalUnrealizedROI,
5797
5967
  freeCollateral,
5798
5968
  availableBalance,
5799
- unsettledPnL: totalUnsettlementPnL,
5969
+ unsettledPnL,
5800
5970
  holding,
5801
5971
  usdcHolding: USDC_holding,
5802
5972
  freeCollateralUSDCOnly
@@ -5915,7 +6085,7 @@ var usePositionStream = (symbol = "all", options) => {
5915
6085
  total_unreal_pnl: total_unreal_pnl_index,
5916
6086
  unrealPnlROI: unrealPnlROI_index
5917
6087
  };
5918
- }, [calcMode]);
6088
+ }, [calcMode, formattedPositions]);
5919
6089
  let rows = formattedPositions[0];
5920
6090
  {
5921
6091
  if (!rows) {
@@ -6405,14 +6575,8 @@ function formatPortfolio(inputs) {
6405
6575
  if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !indexPrices || !accountInfo || symbolsInfo?.isNil) {
6406
6576
  return null;
6407
6577
  }
6408
- const totallCrossUnsettledPnL = positions3.rows.reduce(
6409
- (sum, pos) => pos.margin_mode === MarginMode.ISOLATED ? sum : sum + (pos.unsettled_pnl ?? 0),
6410
- 0
6411
- );
6412
- const totalUnsettlementPnL = positions3.rows.reduce(
6413
- (sum, pos) => sum + (pos.unsettled_pnl ?? 0),
6414
- 0
6415
- );
6578
+ const unsettledPnL = pathOr(0, ["total_unsettled_pnl"])(positions3);
6579
+ const unsettledCrossPnL = pathOr(0, ["total_unsettled_cross_pnl"])(positions3);
6416
6580
  const unrealizedPnL = pathOr(0, ["total_unreal_pnl"])(positions3);
6417
6581
  const [USDC_holding, nonUSDC] = parseHolding(
6418
6582
  holding,
@@ -6423,7 +6587,7 @@ function formatPortfolio(inputs) {
6423
6587
  const totalCollateral = account.totalCollateral({
6424
6588
  USDCHolding: USDC_holding,
6425
6589
  nonUSDCHolding: nonUSDC,
6426
- unsettlementPnL: totallCrossUnsettledPnL,
6590
+ unsettlementPnL: unsettledCrossPnL,
6427
6591
  usdcBalancePendingShortQty: usdc?.pending_short ?? 0,
6428
6592
  usdcBalanceIsolatedOrderFrozen: usdc?.isolated_order_frozen ?? 0
6429
6593
  });
@@ -6434,7 +6598,7 @@ function formatPortfolio(inputs) {
6434
6598
  return acc.add(curr.margin ?? 0);
6435
6599
  }, zero);
6436
6600
  const totalValue = account.totalValue({
6437
- totalUnsettlementPnL,
6601
+ totalUnsettlementPnL: unsettledPnL,
6438
6602
  USDCHolding: USDC_holding,
6439
6603
  nonUSDCHolding: nonUSDC,
6440
6604
  totalIsolatedPositionMargin: sumIsolatedMargin.toNumber()
@@ -6478,7 +6642,7 @@ function formatPortfolio(inputs) {
6478
6642
  totalUnrealizedROI,
6479
6643
  freeCollateral,
6480
6644
  availableBalance,
6481
- unsettledPnL: totalUnsettlementPnL,
6645
+ unsettledPnL,
6482
6646
  holding,
6483
6647
  freeCollateralUSDCOnly
6484
6648
  };
@@ -6487,7 +6651,7 @@ function formatPositions(data, accountInfo, symbolsInfo, fundingRates) {
6487
6651
  if (!accountInfo || !fundingRates || !symbolsInfo) {
6488
6652
  return data;
6489
6653
  }
6490
- 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;
6491
6655
  const rows = data.rows.map((item) => {
6492
6656
  const info = symbolsInfo[item.symbol];
6493
6657
  const notional = positions.notional(item.position_qty, item.mark_price);
@@ -6549,6 +6713,12 @@ function formatPositions(data, accountInfo, symbolsInfo, fundingRates) {
6549
6713
  unrealPnL_total_index = unrealPnL_total_index.add(unrealPnl_index);
6550
6714
  notional_total = notional_total.add(notional);
6551
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
+ }
6552
6722
  return {
6553
6723
  ...item,
6554
6724
  mm: positions.maintenanceMargin({
@@ -6562,7 +6732,8 @@ function formatPositions(data, accountInfo, symbolsInfo, fundingRates) {
6562
6732
  unrealized_pnl: unrealPnl,
6563
6733
  unrealized_pnl_index: unrealPnl_index,
6564
6734
  unrealized_pnl_ROI: unrealPnlROI,
6565
- unrealized_pnl_ROI_index: unrealPnlROI_index
6735
+ unrealized_pnl_ROI_index: unrealPnlROI_index,
6736
+ unsettled_pnl: unsettlementPnL2
6566
6737
  };
6567
6738
  });
6568
6739
  const totalUnrealPnl = unrealPnL_total.toNumber();
@@ -6576,6 +6747,8 @@ function formatPositions(data, accountInfo, symbolsInfo, fundingRates) {
6576
6747
  notional: notional_total.toNumber(),
6577
6748
  unsettledPnL: unsettlementPnL,
6578
6749
  total_unsettled_pnl: unsettlementPnL,
6750
+ total_unsettled_cross_pnl: totalUnsettledCrossPnl.toNumber(),
6751
+ total_unsettled_isolated_pnl: totalUnsettledIsolatedPnl.toNumber(),
6579
6752
  rows
6580
6753
  };
6581
6754
  }
@@ -7958,7 +8131,9 @@ var useDeposit = (options) => {
7958
8131
  const depositPromise = isNativeToken ? account9.assetsManager.depositNativeToken(inputs) : account9.assetsManager.deposit(inputs);
7959
8132
  return depositPromise.then((result) => {
7960
8133
  updateAllowanceWhenTxSuccess(result.hash);
7961
- setBalance((value) => new Decimal(value).sub(quantity).toString());
8134
+ setBalance(
8135
+ (value) => value ? new Decimal(value).sub(quantity).toString() : "0"
8136
+ );
7962
8137
  track2(TrackerEventName.depositSuccess, {
7963
8138
  wallet: state?.connectWallet?.name,
7964
8139
  network: targetChain?.network_infos.name,
@@ -8010,16 +8185,16 @@ var useDeposit = (options) => {
8010
8185
  };
8011
8186
  function useBalance(options) {
8012
8187
  const { srcToken, address, decimals, account: account9, status } = options;
8013
- const [balance, setBalance] = useState("0");
8188
+ const [balance, setBalance] = useState(null);
8014
8189
  const fetchBalance = useCallback(
8015
8190
  async (address2, decimals2) => {
8016
8191
  try {
8017
8192
  if (isNativeTokenChecker(address2)) {
8018
- return account9.assetsManager.getNativeBalance({
8193
+ return await account9.assetsManager.getNativeBalance({
8019
8194
  decimals: decimals2
8020
8195
  });
8021
8196
  }
8022
- return account9.assetsManager.getBalance(address2, {
8197
+ return await account9.assetsManager.getBalance(address2, {
8023
8198
  decimals: decimals2
8024
8199
  });
8025
8200
  } catch (err) {
@@ -8068,11 +8243,13 @@ function useBalance(options) {
8068
8243
  useEffect(() => {
8069
8244
  if (swrBalance !== void 0) {
8070
8245
  setBalance(swrBalance || "0");
8246
+ } else {
8247
+ setBalance(null);
8071
8248
  }
8072
- }, [swrBalance]);
8249
+ }, [swrBalance, address]);
8073
8250
  return {
8074
8251
  balance,
8075
- balanceRevalidating,
8252
+ balanceRevalidating: balanceRevalidating || balance === null,
8076
8253
  setBalance,
8077
8254
  fetchBalance,
8078
8255
  fetchBalances
@@ -9602,6 +9779,9 @@ var PriceValidationStrategy = class {
9602
9779
  }
9603
9780
  const price = new Decimal(order_price);
9604
9781
  const { symbol } = config;
9782
+ if (!symbol) {
9783
+ return;
9784
+ }
9605
9785
  const { quote_max, quote_min, quote_dp, price_range, price_scope } = symbol;
9606
9786
  const maxPriceNumber = order.maxPrice(config.markPrice, price_range);
9607
9787
  const minPriceNumber = order.minPrice(config.markPrice, price_range);
@@ -9648,6 +9828,9 @@ var TriggerPriceValidationStrategy = class {
9648
9828
  validate(values, config) {
9649
9829
  const { trigger_price } = values;
9650
9830
  const { symbol } = config;
9831
+ if (!symbol) {
9832
+ return;
9833
+ }
9651
9834
  const { quote_max, quote_min } = symbol;
9652
9835
  if (!trigger_price) {
9653
9836
  return OrderValidation.required("trigger_price");
@@ -9694,6 +9877,9 @@ var QuantityValidationStrategy = class {
9694
9877
  validate(values, config) {
9695
9878
  let { order_quantity, total, order_price } = values;
9696
9879
  const { maxQty, symbol } = config;
9880
+ if (!symbol) {
9881
+ return;
9882
+ }
9697
9883
  const { base_min, base_dp, quote_dp } = symbol;
9698
9884
  if (!order_quantity && total && order_price) {
9699
9885
  const totalNumber = new Decimal(total);
@@ -10894,7 +11080,11 @@ var tpslFields = [
10894
11080
  "tp_offset",
10895
11081
  "sl_offset",
10896
11082
  "tp_offset_percentage",
10897
- "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"
10898
11088
  ];
10899
11089
  var isBracketOrder = (order) => {
10900
11090
  return !!order.tp_trigger_price || !!order.sl_trigger_price;
@@ -10949,7 +11139,7 @@ var calcEstLiqPrice = (order$1, askAndBid, inputs) => {
10949
11139
  totalCollateral,
10950
11140
  futures_taker_fee_rate,
10951
11141
  positions: positions3,
10952
- // leverage,
11142
+ symbolLeverage,
10953
11143
  sumUnitaryFunding
10954
11144
  } = inputs;
10955
11145
  const orderFee = order.orderFee({
@@ -10974,7 +11164,7 @@ var calcEstLiqPrice = (order$1, askAndBid, inputs) => {
10974
11164
  }
10975
11165
  });
10976
11166
  } else {
10977
- let isolatedPositionMargin = 0, costPosition = 0, positionQty = 0, lastSumUnitaryFunding = 0, leverage = 1;
11167
+ let isolatedPositionMargin = 0, costPosition = 0, positionQty = 0, lastSumUnitaryFunding = 0, leverage = symbolLeverage ?? 1;
10978
11168
  if (positions3) {
10979
11169
  const position = positions3.find(
10980
11170
  (p) => p.symbol === symbol && p.margin_mode === MarginMode.ISOLATED
@@ -11110,6 +11300,8 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
11110
11300
  entryPrice: position.average_open_price,
11111
11301
  qty: side === OrderSide.BUY ? Number(prev.quantity) : -Number(prev.quantity),
11112
11302
  orderSide: side,
11303
+ markPrice: markPrice ?? position.average_open_price,
11304
+ // use mark price as the default value
11113
11305
  values: prev
11114
11306
  },
11115
11307
  {
@@ -12664,6 +12856,12 @@ var DataPaint = class extends BasePaint {
12664
12856
  this.DEFAULT_LOSS_COLOR = "rgb(255,103,194)";
12665
12857
  this.transformTop = 0;
12666
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";
12667
12865
  }
12668
12866
  async draw(options) {
12669
12867
  const needDrawDetails = Array.isArray(options.data?.position?.informations) && (options.data?.position?.informations?.length ?? 0) > 0;
@@ -12750,6 +12948,49 @@ var DataPaint = class extends BasePaint {
12750
12948
  fontSize: this._ratio(fontSize),
12751
12949
  fontFamily: options.fontFamily
12752
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
+ }
12753
12994
  }
12754
12995
  const marginMode = options.data?.position.marginMode;
12755
12996
  if (marginMode) {
@@ -12764,7 +13005,7 @@ var DataPaint = class extends BasePaint {
12764
13005
  });
12765
13006
  }
12766
13007
  left += (prevElementBoundingBox.width ?? 0) + this._ratio(7);
12767
- const marginModeText = marginMode.charAt(0).toUpperCase() + marginMode.slice(1);
13008
+ const marginModeText = this.formatMarginMode(marginMode);
12768
13009
  prevElementBoundingBox = this._drawText(marginModeText, {
12769
13010
  color: layout.color,
12770
13011
  left,
@@ -12797,6 +13038,20 @@ var DataPaint = class extends BasePaint {
12797
13038
  );
12798
13039
  }
12799
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
+ }
12800
13055
  drawUnrealizedPnL(options, offsetTop = 0) {
12801
13056
  const layout = path(
12802
13057
  ["layout", "unrealizedPnl"],
@@ -13250,18 +13505,6 @@ var useEpochInfo = (type) => {
13250
13505
  }, [epochInfo]);
13251
13506
  return [epochInfo, { isLoading, curEpochInfo, isNotStared, refresh }];
13252
13507
  };
13253
-
13254
- // src/trading-rewards/useAllBrokers.ts
13255
- var useAllBrokers = () => {
13256
- const { data } = useQuery("/v1/public/broker/name", {
13257
- formatter: (res) => {
13258
- const { rows } = res;
13259
- return rows?.map((item) => ({ [item.broker_id]: item.broker_name })).reduce((acc, curr) => ({ ...acc, ...curr }), {});
13260
- },
13261
- revalidateOnFocus: false
13262
- });
13263
- return [data];
13264
- };
13265
13508
  var useCurEpochEstimate = (type) => {
13266
13509
  const [data, setData] = useState(void 0);
13267
13510
  const { account: account9 } = useAccount();
@@ -18397,108 +18640,69 @@ var initialOrderState = {
18397
18640
  tp_trigger_price: "",
18398
18641
  sl_trigger_price: "",
18399
18642
  total: "",
18400
- symbol: ""
18643
+ symbol: "",
18644
+ side: OrderSide.BUY,
18645
+ order_type: OrderType.LIMIT,
18646
+ margin_mode: MarginMode.CROSS
18401
18647
  };
18402
- var useOrderStore = create()(
18403
- immer((set, get3) => ({
18404
- entry: {
18405
- side: OrderSide.BUY,
18406
- order_type: OrderType.LIMIT,
18407
- ...initialOrderState
18408
- },
18409
- estLeverage: null,
18410
- estLiquidationPrice: null,
18411
- errors: {},
18412
- actions: {
18413
- initOrder: (symbol, options) => {
18414
- set((state) => {
18415
- state.entry = {
18416
- ...initialOrderState,
18417
- symbol,
18418
- side: options?.side ?? OrderSide.BUY,
18419
- order_type: options?.order_type ?? OrderType.LIMIT,
18420
- margin_mode: options?.margin_mode ?? MarginMode.CROSS
18421
- };
18422
- state.estLeverage = null;
18423
- state.estLiquidationPrice = null;
18424
- 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
18425
18666
  });
18426
18667
  },
18427
- hasTP_SL: () => {
18428
- const order = get3().entry;
18429
- return typeof order.tp_trigger_price !== "undefined" || typeof order.sl_trigger_price !== "undefined";
18430
- },
18431
- updateOrderComputed: (data) => {
18432
- set(
18433
- (state) => {
18434
- state.estLeverage = data.estLeverage;
18435
- state.estLiquidationPrice = data.estLiquidationPrice;
18436
- },
18437
- false
18438
- // "updateOrderComputed"
18439
- );
18440
- },
18441
18668
  updateOrder: (order) => {
18442
- set(
18443
- (state) => {
18444
- state.entry = {
18445
- ...state.entry,
18446
- ...order
18447
- };
18448
- },
18449
- false
18450
- // "updateOrder"
18451
- );
18669
+ setOrderEntity((prev) => ({ ...prev, ...order }));
18452
18670
  },
18453
18671
  updateOrderByKey: (key, value) => {
18454
- set(
18455
- (state) => {
18456
- state.entry[key] = value;
18457
- },
18458
- false
18459
- // "updateOrderByKey"
18460
- );
18461
- },
18462
- restoreOrder: (order) => {
18463
- set(
18464
- (state) => {
18465
- state.entry = order;
18466
- },
18467
- false
18468
- // "restoreOrder"
18469
- );
18672
+ setOrderEntity((prev) => ({ ...prev, [key]: value }));
18470
18673
  },
18471
18674
  resetOrder: (_order) => {
18472
- set(
18473
- (state) => {
18474
- state.entry.order_price = "";
18475
- state.entry.order_quantity = "";
18476
- state.entry.trigger_price = "";
18477
- state.entry.total = "";
18478
- state.entry.tp_trigger_price = "";
18479
- state.entry.tp_pnl = "";
18480
- state.entry.tp_offset = "";
18481
- state.entry.tp_offset_percentage = "";
18482
- state.entry.sl_trigger_price = "";
18483
- state.entry.sl_pnl = "";
18484
- state.entry.sl_offset = "";
18485
- state.entry.sl_offset_percentage = "";
18486
- },
18487
- true
18488
- // "resetOrder"
18489
- );
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";
18490
18698
  }
18491
- }
18492
- }))
18493
- );
18494
- var useOrderEntryNextInternal = (symbol, options = {}) => {
18495
- const { symbolInfo, symbolLeverage } = options;
18496
- const orderEntity = useOrderStore((state) => state.entry);
18497
- const orderEntryActions = useOrderStore((state) => state.actions);
18699
+ }),
18700
+ [orderEntity]
18701
+ );
18498
18702
  useEffect(() => {
18499
- orderEntryActions.initOrder(symbol, options.initialOrder);
18703
+ actions.initOrder(symbol, options.initialOrder);
18500
18704
  if (options.initialOrder) {
18501
- orderEntryActions.updateOrder(options.initialOrder);
18705
+ actions.updateOrder(options.initialOrder);
18502
18706
  }
18503
18707
  }, [symbol]);
18504
18708
  const calculate2 = useCallback(
@@ -18516,10 +18720,10 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18516
18720
  );
18517
18721
  const setValue = (key, value, additional) => {
18518
18722
  if (!symbolInfo) {
18519
- orderEntryActions.updateOrderByKey(key, value);
18723
+ actions.updateOrderByKey(key, value);
18520
18724
  return;
18521
18725
  }
18522
- const currentEntry = useOrderStore.getState().entry;
18726
+ const currentEntry = orderEntity;
18523
18727
  const { markPrice } = additional ?? { markPrice: 0 };
18524
18728
  let newValues = calculate2(
18525
18729
  { ...currentEntry },
@@ -18553,7 +18757,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18553
18757
  if (sl_ROI) {
18554
18758
  newValues.sl_ROI = sl_ROI;
18555
18759
  }
18556
- orderEntryActions.updateOrder(newValues);
18760
+ actions.updateOrder(newValues);
18557
18761
  return newValues;
18558
18762
  };
18559
18763
  const calculateTPSL = (key, newValues, markPrice, symbolInfo2) => {
@@ -18576,6 +18780,42 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18576
18780
  symbolInfo2
18577
18781
  );
18578
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
+ }
18579
18819
  } else {
18580
18820
  if (typeof newValues.tp_trigger_price !== "undefined") {
18581
18821
  newValues = calculate2(
@@ -18595,16 +18835,51 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18595
18835
  symbolInfo2
18596
18836
  );
18597
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
+ }
18598
18874
  }
18599
18875
  return newValues;
18600
18876
  };
18601
18877
  const setValues = (values, additional) => {
18602
18878
  if (!symbolInfo) {
18603
- orderEntryActions.updateOrder(values);
18879
+ actions.updateOrder(values);
18604
18880
  return;
18605
18881
  }
18606
- const currentEntry = useOrderStore.getState().entry;
18607
- let newValues = { ...currentEntry };
18882
+ let newValues = { ...orderEntity };
18608
18883
  Object.keys(values).forEach((key) => {
18609
18884
  newValues = calculate2(
18610
18885
  newValues,
@@ -18614,17 +18889,28 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18614
18889
  symbolInfo
18615
18890
  );
18616
18891
  });
18617
- 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);
18618
18905
  return newValues;
18619
18906
  };
18620
18907
  const onMarkPriceUpdated = useCallback(
18621
18908
  (markPrice, baseOn = []) => {
18622
18909
  if (!options.symbolInfo) return;
18623
- const currentEntry = useOrderStore.getState().entry;
18624
- let newValues = { ...currentEntry };
18910
+ let newValues = { ...orderEntity };
18625
18911
  if (baseOn.length === 0) {
18626
18912
  newValues = calculate2(
18627
- { ...currentEntry },
18913
+ { ...orderEntity },
18628
18914
  "order_price",
18629
18915
  markPrice,
18630
18916
  markPrice,
@@ -18635,7 +18921,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18635
18921
  newValues = calculate2(
18636
18922
  { ...newValues },
18637
18923
  key,
18638
- currentEntry[key],
18924
+ orderEntity[key],
18639
18925
  markPrice,
18640
18926
  options.symbolInfo
18641
18927
  );
@@ -18654,9 +18940,9 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18654
18940
  newValues.sl_ROI = sl_ROI;
18655
18941
  }
18656
18942
  }
18657
- orderEntryActions.updateOrder(newValues);
18943
+ actions.updateOrder(newValues);
18658
18944
  },
18659
- [calculate2, options.symbolInfo, orderEntryActions]
18945
+ [calculate2, options.symbolInfo, symbolLeverage, orderEntity]
18660
18946
  );
18661
18947
  const validate = (order, creator, options2) => {
18662
18948
  return creator?.validate(order, {
@@ -18674,12 +18960,13 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
18674
18960
  const submitOrder = useCallback(() => {
18675
18961
  }, [orderEntity]);
18676
18962
  const resetOrder = (order) => {
18677
- orderEntryActions.resetOrder(order);
18963
+ actions.resetOrder(order);
18678
18964
  };
18679
18965
  return {
18680
18966
  formattedOrder: orderEntity,
18681
18967
  setValue,
18682
18968
  setValues,
18969
+ setValuesRaw,
18683
18970
  submit: submitOrder,
18684
18971
  reset: resetOrder,
18685
18972
  generateOrder,
@@ -18695,6 +18982,8 @@ var useOrderEntry2 = (symbol, options = {}) => {
18695
18982
  }
18696
18983
  const ee = useEventEmitter();
18697
18984
  const { track: track2 } = useTrack();
18985
+ const apiBaseUrl = useConfig("apiBaseUrl");
18986
+ const fetchSymbols = useSymbolStore((state) => state.fetchData);
18698
18987
  const [meta, setMeta] = useState({
18699
18988
  dirty: {},
18700
18989
  submitted: false,
@@ -18714,8 +19003,7 @@ var useOrderEntry2 = (symbol, options = {}) => {
18714
19003
  const symbolConfig = useSymbolsInfo();
18715
19004
  const accountInfo = useAccountInfo();
18716
19005
  const positions3 = usePositions();
18717
- const entry = useOrderStore((s) => s.entry);
18718
- const effectiveMarginMode = options?.initialOrder?.margin_mode ?? entry?.margin_mode ?? MarginMode.CROSS;
19006
+ const effectiveMarginMode = options?.initialOrder?.margin_mode ?? MarginMode.CROSS;
18719
19007
  const symbolLeverage = useLeverageBySymbol(symbol, effectiveMarginMode);
18720
19008
  const symbolInfo = symbolConfig[symbol]();
18721
19009
  const markPrice = actions.getMarkPriceBySymbol(symbol);
@@ -18724,6 +19012,7 @@ var useOrderEntry2 = (symbol, options = {}) => {
18724
19012
  formattedOrder,
18725
19013
  setValue: setValueInternal,
18726
19014
  setValues: setValuesInternal,
19015
+ setValuesRaw: setValuesRawInternal,
18727
19016
  validate,
18728
19017
  generateOrder,
18729
19018
  reset,
@@ -18948,6 +19237,21 @@ var useOrderEntry2 = (symbol, options = {}) => {
18948
19237
  interactiveValidate(newValues);
18949
19238
  }
18950
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
+ };
18951
19255
  async function validateFunc(order) {
18952
19256
  const creator = getOrderCreator(order);
18953
19257
  return validate(order, creator, prepareData());
@@ -19002,11 +19306,12 @@ var useOrderEntry2 = (symbol, options = {}) => {
19002
19306
  markPrice: markPrice2,
19003
19307
  totalCollateral,
19004
19308
  futures_taker_fee_rate: accountInfo.futures_taker_fee_rate,
19005
- imr_factor: accountInfo.imr_factor[symbol],
19309
+ imr_factor: accountInfo.imr_factor?.[symbol] ?? 0,
19006
19310
  symbol,
19007
19311
  positions: positions3,
19008
19312
  symbolInfo,
19009
- sumUnitaryFunding
19313
+ sumUnitaryFunding,
19314
+ symbolLeverage
19010
19315
  });
19011
19316
  return estLiqPrice2;
19012
19317
  }, [
@@ -19017,7 +19322,8 @@ var useOrderEntry2 = (symbol, options = {}) => {
19017
19322
  symbol,
19018
19323
  maxQty,
19019
19324
  symbolInfo,
19020
- fundingRates
19325
+ fundingRates,
19326
+ symbolLeverage
19021
19327
  ]);
19022
19328
  const estLiqPriceDistance = useMemo(() => {
19023
19329
  if (!estLiqPrice) {
@@ -19089,6 +19395,9 @@ var useOrderEntry2 = (symbol, options = {}) => {
19089
19395
  orders: appendOrderMetadata(order.orders, orderMetadata)
19090
19396
  } : appendOrderMetadata(order, orderMetadata);
19091
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
+ }
19092
19401
  if (result.success) {
19093
19402
  let trackParams = {
19094
19403
  side: order.side,
@@ -19156,6 +19465,7 @@ var useOrderEntry2 = (symbol, options = {}) => {
19156
19465
  freeCollateral: effectiveMarginMode === MarginMode.ISOLATED ? freeCollateralUSDCOnly : freeCollateral,
19157
19466
  setValue: useMemoizedFn(setValue),
19158
19467
  setValues: useMemoizedFn(setValues),
19468
+ setValuesRaw: useMemoizedFn(setValuesRaw),
19159
19469
  symbolInfo: symbolInfo || EMPTY_OBJECT,
19160
19470
  metaState: meta,
19161
19471
  isMutating,
@@ -19163,6 +19473,107 @@ var useOrderEntry2 = (symbol, options = {}) => {
19163
19473
  symbolLeverage
19164
19474
  };
19165
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
+ );
19166
19577
  var useOrderEntity = (order, options) => {
19167
19578
  const { symbol } = order;
19168
19579
  const { maxQty } = options || {};
@@ -19439,6 +19850,7 @@ var useTpslPriceChecker = (params) => {
19439
19850
  slPrice,
19440
19851
  liqPrice,
19441
19852
  side,
19853
+ markPrice,
19442
19854
  currentPosition,
19443
19855
  orderQuantity
19444
19856
  } = params;
@@ -19494,6 +19906,17 @@ var useTpslPriceChecker = (params) => {
19494
19906
  if (slPrice === void 0 || liqPrice === void 0 || side === void 0 || liqPrice === null) {
19495
19907
  return null;
19496
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
+ }
19497
19920
  let slPriceDecimal;
19498
19921
  let liqPriceDecimal;
19499
19922
  try {
@@ -19520,6 +19943,7 @@ var useTpslPriceChecker = (params) => {
19520
19943
  slPrice,
19521
19944
  liqPrice,
19522
19945
  side,
19946
+ markPrice,
19523
19947
  warning_threshold,
19524
19948
  currentPosition,
19525
19949
  orderQuantity
@@ -19612,6 +20036,6 @@ var FlagKeys = /* @__PURE__ */ ((FlagKeys2) => {
19612
20036
  return FlagKeys2;
19613
20037
  })(FlagKeys || {});
19614
20038
 
19615
- 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 };
19616
20040
  //# sourceMappingURL=index.mjs.map
19617
20041
  //# sourceMappingURL=index.mjs.map