@kodiak-finance/orderly-utils 2.8.18 → 2.8.19-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -73,6 +73,41 @@ declare const getTimestamp: () => number;
73
73
  * ```
74
74
  */
75
75
  declare function formatSymbol(symbol: string, formatString?: string): string;
76
+ /**
77
+ * Optimize symbol text display by converting leading numbers to human-readable format
78
+ *
79
+ * This function matches numbers at the beginning of a symbol string and converts them
80
+ * to abbreviated format (K, M, B, T) for better readability.
81
+ *
82
+ * @param symbol - The symbol string to optimize (e.g., "1000000BABYDOGE")
83
+ * @param decimalPlaces - Number of decimal places for the abbreviated number (default: 0)
84
+ * @returns Optimized symbol string (e.g., "1MBABYDOGE")
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * // Basic usage - convert large numbers to abbreviated format
89
+ * optimizeSymbolDisplay("1000000BABYDOGE") // "1MBABYDOGE"
90
+ * optimizeSymbolDisplay("5000ETH") // "5KETH"
91
+ * optimizeSymbolDisplay("1500000000SHIB") // "1BSHIB"
92
+ * optimizeSymbolDisplay("2000000000000TOKEN") // "2TTOKEN"
93
+ *
94
+ * // With decimal places
95
+ * optimizeSymbolDisplay("1500000TOKEN", 1) // "1.5MTOKEN"
96
+ * optimizeSymbolDisplay("2750000COIN", 2) // "2.75MTOKEN"
97
+ *
98
+ * // Edge cases - no modification needed
99
+ * optimizeSymbolDisplay("BITCOIN") // "BITCOIN" (no leading number)
100
+ * optimizeSymbolDisplay("123.45TOKEN") // "123.45TOKEN" (less than 1000)
101
+ * optimizeSymbolDisplay("999COIN") // "999COIN" (less than 1000)
102
+ *
103
+ * // Usage in React component
104
+ * <SymbolText size="sm" optimizeDisplay={true} decimalPlaces={1}>
105
+ * 1000000BABYDOGE
106
+ * </SymbolText>
107
+ * // Renders: "1MBABYDOGE" with token icon
108
+ * ```
109
+ */
110
+ declare function optimizeSymbolDisplay(symbol: string, decimalPlaces?: number): string;
76
111
 
77
112
  /**
78
113
  * Trailing stop price calculation
@@ -97,4 +132,21 @@ declare function getTPSLDirection(inputs: {
97
132
  orderPrice: number;
98
133
  }): number;
99
134
 
100
- export { camelCaseToUnderscoreCase, capitalizeString, checkIsNaN, commify, commifyOptional, cutNumber, findLongestCommonSubString, formatSymbol, getBBOType, getGlobalObject, getPrecisionByNumber, getTPSLDirection, getTimestamp, getTrailingStopPrice, hex2int, int2hex, isSolana, isTestnet, numberToHumanStyle, parseChainIdToNumber, parseNumStr, praseChainId, praseChainIdToNumber, removeTrailingZeros, subtractDaysFromCurrentDate, timeConvertString, timestampToString, toNonExponential, todpIfNeed, transSymbolformString, windowGuard, zero };
135
+ declare enum FormatNumType {
136
+ pnl = 0,
137
+ notional = 1,
138
+ roi = 2,
139
+ assetValue = 3,
140
+ collateral = 4
141
+ }
142
+ declare function formatNum(type: FormatNumType, dp?: number, num?: number | Decimal | string, rm?: number): Decimal | undefined;
143
+ type FormatNumWithNamespace = typeof formatNum & {
144
+ pnl: (num?: number | Decimal | string) => Decimal | undefined;
145
+ notional: (num?: number | Decimal | string) => Decimal | undefined;
146
+ roi: (num?: number | Decimal | string, dp?: number) => Decimal | undefined;
147
+ assetValue: (num?: number | Decimal | string) => Decimal | undefined;
148
+ collateral: (num?: number | Decimal | string) => Decimal | undefined;
149
+ };
150
+ declare const formatNumWithNamespace: FormatNumWithNamespace;
151
+
152
+ export { camelCaseToUnderscoreCase, capitalizeString, checkIsNaN, commify, commifyOptional, cutNumber, findLongestCommonSubString, formatNumWithNamespace as formatNum, formatSymbol, getBBOType, getGlobalObject, getPrecisionByNumber, getTPSLDirection, getTimestamp, getTrailingStopPrice, hex2int, int2hex, isSolana, isTestnet, numberToHumanStyle, optimizeSymbolDisplay, parseChainIdToNumber, parseNumStr, praseChainId, praseChainIdToNumber, removeTrailingZeros, subtractDaysFromCurrentDate, timeConvertString, timestampToString, toNonExponential, todpIfNeed, transSymbolformString, windowGuard, zero };
package/dist/index.d.ts CHANGED
@@ -73,6 +73,41 @@ declare const getTimestamp: () => number;
73
73
  * ```
74
74
  */
75
75
  declare function formatSymbol(symbol: string, formatString?: string): string;
76
+ /**
77
+ * Optimize symbol text display by converting leading numbers to human-readable format
78
+ *
79
+ * This function matches numbers at the beginning of a symbol string and converts them
80
+ * to abbreviated format (K, M, B, T) for better readability.
81
+ *
82
+ * @param symbol - The symbol string to optimize (e.g., "1000000BABYDOGE")
83
+ * @param decimalPlaces - Number of decimal places for the abbreviated number (default: 0)
84
+ * @returns Optimized symbol string (e.g., "1MBABYDOGE")
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * // Basic usage - convert large numbers to abbreviated format
89
+ * optimizeSymbolDisplay("1000000BABYDOGE") // "1MBABYDOGE"
90
+ * optimizeSymbolDisplay("5000ETH") // "5KETH"
91
+ * optimizeSymbolDisplay("1500000000SHIB") // "1BSHIB"
92
+ * optimizeSymbolDisplay("2000000000000TOKEN") // "2TTOKEN"
93
+ *
94
+ * // With decimal places
95
+ * optimizeSymbolDisplay("1500000TOKEN", 1) // "1.5MTOKEN"
96
+ * optimizeSymbolDisplay("2750000COIN", 2) // "2.75MTOKEN"
97
+ *
98
+ * // Edge cases - no modification needed
99
+ * optimizeSymbolDisplay("BITCOIN") // "BITCOIN" (no leading number)
100
+ * optimizeSymbolDisplay("123.45TOKEN") // "123.45TOKEN" (less than 1000)
101
+ * optimizeSymbolDisplay("999COIN") // "999COIN" (less than 1000)
102
+ *
103
+ * // Usage in React component
104
+ * <SymbolText size="sm" optimizeDisplay={true} decimalPlaces={1}>
105
+ * 1000000BABYDOGE
106
+ * </SymbolText>
107
+ * // Renders: "1MBABYDOGE" with token icon
108
+ * ```
109
+ */
110
+ declare function optimizeSymbolDisplay(symbol: string, decimalPlaces?: number): string;
76
111
 
77
112
  /**
78
113
  * Trailing stop price calculation
@@ -97,4 +132,21 @@ declare function getTPSLDirection(inputs: {
97
132
  orderPrice: number;
98
133
  }): number;
99
134
 
100
- export { camelCaseToUnderscoreCase, capitalizeString, checkIsNaN, commify, commifyOptional, cutNumber, findLongestCommonSubString, formatSymbol, getBBOType, getGlobalObject, getPrecisionByNumber, getTPSLDirection, getTimestamp, getTrailingStopPrice, hex2int, int2hex, isSolana, isTestnet, numberToHumanStyle, parseChainIdToNumber, parseNumStr, praseChainId, praseChainIdToNumber, removeTrailingZeros, subtractDaysFromCurrentDate, timeConvertString, timestampToString, toNonExponential, todpIfNeed, transSymbolformString, windowGuard, zero };
135
+ declare enum FormatNumType {
136
+ pnl = 0,
137
+ notional = 1,
138
+ roi = 2,
139
+ assetValue = 3,
140
+ collateral = 4
141
+ }
142
+ declare function formatNum(type: FormatNumType, dp?: number, num?: number | Decimal | string, rm?: number): Decimal | undefined;
143
+ type FormatNumWithNamespace = typeof formatNum & {
144
+ pnl: (num?: number | Decimal | string) => Decimal | undefined;
145
+ notional: (num?: number | Decimal | string) => Decimal | undefined;
146
+ roi: (num?: number | Decimal | string, dp?: number) => Decimal | undefined;
147
+ assetValue: (num?: number | Decimal | string) => Decimal | undefined;
148
+ collateral: (num?: number | Decimal | string) => Decimal | undefined;
149
+ };
150
+ declare const formatNumWithNamespace: FormatNumWithNamespace;
151
+
152
+ export { camelCaseToUnderscoreCase, capitalizeString, checkIsNaN, commify, commifyOptional, cutNumber, findLongestCommonSubString, formatNumWithNamespace as formatNum, formatSymbol, getBBOType, getGlobalObject, getPrecisionByNumber, getTPSLDirection, getTimestamp, getTrailingStopPrice, hex2int, int2hex, isSolana, isTestnet, numberToHumanStyle, optimizeSymbolDisplay, parseChainIdToNumber, parseNumStr, praseChainId, praseChainIdToNumber, removeTrailingZeros, subtractDaysFromCurrentDate, timeConvertString, timestampToString, toNonExponential, todpIfNeed, transSymbolformString, windowGuard, zero };
package/dist/index.js CHANGED
@@ -1,2 +1,514 @@
1
- "use strict";var O=Object.create;var d=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty;var A=(e,t)=>{for(var r in t)d(e,r,{get:t[r],enumerable:!0})},p=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of y(t))!I.call(e,i)&&i!==r&&d(e,i,{get:()=>t[i],enumerable:!(n=h(t,i))||n.enumerable});return e};var b=(e,t,r)=>(r=e!=null?O(D(e)):{},p(t||!e||!e.__esModule?d(r,"default",{value:e,enumerable:!0}):r,e)),C=e=>p(d({},"__esModule",{value:!0}),e);var oe={};A(oe,{Decimal:()=>a,camelCaseToUnderscoreCase:()=>v,capitalizeString:()=>V,checkIsNaN:()=>G,commify:()=>N,commifyOptional:()=>R,cutNumber:()=>_,dayjs:()=>w.default,findLongestCommonSubString:()=>ee,formatSymbol:()=>te,getBBOType:()=>ne,getGlobalObject:()=>g,getPrecisionByNumber:()=>B,getTPSLDirection:()=>ie,getTimestamp:()=>E,getTrailingStopPrice:()=>re,hex2int:()=>m,int2hex:()=>Q,isSolana:()=>q,isTestnet:()=>Z,numberToHumanStyle:()=>L,parseChainIdToNumber:()=>X,parseNumStr:()=>Y,praseChainId:()=>K,praseChainIdToNumber:()=>T,removeTrailingZeros:()=>F,subtractDaysFromCurrentDate:()=>z,timeConvertString:()=>W,timestampToString:()=>j,toNonExponential:()=>x,todpIfNeed:()=>H,transSymbolformString:()=>J,windowGuard:()=>S,zero:()=>U});module.exports=C(oe);var c=b(require("decimal.js-light"));c.default.set({rounding:c.default.ROUND_DOWN});var a=c.default,_=(e,t)=>{},U=new c.default(0),R=(e,t)=>{if(typeof e=="string"&&Number.isNaN(Number(e)))return(t==null?void 0:t.fallback)||"--";let r=(t==null?void 0:t.prefix)||"";if(typeof e=="undefined"||e===null)return r+((t==null?void 0:t.fallback)||"--");let n=N(e,t==null?void 0:t.fix);if(t&&t.padEnd&&t.fix){let i=(t==null?void 0:t.fillString)||"0",o=n.includes("."),f=n.split(".");return o?r+f[0]+"."+f[1].padEnd(t.fix,i):r+f[0]+"."+"".padEnd(t.fix,i)}return r+n},$=/\B(?=(\d{3})+(?!\d))/g,N=(e,t)=>{let r=`${e}`,n=r.split("."),i=n[0],o=n[1],f=r.endsWith(".")&&r.length>1,l=i.replace($,",")+(o?"."+o.substring(0,t||o.length):f?".":"");return t===0&&l.includes(".")?l.substring(0,l.indexOf(".")):l},P=/\d(?:\.(\d*))?e([+-]\d+)/,x=e=>{let t=e.toExponential().match(P);return Array.isArray(t)?e.toFixed(Math.max(0,(t[1]||"").length-t[2])):e},B=e=>{e=x(Number(e));let t=e.toString().split(".");return t[1]?t[1].length:0};function L(e,t=2,r){let{padding:n}=r||{},i=["","K","M","B","T"],o=0;for(;e>=1e3&&o<i.length-1;)e/=1e3,o++;return`${new c.default(e).toFixed(t,c.default.ROUND_DOWN).toString().replace(/\.0+$/,"")}${i[o]}`}function Y(e){let r=e.toString().replace(/,/g,""),n=new c.default(r),i=r.slice(-1);if(Number.isNaN(n.toNumber()))return;let o;switch(i){case"k":case"K":o=n.mul(1e3);break;case"m":case"M":o=n.mul(1e6);break;case"b":case"B":o=n.mul(1e9);break;case"t":case"T":o=n.mul(1e12);break;default:o=n}return o}var k=/^[-+]?[0-9]+(\.[0-9]+)?[eE][-+]?[0-9]+$/,M=/(\.[0-9]*[1-9])0+$/,F=(e,t=16)=>{let r=`${e}`,n=k.test(r);return!e.toString().includes(".")&&!n?`${e}`:new c.default(e).toFixed(t).replace(M,"$1")},H=(e,t)=>{if(e===void 0||e===""||(typeof e=="number"&&(e=e.toString()),e.endsWith(".")))return e;let r=e.split(".");return r.length===1||r[1].length<=t||!r[1]?e:`${r[0]}.${r[1].substring(0,t)}`},G=e=>e===void 0||e===""||e===null?!0:Number.isNaN(Number(e));var W=e=>{e/=1e3;let t=Math.floor(e/3600),r=Math.floor(e/60%60),n=Math.floor(e%60);return[t,r,n]},j=e=>{let t=new Date(e),r=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),f=String(t.getMinutes()).padStart(2,"0"),l=String(t.getSeconds()).padStart(2,"0");return`${r}-${n}-${i} ${o}:${f}:${l}`};function z(e,t){let r=t||new Date,n=new Date(r);return n.setDate(r.getDate()-e),n}var u=require("@kodiak-finance/orderly-types"),m=e=>parseInt(e),Q=e=>`0x${e.toString(16)}`,K=e=>typeof e=="string"?m(e):e,T=e=>typeof e=="string"&&e.startsWith("0x")&&/^[a-f0-9]+$/iu.test(e.slice(2))?m(e):e,X=T,Z=e=>[u.ARBITRUM_TESTNET_CHAINID,u.SOLANA_TESTNET_CHAINID,u.STORY_TESTNET_CHAINID,u.MONAD_TESTNET_CHAINID,u.ABSTRACT_TESTNET_CHAINID,u.BSC_TESTNET_CHAINID].includes(e),q=e=>[u.SOLANA_TESTNET_CHAINID,u.SOLANA_MAINNET_CHAINID].includes(e);function V(e){let t=e.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function J(e){let t=e.split("_");if(t.length!==3)throw new Error("Invalid string format");let[r,n,i]=t;if(!r.startsWith("PERP"))throw new Error("Invalid string format");return`${n}-${r}`}function v(e){return e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase()}var ee=(e,t)=>{for(let r=0;r<e.length;r++){let n=e.at(r),i=t.at(r);if(n!==i)return r}return-1};var S=e=>{typeof window!="undefined"&&e()},g=()=>{if(typeof globalThis!="undefined")return globalThis;if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;throw new Error("cannot find the global object")},E=()=>{var e;if(typeof window!="undefined"){let t=(e=g())==null?void 0:e.__ORDERLY_timestamp_offset;if(typeof t=="number")return Date.now()+(t||0)}return Date.now()};var w=b(require("dayjs"));function te(e,t="base-type"){if(!e)return"";let r=e.split("_"),n=r[0],i=r[1],o=r[2];return t.replace("type",n).replace("base",i).replace("quote",o)}var s=require("@kodiak-finance/orderly-types");function re(e){let{side:t,extreme_price:r,callback_value:n,callback_rate:i}=e,o=t===s.OrderSide.BUY;return r?n?o?new a(r).plus(n).toNumber():new a(r).minus(n).toNumber():i?o?new a(r).mul(new a(1).plus(i)).toNumber():new a(r).mul(new a(1).minus(i)).toNumber():0:0}function ne(e){let{type:t,side:r,level:n}=e;if(t===s.OrderType.ASK){if(n===s.OrderLevel.ONE)return r===s.OrderSide.BUY?s.BBOOrderType.COUNTERPARTY1:s.BBOOrderType.QUEUE1;if(n===s.OrderLevel.FIVE)return r===s.OrderSide.BUY?s.BBOOrderType.COUNTERPARTY5:s.BBOOrderType.QUEUE5}if(t===s.OrderType.BID){if(n===s.OrderLevel.ONE)return r===s.OrderSide.BUY?s.BBOOrderType.QUEUE1:s.BBOOrderType.COUNTERPARTY1;if(n===s.OrderLevel.FIVE)return r===s.OrderSide.BUY?s.BBOOrderType.QUEUE5:s.BBOOrderType.COUNTERPARTY5}}function ie(e){let{side:t,type:r,closePrice:n,orderPrice:i}=e,o=1;return t===s.OrderSide.BUY&&(r==="tp"?o=n>=i?1:-1:o=n<i?-1:1),t===s.OrderSide.SELL&&(r==="tp"?o=n<=i?1:-1:o=n>i?-1:1),o}0&&(module.exports={Decimal,camelCaseToUnderscoreCase,capitalizeString,checkIsNaN,commify,commifyOptional,cutNumber,dayjs,findLongestCommonSubString,formatSymbol,getBBOType,getGlobalObject,getPrecisionByNumber,getTPSLDirection,getTimestamp,getTrailingStopPrice,hex2int,int2hex,isSolana,isTestnet,numberToHumanStyle,parseChainIdToNumber,parseNumStr,praseChainId,praseChainIdToNumber,removeTrailingZeros,subtractDaysFromCurrentDate,timeConvertString,timestampToString,toNonExponential,todpIfNeed,transSymbolformString,windowGuard,zero});
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ Decimal: () => decimal_default,
34
+ camelCaseToUnderscoreCase: () => camelCaseToUnderscoreCase,
35
+ capitalizeString: () => capitalizeString,
36
+ checkIsNaN: () => checkIsNaN,
37
+ commify: () => commify,
38
+ commifyOptional: () => commifyOptional,
39
+ cutNumber: () => cutNumber,
40
+ dayjs: () => import_dayjs.default,
41
+ findLongestCommonSubString: () => findLongestCommonSubString,
42
+ formatNum: () => formatNumWithNamespace,
43
+ formatSymbol: () => formatSymbol,
44
+ getBBOType: () => getBBOType,
45
+ getGlobalObject: () => getGlobalObject,
46
+ getPrecisionByNumber: () => getPrecisionByNumber,
47
+ getTPSLDirection: () => getTPSLDirection,
48
+ getTimestamp: () => getTimestamp,
49
+ getTrailingStopPrice: () => getTrailingStopPrice,
50
+ hex2int: () => hex2int,
51
+ int2hex: () => int2hex,
52
+ isSolana: () => isSolana,
53
+ isTestnet: () => isTestnet,
54
+ numberToHumanStyle: () => numberToHumanStyle,
55
+ optimizeSymbolDisplay: () => optimizeSymbolDisplay,
56
+ parseChainIdToNumber: () => parseChainIdToNumber,
57
+ parseNumStr: () => parseNumStr,
58
+ praseChainId: () => praseChainId,
59
+ praseChainIdToNumber: () => praseChainIdToNumber,
60
+ removeTrailingZeros: () => removeTrailingZeros,
61
+ subtractDaysFromCurrentDate: () => subtractDaysFromCurrentDate,
62
+ timeConvertString: () => timeConvertString,
63
+ timestampToString: () => timestampToString,
64
+ toNonExponential: () => toNonExponential,
65
+ todpIfNeed: () => todpIfNeed,
66
+ transSymbolformString: () => transSymbolformString,
67
+ windowGuard: () => windowGuard,
68
+ zero: () => zero
69
+ });
70
+ module.exports = __toCommonJS(src_exports);
71
+
72
+ // src/decimal.ts
73
+ var import_decimal = __toESM(require("decimal.js-light"));
74
+ import_decimal.default.set({ rounding: import_decimal.default.ROUND_DOWN });
75
+ var decimal_default = import_decimal.default;
76
+ var cutNumber = (num, lenght) => {
77
+ };
78
+ var zero = new import_decimal.default(0);
79
+ var commifyOptional = (num, options) => {
80
+ if (typeof num === "string" && Number.isNaN(Number(num))) {
81
+ return (options == null ? void 0 : options.fallback) || "--";
82
+ }
83
+ const prefix = (options == null ? void 0 : options.prefix) || "";
84
+ if (typeof num === "undefined" || num === null) {
85
+ return prefix + ((options == null ? void 0 : options.fallback) || "--");
86
+ }
87
+ const value = commify(num, options == null ? void 0 : options.fix);
88
+ if (options && options.padEnd && options.fix) {
89
+ const fillString = (options == null ? void 0 : options.fillString) || "0";
90
+ const hasDecimal = value.includes(".");
91
+ const list = value.split(".");
92
+ if (hasDecimal) {
93
+ return prefix + list[0] + "." + list[1].padEnd(options.fix, fillString);
94
+ }
95
+ return prefix + list[0] + "." + "".padEnd(options.fix, fillString);
96
+ }
97
+ return prefix + value;
98
+ };
99
+ var THOUSANDS_REGEXP = /\B(?=(\d{3})+(?!\d))/g;
100
+ var commify = (num, fix) => {
101
+ const str = `${num}`;
102
+ const parts = str.split(".");
103
+ const numberPart = parts[0];
104
+ const decimalPart = parts[1];
105
+ const endsWithPoint = str.endsWith(".") && str.length > 1;
106
+ const result = numberPart.replace(THOUSANDS_REGEXP, ",") + (decimalPart ? "." + decimalPart.substring(0, fix || decimalPart.length) : endsWithPoint ? "." : "");
107
+ if (fix === 0 && result.includes(".")) {
108
+ return result.substring(0, result.indexOf("."));
109
+ }
110
+ return result;
111
+ };
112
+ var SCIENTIFICNOTATION_REGEX = /\d(?:\.(\d*))?e([+-]\d+)/;
113
+ var toNonExponential = (num) => {
114
+ const m = num.toExponential().match(SCIENTIFICNOTATION_REGEX);
115
+ if (!Array.isArray(m)) {
116
+ return num;
117
+ }
118
+ return num.toFixed(
119
+ Math.max(0, (m[1] || "").length - m[2])
120
+ );
121
+ };
122
+ var getPrecisionByNumber = (num) => {
123
+ num = toNonExponential(Number(num));
124
+ const parts = num.toString().split(".");
125
+ return parts[1] ? parts[1].length : 0;
126
+ };
127
+ function numberToHumanStyle(number, decimalPlaces = 2, options) {
128
+ const { padding } = options || {};
129
+ const abbreviations = ["", "K", "M", "B", "T"];
130
+ let index = 0;
131
+ while (number >= 1e3 && index < abbreviations.length - 1) {
132
+ number /= 1e3;
133
+ index++;
134
+ }
135
+ const roundedNumber = new import_decimal.default(number).toFixed(decimalPlaces, import_decimal.default.ROUND_DOWN).toString().replace(/\.0+$/, "");
136
+ return `${roundedNumber}${abbreviations[index]}`;
137
+ }
138
+ function parseNumStr(str) {
139
+ const value = str.toString();
140
+ const cleanedStr = value.replace(/,/g, "");
141
+ const numberPart = new import_decimal.default(cleanedStr);
142
+ const unitPart = cleanedStr.slice(-1);
143
+ if (Number.isNaN(numberPart.toNumber())) {
144
+ return void 0;
145
+ }
146
+ let result;
147
+ switch (unitPart) {
148
+ case "k":
149
+ case "K":
150
+ result = numberPart.mul(1e3);
151
+ break;
152
+ case "m":
153
+ case "M":
154
+ result = numberPart.mul(1e6);
155
+ break;
156
+ case "b":
157
+ case "B":
158
+ result = numberPart.mul(1e9);
159
+ break;
160
+ case "t":
161
+ case "T":
162
+ result = numberPart.mul(1e12);
163
+ break;
164
+ default:
165
+ result = numberPart;
166
+ }
167
+ return result;
168
+ }
169
+ var SCIENTIFICNOTATIONPATTERN = /^[-+]?[0-9]+(\.[0-9]+)?[eE][-+]?[0-9]+$/;
170
+ var TRAILINGZERODECIMAL_REGEX = /(\.[0-9]*[1-9])0+$/;
171
+ var removeTrailingZeros = (value, fixedCount = 16) => {
172
+ const text = `${value}`;
173
+ const isScientific = SCIENTIFICNOTATIONPATTERN.test(text);
174
+ if (!value.toString().includes(".") && !isScientific) {
175
+ return `${value}`;
176
+ }
177
+ const formattedNumber = new import_decimal.default(value).toFixed(fixedCount).replace(TRAILINGZERODECIMAL_REGEX, "$1");
178
+ return formattedNumber;
179
+ };
180
+ var todpIfNeed = (value, dp) => {
181
+ if (value === void 0 || value === "") {
182
+ return value;
183
+ }
184
+ if (typeof value === "number") {
185
+ value = value.toString();
186
+ }
187
+ if (value.endsWith(".")) {
188
+ return value;
189
+ }
190
+ const numbers = value.split(".");
191
+ if (numbers.length === 1) {
192
+ return value;
193
+ }
194
+ if (numbers[1].length <= dp || !numbers[1]) {
195
+ return value;
196
+ }
197
+ return `${numbers[0]}.${numbers[1].substring(0, dp)}`;
198
+ };
199
+ var checkIsNaN = (value) => {
200
+ if (value === void 0 || value === "" || value === null) {
201
+ return true;
202
+ }
203
+ return Number.isNaN(Number(value));
204
+ };
205
+
206
+ // src/dateTime.ts
207
+ var timeConvertString = (time) => {
208
+ time /= 1e3;
209
+ const h = Math.floor(time / 3600);
210
+ const m = Math.floor(time / 60 % 60);
211
+ const s = Math.floor(time % 60);
212
+ return [h, m, s];
213
+ };
214
+ var timestampToString = (timestamp) => {
215
+ const date = new Date(timestamp);
216
+ const year = date.getFullYear();
217
+ const month = String(date.getMonth() + 1).padStart(2, "0");
218
+ const day = String(date.getDate()).padStart(2, "0");
219
+ const hours = String(date.getHours()).padStart(2, "0");
220
+ const minutes = String(date.getMinutes()).padStart(2, "0");
221
+ const seconds = String(date.getSeconds()).padStart(2, "0");
222
+ return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
223
+ };
224
+ function subtractDaysFromCurrentDate(days, startDate) {
225
+ const currentDate = startDate || /* @__PURE__ */ new Date();
226
+ const resultDate = new Date(currentDate);
227
+ resultDate.setDate(currentDate.getDate() - days);
228
+ return resultDate;
229
+ }
230
+
231
+ // src/chain.ts
232
+ var import_orderly_types = require("@kodiak-finance/orderly-types");
233
+ var hex2int = (chainId) => parseInt(chainId);
234
+ var int2hex = (chainId) => `0x${chainId.toString(16)}`;
235
+ var praseChainId = (chainId) => {
236
+ if (typeof chainId === "string")
237
+ return hex2int(chainId);
238
+ return chainId;
239
+ };
240
+ var praseChainIdToNumber = (chainId) => {
241
+ if (typeof chainId === "string" && chainId.startsWith("0x") && /^[a-f0-9]+$/iu.test(chainId.slice(2)))
242
+ return hex2int(chainId);
243
+ return chainId;
244
+ };
245
+ var parseChainIdToNumber = praseChainIdToNumber;
246
+ var isTestnet = (chainId) => {
247
+ const testnetIds = [
248
+ import_orderly_types.ARBITRUM_TESTNET_CHAINID,
249
+ import_orderly_types.SOLANA_TESTNET_CHAINID,
250
+ import_orderly_types.STORY_TESTNET_CHAINID,
251
+ import_orderly_types.MONAD_TESTNET_CHAINID,
252
+ import_orderly_types.ABSTRACT_TESTNET_CHAINID,
253
+ import_orderly_types.BSC_TESTNET_CHAINID
254
+ ];
255
+ return testnetIds.includes(chainId);
256
+ };
257
+ var isSolana = (chainId) => {
258
+ return [import_orderly_types.SOLANA_TESTNET_CHAINID, import_orderly_types.SOLANA_MAINNET_CHAINID].includes(chainId);
259
+ };
260
+
261
+ // src/string.ts
262
+ function capitalizeString(str) {
263
+ const lowercaseStr = str.toLowerCase();
264
+ const capitalizedStr = lowercaseStr.charAt(0).toUpperCase() + lowercaseStr.slice(1);
265
+ return capitalizedStr;
266
+ }
267
+ function transSymbolformString(input) {
268
+ const parts = input.split("_");
269
+ if (parts.length !== 3) {
270
+ throw new Error("Invalid string format");
271
+ }
272
+ const [first, second, third] = parts;
273
+ if (!first.startsWith("PERP")) {
274
+ throw new Error("Invalid string format");
275
+ }
276
+ const result = `${second}-${first}`;
277
+ return result;
278
+ }
279
+ function camelCaseToUnderscoreCase(str) {
280
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
281
+ }
282
+ var findLongestCommonSubString = (str1, str2) => {
283
+ for (let index = 0; index < str1.length; index++) {
284
+ const ele1 = str1.at(index);
285
+ const ele2 = str2.at(index);
286
+ if (ele1 === ele2) {
287
+ continue;
288
+ }
289
+ return index;
290
+ }
291
+ return -1;
292
+ };
293
+
294
+ // src/window.ts
295
+ var windowGuard = (cb) => {
296
+ if (typeof window !== "undefined") {
297
+ cb();
298
+ }
299
+ };
300
+ var getGlobalObject = () => {
301
+ if (typeof globalThis !== "undefined") {
302
+ return globalThis;
303
+ }
304
+ if (typeof self !== "undefined") {
305
+ return self;
306
+ }
307
+ if (typeof window !== "undefined") {
308
+ return window;
309
+ }
310
+ if (typeof global !== "undefined") {
311
+ return global;
312
+ }
313
+ throw new Error("cannot find the global object");
314
+ };
315
+ var getTimestamp = () => {
316
+ var _a;
317
+ if (typeof window !== "undefined") {
318
+ const timeOffset = (_a = getGlobalObject()) == null ? void 0 : _a.__ORDERLY_timestamp_offset;
319
+ if (typeof timeOffset === "number") {
320
+ return Date.now() + (timeOffset || 0);
321
+ }
322
+ }
323
+ return Date.now();
324
+ };
325
+
326
+ // src/index.ts
327
+ var import_dayjs = __toESM(require("dayjs"));
328
+
329
+ // src/symbol.ts
330
+ function formatSymbol(symbol, formatString = "base-type") {
331
+ if (!symbol) {
332
+ return "";
333
+ }
334
+ const arr = symbol.split("_");
335
+ const type = arr[0];
336
+ const base = arr[1];
337
+ const quote = arr[2];
338
+ return formatString.replace("type", type).replace("base", base).replace("quote", quote);
339
+ }
340
+ function optimizeSymbolDisplay(symbol, decimalPlaces = 0) {
341
+ if (!symbol) {
342
+ return "";
343
+ }
344
+ const numberRegex = /^(\d+(?:\.\d+)?)/;
345
+ const match = symbol.match(numberRegex);
346
+ if (!match) {
347
+ return symbol;
348
+ }
349
+ const numberPart = match[1];
350
+ const textPart = symbol.slice(numberPart.length);
351
+ const numericValue = parseFloat(numberPart);
352
+ if (numericValue < 1e3) {
353
+ return symbol;
354
+ }
355
+ const abbreviatedNumber = numberToHumanStyle(numericValue, decimalPlaces);
356
+ return abbreviatedNumber + textPart;
357
+ }
358
+
359
+ // src/order.ts
360
+ var import_orderly_types2 = require("@kodiak-finance/orderly-types");
361
+ function getTrailingStopPrice(order) {
362
+ const { side, extreme_price, callback_value, callback_rate } = order;
363
+ const isBuy = side === import_orderly_types2.OrderSide.BUY;
364
+ if (!extreme_price) {
365
+ return 0;
366
+ }
367
+ if (callback_value) {
368
+ return isBuy ? new decimal_default(extreme_price).plus(callback_value).toNumber() : new decimal_default(extreme_price).minus(callback_value).toNumber();
369
+ }
370
+ if (callback_rate) {
371
+ return isBuy ? new decimal_default(extreme_price).mul(new decimal_default(1).plus(callback_rate)).toNumber() : new decimal_default(extreme_price).mul(new decimal_default(1).minus(callback_rate)).toNumber();
372
+ }
373
+ return 0;
374
+ }
375
+ function getBBOType(options) {
376
+ const { type, side, level } = options;
377
+ if (type === import_orderly_types2.OrderType.ASK) {
378
+ if (level === import_orderly_types2.OrderLevel.ONE) {
379
+ return side === import_orderly_types2.OrderSide.BUY ? import_orderly_types2.BBOOrderType.COUNTERPARTY1 : import_orderly_types2.BBOOrderType.QUEUE1;
380
+ }
381
+ if (level === import_orderly_types2.OrderLevel.FIVE) {
382
+ return side === import_orderly_types2.OrderSide.BUY ? import_orderly_types2.BBOOrderType.COUNTERPARTY5 : import_orderly_types2.BBOOrderType.QUEUE5;
383
+ }
384
+ }
385
+ if (type === import_orderly_types2.OrderType.BID) {
386
+ if (level === import_orderly_types2.OrderLevel.ONE) {
387
+ return side === import_orderly_types2.OrderSide.BUY ? import_orderly_types2.BBOOrderType.QUEUE1 : import_orderly_types2.BBOOrderType.COUNTERPARTY1;
388
+ }
389
+ if (level === import_orderly_types2.OrderLevel.FIVE) {
390
+ return side === import_orderly_types2.OrderSide.BUY ? import_orderly_types2.BBOOrderType.QUEUE5 : import_orderly_types2.BBOOrderType.COUNTERPARTY5;
391
+ }
392
+ }
393
+ }
394
+ function getTPSLDirection(inputs) {
395
+ const { side, type, closePrice, orderPrice } = inputs;
396
+ let direction = 1;
397
+ if (side === import_orderly_types2.OrderSide.BUY) {
398
+ if (type === "tp") {
399
+ direction = closePrice >= orderPrice ? 1 : -1;
400
+ } else {
401
+ direction = closePrice < orderPrice ? -1 : 1;
402
+ }
403
+ }
404
+ if (side === import_orderly_types2.OrderSide.SELL) {
405
+ if (type === "tp") {
406
+ direction = closePrice <= orderPrice ? 1 : -1;
407
+ } else {
408
+ direction = closePrice > orderPrice ? -1 : 1;
409
+ }
410
+ }
411
+ return direction;
412
+ }
413
+
414
+ // src/formatNum.ts
415
+ function formatNum(type, dp = 2, num, rm) {
416
+ const decimalNum = parseToDecimal(num);
417
+ if (!decimalNum) {
418
+ return void 0;
419
+ }
420
+ const isMoreThanZero = decimalNum.greaterThan(0);
421
+ switch (type) {
422
+ case 0 /* pnl */:
423
+ case 2 /* roi */:
424
+ const innerRm = rm != null ? rm : isMoreThanZero ? decimal_default.ROUND_DOWN : decimal_default.ROUND_UP;
425
+ return format(decimalNum, dp, innerRm);
426
+ case 1 /* notional */:
427
+ return format(decimalNum, dp, rm != null ? rm : decimal_default.ROUND_DOWN);
428
+ case 3 /* assetValue */:
429
+ return format(decimalNum, dp, rm != null ? rm : decimal_default.ROUND_DOWN);
430
+ case 4 /* collateral */:
431
+ return format(decimalNum, dp, rm != null ? rm : decimal_default.ROUND_DOWN);
432
+ }
433
+ }
434
+ function format(num, dp, rm) {
435
+ return num.toDecimalPlaces(dp, rm);
436
+ }
437
+ function parseToDecimal(num) {
438
+ try {
439
+ if (num instanceof decimal_default) {
440
+ return num;
441
+ }
442
+ if (!num) {
443
+ return void 0;
444
+ }
445
+ if (typeof num === "number") {
446
+ return new decimal_default(num);
447
+ }
448
+ if (typeof num === "string") {
449
+ if (!num.trim()) {
450
+ return void 0;
451
+ }
452
+ return new decimal_default(num);
453
+ }
454
+ return num;
455
+ } catch (error) {
456
+ return void 0;
457
+ }
458
+ }
459
+ var formatNumWithNamespace = formatNum;
460
+ formatNumWithNamespace.pnl = (num) => {
461
+ return formatNum(0 /* pnl */, 2, num);
462
+ };
463
+ formatNumWithNamespace.notional = (num) => {
464
+ return formatNum(1 /* notional */, 2, num);
465
+ };
466
+ formatNumWithNamespace.roi = (num, dp) => {
467
+ return formatNum(2 /* roi */, dp != null ? dp : 4, num);
468
+ };
469
+ formatNumWithNamespace.assetValue = (num) => {
470
+ return formatNum(3 /* assetValue */, 2, num);
471
+ };
472
+ formatNumWithNamespace.collateral = (num) => {
473
+ return formatNum(4 /* collateral */, 2, num);
474
+ };
475
+ // Annotate the CommonJS export names for ESM import in node:
476
+ 0 && (module.exports = {
477
+ Decimal,
478
+ camelCaseToUnderscoreCase,
479
+ capitalizeString,
480
+ checkIsNaN,
481
+ commify,
482
+ commifyOptional,
483
+ cutNumber,
484
+ dayjs,
485
+ findLongestCommonSubString,
486
+ formatNum,
487
+ formatSymbol,
488
+ getBBOType,
489
+ getGlobalObject,
490
+ getPrecisionByNumber,
491
+ getTPSLDirection,
492
+ getTimestamp,
493
+ getTrailingStopPrice,
494
+ hex2int,
495
+ int2hex,
496
+ isSolana,
497
+ isTestnet,
498
+ numberToHumanStyle,
499
+ optimizeSymbolDisplay,
500
+ parseChainIdToNumber,
501
+ parseNumStr,
502
+ praseChainId,
503
+ praseChainIdToNumber,
504
+ removeTrailingZeros,
505
+ subtractDaysFromCurrentDate,
506
+ timeConvertString,
507
+ timestampToString,
508
+ toNonExponential,
509
+ todpIfNeed,
510
+ transSymbolformString,
511
+ windowGuard,
512
+ zero
513
+ });
2
514
  //# sourceMappingURL=index.js.map