@orderly.network/hooks 0.0.4

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 ADDED
@@ -0,0 +1,1469 @@
1
+ import { createContext, useContext, useState, useEffect, useCallback, useRef, useMemo } from 'react';
2
+ import useSWR from 'swr';
3
+ export { default as useSWR } from 'swr';
4
+ import { WebSocketClient, get, post } from '@orderly.network/net';
5
+ import useSWRMutation from 'swr/mutation';
6
+ import { getMockSigner, SimpleDI, Account } from '@orderly.network/core';
7
+ import useConstant from 'use-constant';
8
+ export { default as useConstant } from 'use-constant';
9
+ import { useObservable, useEventCallback } from 'rxjs-hooks';
10
+ export { useEventCallback, useObservable } from 'rxjs-hooks';
11
+ import { BehaviorSubject, merge, iif } from 'rxjs';
12
+ import { map, combineLatestWith, startWith, debounceTime, switchMap, scan, filter, distinct, withLatestFrom } from 'rxjs/operators';
13
+ import { compose, defaultTo, head, last, pathOr, pick } from 'ramda';
14
+ import { Decimal, zero, getPrecisionByNumber, timeConvertString } from '@orderly.network/utils';
15
+ import { OrderSide, OrderType } from '@orderly.network/types';
16
+ import { useFormik } from 'formik';
17
+ import { positions, account, order } from '@orderly.network/futures';
18
+ import useSWRInfinite from 'swr/infinite';
19
+
20
+ var __defProp = Object.defineProperty;
21
+ var __defProps = Object.defineProperties;
22
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
23
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
24
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
25
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
26
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
27
+ var __spreadValues = (a, b) => {
28
+ for (var prop in b || (b = {}))
29
+ if (__hasOwnProp.call(b, prop))
30
+ __defNormalProp(a, prop, b[prop]);
31
+ if (__getOwnPropSymbols)
32
+ for (var prop of __getOwnPropSymbols(b)) {
33
+ if (__propIsEnum.call(b, prop))
34
+ __defNormalProp(a, prop, b[prop]);
35
+ }
36
+ return a;
37
+ };
38
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
39
+ var __objRest = (source, exclude) => {
40
+ var target = {};
41
+ for (var prop in source)
42
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
43
+ target[prop] = source[prop];
44
+ if (source != null && __getOwnPropSymbols)
45
+ for (var prop of __getOwnPropSymbols(source)) {
46
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
47
+ target[prop] = source[prop];
48
+ }
49
+ return target;
50
+ };
51
+ var __export = (target, all) => {
52
+ for (var name in all)
53
+ __defProp(target, name, { get: all[name], enumerable: true });
54
+ };
55
+ var __async = (__this, __arguments, generator) => {
56
+ return new Promise((resolve, reject) => {
57
+ var fulfilled = (value) => {
58
+ try {
59
+ step(generator.next(value));
60
+ } catch (e) {
61
+ reject(e);
62
+ }
63
+ };
64
+ var rejected = (value) => {
65
+ try {
66
+ step(generator.throw(value));
67
+ } catch (e) {
68
+ reject(e);
69
+ }
70
+ };
71
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
72
+ step((generator = generator.apply(__this, __arguments)).next());
73
+ });
74
+ };
75
+ var OrderlyContext = createContext({
76
+ // configStore: new MemoryConfigStore(),
77
+ });
78
+ var OrderlyProvider = OrderlyContext.Provider;
79
+ var fetcher = (url, init = {}, queryOptions) => get(url, init, queryOptions == null ? void 0 : queryOptions.formatter);
80
+
81
+ // src/useQuery.ts
82
+ var useQuery = (query, options) => {
83
+ const { apiBaseUrl } = useContext(OrderlyContext);
84
+ const _a = options || {}, { formatter } = _a, swrOptions = __objRest(_a, ["formatter"]);
85
+ if (!query.startsWith("/public")) {
86
+ throw new Error("useQuery is only for public api");
87
+ }
88
+ if (typeof apiBaseUrl === "undefined") {
89
+ throw new Error("please add OrderlyProvider to your app");
90
+ }
91
+ return useSWR(
92
+ `${apiBaseUrl}${query}`,
93
+ (url, init) => fetcher(url, init, { formatter }),
94
+ swrOptions
95
+ );
96
+ };
97
+ var fetcher2 = (url, options) => {
98
+ return post(url, options.arg.data, {
99
+ headers: __spreadProps(__spreadValues({}, options.arg.signature), {
100
+ "orderly-account-id": "0x47ab075adca7dfe9dd206eb7c50a10f7b99f4f08fa6c3abd4c170d438e15093b"
101
+ })
102
+ });
103
+ };
104
+ var useMutation = (url, options) => {
105
+ const { apiBaseUrl } = useContext(OrderlyContext);
106
+ if (!url.startsWith("http")) {
107
+ url = `${apiBaseUrl}${url}`;
108
+ }
109
+ const signer = getMockSigner();
110
+ const { trigger, data, error, reset, isMutating } = useSWRMutation(
111
+ url,
112
+ fetcher2,
113
+ options
114
+ );
115
+ const mutation = (data2) => __async(void 0, null, function* () {
116
+ const payload = {
117
+ method: "POST",
118
+ url,
119
+ data: data2
120
+ };
121
+ const signature = yield signer.sign(payload);
122
+ return trigger({ data: data2, signature });
123
+ });
124
+ return {
125
+ mutation,
126
+ data,
127
+ error,
128
+ reset,
129
+ isMutating
130
+ };
131
+ };
132
+ var signatureMiddleware = (useSWRNext) => {
133
+ return (key, fetcher4, config) => {
134
+ const extendedFetcher = (url) => __async(void 0, null, function* () {
135
+ const signer = getMockSigner();
136
+ const payload = {
137
+ method: "GET",
138
+ url
139
+ };
140
+ const signature = yield signer.sign(payload);
141
+ return fetcher4(url, {
142
+ headers: __spreadProps(__spreadValues({}, signature), {
143
+ "orderly-account-id": "0x47ab075adca7dfe9dd206eb7c50a10f7b99f4f08fa6c3abd4c170d438e15093b"
144
+ })
145
+ });
146
+ });
147
+ return useSWRNext(key, extendedFetcher, config);
148
+ };
149
+ };
150
+ var usePrivateQuery = (query, options) => {
151
+ var _b;
152
+ const { apiBaseUrl } = useContext(OrderlyContext);
153
+ const _a = options || {}, { formatter } = _a, swrOptions = __objRest(_a, ["formatter"]);
154
+ const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_b = options == null ? void 0 : options.use) != null ? _b : [] : [];
155
+ return useSWR(
156
+ `${apiBaseUrl}${query}`,
157
+ (url, init) => fetcher(url, init, { formatter }),
158
+ __spreadProps(__spreadValues({}, swrOptions), {
159
+ use: [signatureMiddleware, ...middleware]
160
+ })
161
+ );
162
+ };
163
+
164
+ // src/useTradingView.ts
165
+ var useTradingView = () => {
166
+ return {};
167
+ };
168
+ var usePrivateObserve = () => {
169
+ const [data, setData] = useState();
170
+ useEffect(() => {
171
+ return () => {
172
+ };
173
+ }, []);
174
+ return {
175
+ data
176
+ };
177
+ };
178
+ var useTopicObserve = (topic) => {
179
+ const [data, setData] = useState();
180
+ useEffect(() => {
181
+ return () => {
182
+ };
183
+ }, []);
184
+ return {
185
+ data
186
+ };
187
+ };
188
+ var useAccount = () => {
189
+ const { configStore } = useContext(OrderlyContext);
190
+ if (!configStore)
191
+ throw new Error("configStore is not defined, please use OrderlyProvider");
192
+ const account3 = useConstant(() => {
193
+ let account4 = SimpleDI.get("account");
194
+ if (!account4) {
195
+ account4 = new Account(configStore);
196
+ SimpleDI.registerByName("account", account4);
197
+ }
198
+ return account4;
199
+ });
200
+ const { data: accountInfo } = usePrivateQuery("/client/info");
201
+ const state = useObservable(
202
+ () => account3.state$,
203
+ account3.stateValue
204
+ );
205
+ const login = useCallback(
206
+ (address) => {
207
+ account3.login(address);
208
+ },
209
+ [account3]
210
+ );
211
+ return {
212
+ account: state,
213
+ info: accountInfo,
214
+ login
215
+ };
216
+ };
217
+ var WS_NAME = "websocketClient";
218
+ var useWebSocketClient = () => {
219
+ const ws = useConstant(() => {
220
+ let websocketClient = SimpleDI.get(WS_NAME);
221
+ if (!websocketClient) {
222
+ websocketClient = new WebSocketClient({
223
+ accountId: "0x47ab075adca7dfe9dd206eb7c50a10f7b99f4f08fa6c3abd4c170d438e15093b",
224
+ networkId: "testnet",
225
+ onSigntureRequest: (accountId) => __async(void 0, null, function* () {
226
+ const signer = getMockSigner();
227
+ const timestamp = (/* @__PURE__ */ new Date()).getTime();
228
+ const result = yield signer.signText(timestamp.toString());
229
+ return __spreadProps(__spreadValues({}, result), { timestamp });
230
+ })
231
+ });
232
+ SimpleDI.registerByName(WS_NAME, websocketClient);
233
+ }
234
+ return websocketClient;
235
+ });
236
+ return ws;
237
+ };
238
+ var useTickerStream = (symbol) => {
239
+ if (!symbol) {
240
+ throw new Error("useFuturesForSymbol requires a symbol");
241
+ }
242
+ const { data: info } = useQuery(`/public/futures/${symbol}`);
243
+ const ws = useWebSocketClient();
244
+ const ticker = useObservable(
245
+ (_, input$) => input$.pipe(
246
+ map(([config]) => config),
247
+ combineLatestWith(ws.observe(`${symbol}@ticker`).pipe(startWith({}))),
248
+ map(([config, ticker2]) => {
249
+ if (!config)
250
+ return config;
251
+ if (ticker2.close !== void 0) {
252
+ config["24h_close"] = ticker2.close;
253
+ }
254
+ if (ticker2.open !== void 0) {
255
+ config["24h_open"] = ticker2.open;
256
+ }
257
+ if (ticker2.volume !== void 0) {
258
+ config["24h_volumn"] = ticker2.volume;
259
+ }
260
+ if (ticker2.close !== void 0 && ticker2.open !== void 0) {
261
+ config["change"] = new Decimal(ticker2.close).minus(ticker2.open).div(ticker2.open).toNumber();
262
+ }
263
+ return config;
264
+ })
265
+ ),
266
+ null,
267
+ [info]
268
+ );
269
+ return ticker;
270
+ };
271
+ compose(defaultTo(0), head, last, pathOr([], ["asks"]));
272
+ pathOr(0, ["bids", 0, 0]);
273
+ var paddingFn = (len) => Array(len).fill([Number.NaN, Number.NaN, Number.NaN]);
274
+ var asksSortFn = (a, b) => a[0] - b[0];
275
+ var bidsSortFn = (a, b) => b[0] - a[0];
276
+ var reduceItems = (depth, level, data) => {
277
+ if (!Array.isArray(data) || data.length === 0) {
278
+ return [];
279
+ }
280
+ const result = [];
281
+ for (let i = 0; i < data.length; i++) {
282
+ const [price, quantity] = data[i];
283
+ result.push([price, quantity, quantity + (i > 0 ? result[i - 1][2] : 0)]);
284
+ if (i + 1 >= level) {
285
+ break;
286
+ }
287
+ }
288
+ return result;
289
+ };
290
+ var reduceOrderbook = (depth, level, data) => {
291
+ const asks = reduceItems(depth, level, data.asks).reverse();
292
+ const bids = reduceItems(depth, level, data.bids);
293
+ return {
294
+ asks: asks.length < level ? paddingFn(level - asks.length).concat(asks) : asks,
295
+ bids: bids.length < level ? bids.concat(paddingFn(level - bids.length)) : bids
296
+ };
297
+ };
298
+ var mergeItems = (data, update) => {
299
+ if (data.length === 0)
300
+ return update;
301
+ while (update.length > 0) {
302
+ const item = update.shift();
303
+ if (item) {
304
+ const [price, quantity] = item;
305
+ if (price < data[0][0] && quantity > 0) {
306
+ data.unshift(item);
307
+ continue;
308
+ }
309
+ const index = data.findIndex(([p], index2) => p === price);
310
+ if (index === -1) {
311
+ data.push(item);
312
+ } else {
313
+ if (quantity === 0) {
314
+ data.splice(index, 1);
315
+ continue;
316
+ }
317
+ data[index] = item;
318
+ }
319
+ }
320
+ }
321
+ return data;
322
+ };
323
+ var mergeOrderbook = (data, update) => {
324
+ return {
325
+ asks: mergeItems(data.asks, update.asks).sort(asksSortFn),
326
+ bids: mergeItems(data.bids, update.bids).sort(bidsSortFn)
327
+ };
328
+ };
329
+ var useOrderbook = (symbol, initial = { asks: [], bids: [] }, options) => {
330
+ if (!symbol) {
331
+ throw new Error("useOrderbook requires a symbol");
332
+ }
333
+ const [data, setData] = useState(initial);
334
+ const [depth, setDepth] = useState(1e-3);
335
+ const [level, setLevel] = useState(() => {
336
+ var _a;
337
+ return (_a = options == null ? void 0 : options.level) != null ? _a : 10;
338
+ });
339
+ const ws = useWebSocketClient();
340
+ const orderbookSubscriberRef = useRef();
341
+ const ticker = useTickerStream(symbol);
342
+ const orderbookRequest$ = useMemo(() => {
343
+ return ws.observe(
344
+ {
345
+ event: "request",
346
+ params: {
347
+ type: "orderbook",
348
+ symbol
349
+ }
350
+ },
351
+ void 0,
352
+ (message) => message.event === "request"
353
+ );
354
+ }, [symbol]);
355
+ const orderbookUpdate$ = useMemo(() => {
356
+ return ws.observe(`${symbol}@orderbookupdate`, () => ({
357
+ event: "subscribe",
358
+ topic: `${symbol}@orderbookupdate`
359
+ })).pipe(
360
+ startWith({ asks: [], bids: [] })
361
+ // filter((message: any) => !!message.success)
362
+ );
363
+ }, [symbol]);
364
+ const orderbookOptions$ = useConstant(() => {
365
+ return new BehaviorSubject({
366
+ depth: 1e-3,
367
+ level: 10
368
+ });
369
+ });
370
+ const markPrice = useObservable(
371
+ (_, input$) => input$.pipe(
372
+ debounceTime(200),
373
+ switchMap(([symbol2]) => {
374
+ return ws.observe(`${symbol2}@markprice`).pipe(map((data2) => data2.price));
375
+ })
376
+ ),
377
+ 0,
378
+ [symbol]
379
+ );
380
+ useEffect(() => {
381
+ if (orderbookSubscriberRef.current) {
382
+ orderbookSubscriberRef.current.unsubscribe();
383
+ }
384
+ orderbookSubscriberRef.current = merge(orderbookRequest$, orderbookUpdate$).pipe(
385
+ // tap((data) => console.log(data)),
386
+ map(
387
+ (data2) => pick(["asks", "bids"], data2)
388
+ ),
389
+ scan((acc, curr) => {
390
+ if (!acc.asks && !acc.bids) {
391
+ return curr;
392
+ }
393
+ return mergeOrderbook(acc, curr);
394
+ }),
395
+ map((data2) => reduceOrderbook(depth, level, data2))
396
+ ).subscribe((data2) => {
397
+ setData(data2);
398
+ });
399
+ }, [orderbookRequest$, orderbookUpdate$]);
400
+ const onDepthChange = useCallback((depth2) => {
401
+ console.log("Orderbook depth has changed:", depth2);
402
+ orderbookOptions$.next(__spreadProps(__spreadValues({}, orderbookOptions$.value), {
403
+ depth: depth2
404
+ // level,
405
+ }));
406
+ }, []);
407
+ const middlePrice = useMemo(() => {
408
+ let asksFrist = 0, bidsFirst = 0;
409
+ if (data.asks.length > 0) {
410
+ asksFrist = data.asks[data.bids.length - 1][0];
411
+ }
412
+ if (data.bids.length > 0) {
413
+ bidsFirst = data.bids[0][0];
414
+ }
415
+ if (isNaN(asksFrist) || isNaN(bidsFirst) || !ticker)
416
+ return 0;
417
+ return [asksFrist, bidsFirst, ticker["24h_close"]].sort()[1];
418
+ }, [ticker, data]);
419
+ return [
420
+ __spreadProps(__spreadValues({}, data), { markPrice, middlePrice }),
421
+ { onDepthChange, depth }
422
+ ];
423
+ };
424
+
425
+ // src/utils/createGetter.ts
426
+ function createGetter(data, depth = 2) {
427
+ return new Proxy(data || {}, {
428
+ get(target, property, receiver) {
429
+ if (depth === 1) {
430
+ return (defaultValue) => {
431
+ var _a;
432
+ if (!target)
433
+ return defaultValue;
434
+ return (_a = target[property]) != null ? _a : defaultValue;
435
+ };
436
+ }
437
+ return (key, defaultValue) => {
438
+ var _a, _b;
439
+ if (key) {
440
+ return (_b = (_a = target[property]) == null ? void 0 : _a[key]) != null ? _b : defaultValue;
441
+ } else {
442
+ return target[property];
443
+ }
444
+ };
445
+ }
446
+ });
447
+ }
448
+
449
+ // src/orderly/useSymbolsInfo.ts
450
+ var useSymbolsInfo = () => {
451
+ const { data = {} } = useQuery(`/public/info`, {
452
+ focusThrottleInterval: 1e3 * 60 * 60 * 24,
453
+ revalidateOnFocus: false,
454
+ formatter(data2) {
455
+ var _a;
456
+ if (!(data2 == null ? void 0 : data2.rows) || !((_a = data2 == null ? void 0 : data2.rows) == null ? void 0 : _a.length)) {
457
+ return {};
458
+ }
459
+ const obj = /* @__PURE__ */ Object.create(null);
460
+ for (let index = 0; index < data2.rows.length; index++) {
461
+ const item = data2.rows[index];
462
+ const arr = item.symbol.split("_");
463
+ obj[item.symbol] = __spreadProps(__spreadValues({}, item), {
464
+ base: arr[1],
465
+ quote: arr[2],
466
+ type: arr[0],
467
+ name: `${arr[1]}-${arr[0]}`
468
+ });
469
+ }
470
+ return obj;
471
+ }
472
+ });
473
+ return createGetter(data);
474
+ };
475
+
476
+ // src/orderly/useTokenInfo.ts
477
+ var useTokenInfo = () => {
478
+ const { data = {} } = useQuery(
479
+ "/public/token",
480
+ {
481
+ focusThrottleInterval: 1e3 * 60 * 60 * 24,
482
+ revalidateOnFocus: false,
483
+ formatter(data2) {
484
+ var _a;
485
+ if (!(data2 == null ? void 0 : data2.rows) || !((_a = data2 == null ? void 0 : data2.rows) == null ? void 0 : _a.length)) {
486
+ return {};
487
+ }
488
+ const obj = /* @__PURE__ */ Object.create(null);
489
+ for (let index = 0; index < data2.rows.length; index++) {
490
+ const item = data2.rows[index];
491
+ obj[item.token] = item;
492
+ }
493
+ return obj;
494
+ }
495
+ }
496
+ );
497
+ return createGetter(data);
498
+ };
499
+ var needNumberOnlyFields = ["order_quantity", "order_price", "total"];
500
+ function baseInputHandle(inputs) {
501
+ let [values, input, value, markPrice, config] = inputs;
502
+ if (needNumberOnlyFields.includes(input)) {
503
+ value = value.toString();
504
+ value = value.replace(/,/g, "");
505
+ value = value.replace(/[^\d.]/g, "");
506
+ }
507
+ return [
508
+ __spreadProps(__spreadValues({}, values), {
509
+ [input]: value
510
+ }),
511
+ input,
512
+ value,
513
+ markPrice,
514
+ config
515
+ ];
516
+ }
517
+ function orderEntityFormatHandle(baseTick, quoteTick) {
518
+ return function(inputs) {
519
+ const [values, input, value, markPrice, config] = inputs;
520
+ return [values, input, value, markPrice, config];
521
+ };
522
+ }
523
+ function priceInputHandle(inputs) {
524
+ const [values, input, value, markPrice, config] = inputs;
525
+ if (value === "") {
526
+ return [__spreadProps(__spreadValues({}, values), { total: "" }), input, value, markPrice, config];
527
+ }
528
+ const price = new Decimal(value);
529
+ const priceDP = price.dp();
530
+ if (priceDP > config.quoteDP) {
531
+ price.toDecimalPlaces(config.quoteDP);
532
+ values.order_price = price.toNumber();
533
+ }
534
+ price.toDecimalPlaces(Math.min(priceDP, config.quoteDP));
535
+ if (!values.order_quantity) {
536
+ return [values, input, value, markPrice, config];
537
+ }
538
+ const total = price.mul(values.order_quantity);
539
+ const quantityDP = total.dp();
540
+ total.toDecimalPlaces(Math.min(quantityDP, config.baseDP));
541
+ return [
542
+ __spreadProps(__spreadValues({}, values), { total: total.toNumber() }),
543
+ input,
544
+ value,
545
+ markPrice,
546
+ config
547
+ ];
548
+ }
549
+ function quantityInputHandle(inputs) {
550
+ const [values, input, value, markPrice, config] = inputs;
551
+ if (value === "") {
552
+ return [__spreadProps(__spreadValues({}, values), { total: "" }), input, value, markPrice, config];
553
+ }
554
+ let quantity = new Decimal(value);
555
+ const quantityDP = quantity.dp();
556
+ if (quantityDP > config.baseDP) {
557
+ quantity = quantity.toDecimalPlaces(config.baseDP);
558
+ values.order_quantity = quantity.toNumber();
559
+ }
560
+ let price = markPrice;
561
+ if (values.order_type === OrderType.LIMIT && !!values.order_price) {
562
+ price = Number(values.order_price);
563
+ }
564
+ const total = quantity.mul(price);
565
+ const totalDP = total.dp();
566
+ total.todp(Math.min(config.quoteDP, totalDP));
567
+ return [
568
+ __spreadProps(__spreadValues({}, values), {
569
+ total: total.toNumber()
570
+ }),
571
+ input,
572
+ value,
573
+ markPrice,
574
+ config
575
+ ];
576
+ }
577
+ function totalInputHandle(inputs) {
578
+ const [values, input, value, markPrice, config] = inputs;
579
+ if (value === "") {
580
+ return [__spreadProps(__spreadValues({}, values), { order_quantity: "" }), input, value, markPrice, config];
581
+ }
582
+ let price = markPrice;
583
+ if (values.order_type === OrderType.LIMIT && !!values.order_price) {
584
+ price = Number(values.order_price);
585
+ }
586
+ let total = new Decimal(value);
587
+ const totalDP = total.dp();
588
+ if (totalDP > config.quoteDP) {
589
+ total = total.toDecimalPlaces(config.quoteDP);
590
+ values.total = total.toNumber();
591
+ }
592
+ const quantity = total.div(price);
593
+ return [
594
+ __spreadProps(__spreadValues({}, values), {
595
+ order_quantity: quantity.toDecimalPlaces(Math.min(config.baseDP, quantity.dp())).toNumber()
596
+ }),
597
+ input,
598
+ value,
599
+ markPrice,
600
+ config
601
+ ];
602
+ }
603
+ function otherInputHandle(inputs) {
604
+ return inputs;
605
+ }
606
+ var getCalculateHandler = (fieldName) => {
607
+ switch (fieldName) {
608
+ case "order_quantity": {
609
+ return quantityInputHandle;
610
+ }
611
+ case "order_price": {
612
+ return priceInputHandle;
613
+ }
614
+ case "total": {
615
+ return totalInputHandle;
616
+ }
617
+ default:
618
+ return otherInputHandle;
619
+ }
620
+ };
621
+
622
+ // src/orderly/useFundingRates.ts
623
+ var useFundingRates = () => {
624
+ const { data } = useQuery(
625
+ `/public/funding_rates`,
626
+ {
627
+ focusThrottleInterval: 1e3 * 60 * 60 * 24,
628
+ revalidateOnFocus: false,
629
+ formatter(data2) {
630
+ var _a;
631
+ if (!(data2 == null ? void 0 : data2.rows) || !((_a = data2 == null ? void 0 : data2.rows) == null ? void 0 : _a.length)) {
632
+ return {};
633
+ }
634
+ const obj = /* @__PURE__ */ Object.create(null);
635
+ for (let index = 0; index < data2.rows.length; index++) {
636
+ const item = data2.rows[index];
637
+ obj[item.symbol] = item;
638
+ }
639
+ return obj;
640
+ }
641
+ }
642
+ );
643
+ return createGetter(data);
644
+ };
645
+ var useMarkPricesSubject = () => {
646
+ const ws = useWebSocketClient();
647
+ return useConstant(
648
+ () => ws.observe("markprices").pipe(
649
+ map((data) => {
650
+ const prices = {};
651
+ data.forEach((item) => {
652
+ prices[item.symbol] = item.price;
653
+ });
654
+ return prices;
655
+ })
656
+ )
657
+ );
658
+ };
659
+
660
+ // src/orderly/usePositionStream.ts
661
+ var usePositionStream = (symbol, options) => {
662
+ const [visibledSymbol, setVisibleSymbol] = useState(
663
+ symbol
664
+ );
665
+ const symbolInfo = useSymbolsInfo();
666
+ const { info: accountInfo } = useAccount();
667
+ const fundingRates = useFundingRates();
668
+ const markPrices$ = useMarkPricesSubject();
669
+ const { data, error, isLoading } = usePrivateQuery(
670
+ `/positions`,
671
+ __spreadProps(__spreadValues({}, options), {
672
+ formatter: (data2) => data2
673
+ })
674
+ );
675
+ const value = useObservable(
676
+ (_, input$) => input$.pipe(
677
+ // map((data) => {
678
+ // return data[0];
679
+ // }),
680
+ combineLatestWith(markPrices$),
681
+ debounceTime(100),
682
+ map(([[data2, symbolInfo2, accountInfo2], markPrices]) => {
683
+ let totalCollateral = 0;
684
+ return data2 == null ? void 0 : data2.map((item) => {
685
+ var _a;
686
+ const price = (_a = markPrices[item.symbol]) != null ? _a : item.mark_price;
687
+ const info = symbolInfo2 == null ? void 0 : symbolInfo2[item.symbol];
688
+ const MMR = positions.MMR({
689
+ baseMMR: info("base_mmr"),
690
+ baseIMR: info("base_imr"),
691
+ IMRFactor: accountInfo2.imr_factor[info("base")],
692
+ positionNotional: positions.notional(item.position_qty, price),
693
+ IMR_factor_power: 4 / 5
694
+ });
695
+ return __spreadProps(__spreadValues({}, item), {
696
+ mark_price: price,
697
+ est_liq_price: positions.liqPrice({
698
+ markPrice: price,
699
+ totalCollateral,
700
+ positionQty: item.position_qty,
701
+ MMR
702
+ }),
703
+ notional: positions.notional(
704
+ item.position_qty,
705
+ item.average_open_price
706
+ ),
707
+ unrealized_pnl: positions.unrealizedPnL({
708
+ qty: item.position_qty,
709
+ openPrice: item.average_open_price,
710
+ markPrice: price
711
+ })
712
+ });
713
+ });
714
+ })
715
+ ),
716
+ void 0,
717
+ [data == null ? void 0 : data.rows, symbolInfo, accountInfo]
718
+ );
719
+ const aggregatedData = useMemo(() => {
720
+ const aggregatedData2 = {
721
+ unsettledPnL: NaN,
722
+ unrealPnL: NaN,
723
+ notional: NaN
724
+ };
725
+ if (value && value.length) {
726
+ aggregatedData2.unrealPnL = positions.totalUnrealizedPnL(value);
727
+ aggregatedData2.notional = positions.totalNotional(value);
728
+ aggregatedData2.unsettledPnL = positions.totalUnsettlementPnL(
729
+ value.map((item) => {
730
+ var _a;
731
+ return __spreadProps(__spreadValues({}, item), {
732
+ sum_unitary_funding: (_a = fundingRates[item.symbol]) == null ? void 0 : _a.call(
733
+ fundingRates,
734
+ "sum_unitary_funding",
735
+ 0
736
+ )
737
+ });
738
+ })
739
+ );
740
+ }
741
+ return aggregatedData2;
742
+ }, [value, fundingRates]);
743
+ const showSymbol = useCallback((symbol2) => {
744
+ setVisibleSymbol(symbol2);
745
+ }, []);
746
+ return [
747
+ { rows: value, aggregated: aggregatedData },
748
+ createGetter(data, 1),
749
+ {
750
+ close: (qty) => {
751
+ },
752
+ loading: false,
753
+ showSymbol,
754
+ error,
755
+ loadMore: () => {
756
+ },
757
+ refresh: () => {
758
+ }
759
+ // toggleHideOthers,
760
+ // filter: (filter: string) => {},
761
+ }
762
+ ];
763
+ };
764
+ var fetcher3 = (url, init) => get(url, init);
765
+ var usePrivateInfiniteQuery = (getKey, options) => {
766
+ var _a;
767
+ const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_a = options == null ? void 0 : options.use) != null ? _a : [] : [];
768
+ const { apiBaseUrl } = useContext(OrderlyContext);
769
+ const result = useSWRInfinite(
770
+ (index, prevData) => `${apiBaseUrl}${getKey(index, prevData)}`,
771
+ fetcher3,
772
+ __spreadProps(__spreadValues({}, options), {
773
+ use: [signatureMiddleware, ...middleware]
774
+ })
775
+ );
776
+ return result;
777
+ };
778
+ var OrderStatus = /* @__PURE__ */ ((OrderStatus2) => {
779
+ OrderStatus2["FILLED"] = "FILLED";
780
+ OrderStatus2["PARTIAL_FILLED"] = "PARTIAL_FILLED";
781
+ OrderStatus2["CANCELED"] = "CANCELED";
782
+ OrderStatus2["NEW"] = "NEW";
783
+ OrderStatus2["COMPLETED"] = "COMPLETED";
784
+ return OrderStatus2;
785
+ })(OrderStatus || {});
786
+ var useOrderStream = ({
787
+ status = "NEW" /* NEW */,
788
+ symbol
789
+ } = {}) => {
790
+ var _a;
791
+ const markPrices$ = useMarkPricesSubject();
792
+ const res = usePrivateInfiniteQuery(
793
+ (pageIndex, previousPageData) => {
794
+ const search = new URLSearchParams([
795
+ ["size", "100"],
796
+ ["page", `${pageIndex + 1}`],
797
+ [`status`, status]
798
+ ]);
799
+ if (symbol) {
800
+ search.set(`symbol`, symbol);
801
+ }
802
+ return `/orders?${search.toString()}`;
803
+ },
804
+ {
805
+ initialSize: 1,
806
+ onError: (err) => {
807
+ console.error("fetch failed::::", err);
808
+ }
809
+ }
810
+ );
811
+ const orders = useObservable(
812
+ (_, input$) => input$.pipe(
813
+ map(([data]) => {
814
+ return data.flat();
815
+ }),
816
+ combineLatestWith(markPrices$),
817
+ map(([data, markPrices]) => {
818
+ return data.map((item) => {
819
+ var _a2;
820
+ return __spreadProps(__spreadValues({}, item), {
821
+ mark_price: (_a2 = markPrices[item.symbol]) != null ? _a2 : 0
822
+ });
823
+ });
824
+ })
825
+ ),
826
+ null,
827
+ [(_a = res.data) != null ? _a : []]
828
+ );
829
+ const cancelAllOrders = useCallback(() => {
830
+ }, [res.data]);
831
+ const updateOrder = useCallback((id, data) => {
832
+ }, []);
833
+ const cancelOrder = useCallback((id) => {
834
+ }, []);
835
+ return [
836
+ orders,
837
+ // {
838
+ // ...res,
839
+ // data: res.data?.reduce((acc, cur) => {
840
+ // return [...acc, ...cur];
841
+ // }, []),
842
+ // },
843
+ {
844
+ cancelAllOrders,
845
+ updateOrder,
846
+ cancelOrder
847
+ }
848
+ ];
849
+ };
850
+ var useMarkPriceStream = () => {
851
+ const markPrice$ = useMarkPricesSubject();
852
+ return useObservable(() => markPrice$, {});
853
+ };
854
+
855
+ // src/orderly/useCollateral.ts
856
+ var totalUnsettlementPnLPath = pathOr(0, [0, "aggregated", "unsettledPnL"]);
857
+ var positionsPath = pathOr([], [0, "rows"]);
858
+ var useCollateral = (dp = 6) => {
859
+ const positions2 = usePositionStream();
860
+ const orders = useOrderStream();
861
+ const { info: accountInfo } = useAccount();
862
+ const symbolInfo = useSymbolsInfo();
863
+ const markPrices = useMarkPriceStream();
864
+ const { data } = usePrivateQuery("/client/holding", {
865
+ formatter: (data2) => {
866
+ return data2.holding;
867
+ }
868
+ });
869
+ const totalCollateral = useObservable(
870
+ (_, input$) => merge(input$).pipe(
871
+ debounceTime(100),
872
+ filter((data2) => !!data2[0]),
873
+ map(
874
+ ([data2, unsettlemnedPnL, markPrices2]) => {
875
+ const nonUSDC = [];
876
+ let USDC_holding = 0;
877
+ data2.forEach((item) => {
878
+ if (item.token === "USDC") {
879
+ USDC_holding = item.holding;
880
+ } else {
881
+ nonUSDC.push({
882
+ holding: item.holding,
883
+ // markPrice: markPrices[item.token] ?? 0,
884
+ markPrice: 0,
885
+ discount: 0
886
+ });
887
+ }
888
+ });
889
+ const number = account.totalCollateral({
890
+ USDCHolding: USDC_holding,
891
+ nonUSDCHolding: nonUSDC,
892
+ unsettlementPnL: unsettlemnedPnL
893
+ });
894
+ return new Decimal(number);
895
+ }
896
+ )
897
+ ),
898
+ zero,
899
+ [data, totalUnsettlementPnLPath(positions2), markPrices]
900
+ );
901
+ const totalInitialMarginWithOrders = useObservable(
902
+ (_, input$) => input$.pipe(
903
+ filter((data2) => !!data2[3] && !!data2[4]),
904
+ map(([positions3, orders2, markPrices2, accountInfo2, symbolInfo2]) => {
905
+ var _a;
906
+ return account.totalInitialMarginWithOrders({
907
+ positions: positionsPath(positions3),
908
+ orders: (_a = orders2 == null ? void 0 : orders2[0]) != null ? _a : [],
909
+ markPrices: markPrices2,
910
+ IMR_Factors: accountInfo2.imr_factor,
911
+ maxLeverage: accountInfo2.max_leverage,
912
+ symbolInfo: symbolInfo2
913
+ });
914
+ })
915
+ ),
916
+ 0,
917
+ [positions2, orders, markPrices, accountInfo, symbolInfo]
918
+ );
919
+ return {
920
+ totalCollateral: totalCollateral.toDecimalPlaces(dp).toNumber(),
921
+ freeCollateral: account.freeCollateral({
922
+ totalCollateral,
923
+ totalInitialMarginWithOrders
924
+ }).toDecimalPlaces(dp).toNumber(),
925
+ totalValue: 0
926
+ };
927
+ };
928
+ var positionsPath2 = pathOr([], [0, "rows"]);
929
+ var useMaxQty = (symbol, side, reduceOnly = false) => {
930
+ var _a;
931
+ const positions2 = usePositionStream();
932
+ const orders = useOrderStream();
933
+ const { info: accountInfo } = useAccount();
934
+ const symbolInfo = useSymbolsInfo();
935
+ const { totalCollateral } = useCollateral();
936
+ const markPrices = useMarkPriceStream();
937
+ const maxQty = useObservable(
938
+ (_, input$) => input$.pipe(
939
+ switchMap(
940
+ ([{ reduceOnly: reduceOnly2 }]) => iif(
941
+ () => reduceOnly2,
942
+ input$.pipe(
943
+ filter(([{ positions: positions3 }]) => positions3.length > 0),
944
+ map(
945
+ ([
946
+ {
947
+ positions: positions3,
948
+ symbol: symbol2,
949
+ side: side2
950
+ }
951
+ ]) => {
952
+ const positionQty = account.getQtyFromPositions(
953
+ positions3,
954
+ symbol2
955
+ );
956
+ if (positionQty > 0) {
957
+ if (side2 === OrderSide.BUY) {
958
+ return 0;
959
+ } else {
960
+ return Math.abs(positionQty);
961
+ }
962
+ }
963
+ if (positionQty < 0) {
964
+ if (side2 === OrderSide.BUY) {
965
+ return Math.abs(positionQty);
966
+ } else {
967
+ return 0;
968
+ }
969
+ }
970
+ return 0;
971
+ }
972
+ )
973
+ ),
974
+ input$.pipe(
975
+ filter(
976
+ ([
977
+ {
978
+ markPrices: markPrices2,
979
+ positions: positions3,
980
+ orders: orders2,
981
+ accountInfo: accountInfo2,
982
+ symbolInfo: symbolInfo2,
983
+ symbol: symbol2,
984
+ side: side2,
985
+ totalCollateral: totalCollateral2
986
+ }
987
+ ]) => !!symbol2 && !!side2 && !!markPrices2[symbol2] && !!positions3 && !!orders2 && !!accountInfo2 && !!symbolInfo2 && !!totalCollateral2
988
+ ),
989
+ // 数据准备
990
+ map(
991
+ ([
992
+ {
993
+ markPrices: markPrices2,
994
+ positions: positions3,
995
+ orders: orders2,
996
+ accountInfo: accountInfo2,
997
+ symbolInfo: symbolInfo2,
998
+ symbol: symbol2,
999
+ side: side2,
1000
+ totalCollateral: totalCollateral2
1001
+ }
1002
+ ]) => {
1003
+ const getSymbolInfo = symbolInfo2[symbol2];
1004
+ const positionQty = account.getQtyFromPositions(
1005
+ positions3,
1006
+ symbol2
1007
+ );
1008
+ const buyOrdersQty = account.getQtyFromOrdersBySide(
1009
+ orders2,
1010
+ symbol2,
1011
+ OrderSide.BUY
1012
+ );
1013
+ const sellOrdersQty = account.getQtyFromOrdersBySide(
1014
+ orders2,
1015
+ symbol2,
1016
+ OrderSide.SELL
1017
+ );
1018
+ const otherPositions = positions3.filter(
1019
+ (item) => item.symbol !== symbol2
1020
+ );
1021
+ const otherOrders = orders2.filter(
1022
+ (item) => item.symbol !== symbol2
1023
+ );
1024
+ const otherIMs = account.otherIMs({
1025
+ orders: otherOrders,
1026
+ positions: otherPositions,
1027
+ symbolInfo: symbolInfo2,
1028
+ markPrices: markPrices2,
1029
+ IMR_Factors: accountInfo2.imr_factor,
1030
+ maxLeverage: accountInfo2.max_leverage
1031
+ });
1032
+ return [
1033
+ side2,
1034
+ {
1035
+ markPrice: markPrices2[symbol2],
1036
+ baseMaxQty: getSymbolInfo("base_max"),
1037
+ totalCollateral: totalCollateral2,
1038
+ maxLeverage: accountInfo2.max_leverage,
1039
+ takerFeeRate: accountInfo2.taker_fee_rate,
1040
+ baseIMR: getSymbolInfo("base_imr"),
1041
+ otherIMs,
1042
+ positionQty,
1043
+ buyOrdersQty,
1044
+ sellOrdersQty,
1045
+ IMR_Factor: accountInfo2.imr_factor[getSymbolInfo("base")]
1046
+ },
1047
+ {
1048
+ dp: getSymbolInfo("base_tick")
1049
+ }
1050
+ ];
1051
+ }
1052
+ ),
1053
+ map(([side2, inputs, options]) => {
1054
+ const maxQty2 = account.maxQty(side2, inputs);
1055
+ return maxQty2;
1056
+ }),
1057
+ distinct()
1058
+ // tap((data: number) => console.log("************", data))
1059
+ )
1060
+ )
1061
+ )
1062
+ ),
1063
+ 0,
1064
+ [
1065
+ {
1066
+ markPrices,
1067
+ positions: positionsPath2(positions2),
1068
+ orders: (_a = orders[0]) != null ? _a : [],
1069
+ accountInfo,
1070
+ symbolInfo,
1071
+ symbol,
1072
+ side,
1073
+ totalCollateral,
1074
+ reduceOnly
1075
+ }
1076
+ ]
1077
+ );
1078
+ return maxQty;
1079
+ };
1080
+ var { maxPrice, minPrice } = order;
1081
+ var BaseOrderCreator = class {
1082
+ baseOrder(data) {
1083
+ const order2 = {
1084
+ // symbol: data.symbol,
1085
+ order_type: !!data.order_type_ext ? data.order_type_ext : data.order_type,
1086
+ side: data.side,
1087
+ // reduce_only: data.reduce_only,
1088
+ order_quantity: data.order_quantity
1089
+ };
1090
+ if (data.visible_quantity === 0) {
1091
+ order2.visible_quantity = data.visible_quantity;
1092
+ }
1093
+ return order2;
1094
+ }
1095
+ baseValidate(values, configs) {
1096
+ const errors = {};
1097
+ const { maxQty } = configs;
1098
+ const { order_quantity, total } = values;
1099
+ if (!order_quantity) {
1100
+ errors.order_quantity = "quantity is required";
1101
+ } else {
1102
+ const { base_max, base_min } = configs.symbol;
1103
+ const qty = new Decimal(order_quantity);
1104
+ if (qty.lt(base_min)) {
1105
+ errors.order_quantity = `quantity must be greater than ${base_min}`;
1106
+ } else if (qty.gt(maxQty)) {
1107
+ errors.order_quantity = `quantity must be less than ${base_max}`;
1108
+ }
1109
+ }
1110
+ if (!!total) {
1111
+ const { quote_max, quote_min } = configs.symbol;
1112
+ const totalNumber = new Decimal(total);
1113
+ if (totalNumber.lt(quote_min)) {
1114
+ errors.total = `Quantity should be greater than ${quote_min}`;
1115
+ } else if (totalNumber.gt(quote_max)) {
1116
+ errors.total = `Quantity should be less or equal than ${quote_max}`;
1117
+ }
1118
+ }
1119
+ return Promise.resolve(errors);
1120
+ }
1121
+ };
1122
+ var LimitOrderCreator = class extends BaseOrderCreator {
1123
+ create(values) {
1124
+ return __spreadProps(__spreadValues({}, this.baseOrder(values)), {
1125
+ order_price: values.order_price
1126
+ });
1127
+ }
1128
+ validate(values, config) {
1129
+ return this.baseValidate(values, config).then((errors) => {
1130
+ const { order_price } = values;
1131
+ if (!order_price) {
1132
+ errors.order_price = "price is required";
1133
+ } else {
1134
+ const price = new Decimal(order_price);
1135
+ const { symbol } = config;
1136
+ const { price_range } = symbol;
1137
+ const maxPriceNumber = maxPrice(config.markPrice, price_range);
1138
+ const minPriceNumber = minPrice(config.markPrice, price_range);
1139
+ if (price.lt(minPriceNumber)) {
1140
+ errors.order_price = `price must be greater than ${minPriceNumber}`;
1141
+ } else if (price.gt(maxPriceNumber)) {
1142
+ errors.order_price = `price must be less than ${maxPriceNumber}`;
1143
+ }
1144
+ }
1145
+ return errors;
1146
+ });
1147
+ }
1148
+ };
1149
+ var MarketOrderCreator = class extends BaseOrderCreator {
1150
+ create(values) {
1151
+ return __spreadValues({}, this.baseOrder(values));
1152
+ }
1153
+ validate(values, configs) {
1154
+ return this.baseValidate(values, configs);
1155
+ }
1156
+ };
1157
+ var PostOnlyOrderCreator = class extends LimitOrderCreator {
1158
+ };
1159
+ var FOKOrderCreator = class extends LimitOrderCreator {
1160
+ };
1161
+ var IOCOrderCreator = class extends LimitOrderCreator {
1162
+ };
1163
+ var GeneralOrderCreator = class extends BaseOrderCreator {
1164
+ create(data) {
1165
+ return __spreadProps(__spreadValues({}, this.baseOrder(data)), {
1166
+ order_price: data.order_price,
1167
+ order_quantity: data.order_quantity
1168
+ });
1169
+ }
1170
+ validate(values, configs) {
1171
+ return super.baseValidate(values, configs);
1172
+ }
1173
+ };
1174
+ var OrderFactory = class {
1175
+ static create(type2) {
1176
+ switch (type2) {
1177
+ case OrderType.LIMIT:
1178
+ return new LimitOrderCreator();
1179
+ case OrderType.MARKET:
1180
+ return new MarketOrderCreator();
1181
+ case OrderType.IOC:
1182
+ return new IOCOrderCreator();
1183
+ case OrderType.FOK:
1184
+ return new FOKOrderCreator();
1185
+ case OrderType.POST_ONLY:
1186
+ return new PostOnlyOrderCreator();
1187
+ default:
1188
+ return new GeneralOrderCreator();
1189
+ }
1190
+ }
1191
+ };
1192
+
1193
+ // src/orderly/useOrderEntry.ts
1194
+ var useOrderEntry = (symbol, initialValue = {}, options) => {
1195
+ const { mutation } = useMutation("/order");
1196
+ const { freeCollateral } = useCollateral();
1197
+ const symbolInfo = useSymbolsInfo();
1198
+ const tokenInfo = useTokenInfo();
1199
+ const baseDP = useMemo(
1200
+ () => getPrecisionByNumber(symbolInfo[symbol]("base_tick", 0)),
1201
+ [symbolInfo]
1202
+ );
1203
+ const quoteDP = useMemo(() => {
1204
+ return tokenInfo.USDC("decimals", 0);
1205
+ }, [tokenInfo]);
1206
+ const [valuesUpdate, [orderExtraValues]] = useEventCallback(
1207
+ (event$, state$) => {
1208
+ return event$.pipe(
1209
+ withLatestFrom(state$),
1210
+ map(([event, state]) => {
1211
+ const { field, value } = event;
1212
+ console.log("orderExtraValues", field, value);
1213
+ return [__spreadProps(__spreadValues({}, state[0]), { [field]: value })];
1214
+ })
1215
+ );
1216
+ },
1217
+ [
1218
+ {
1219
+ order_type: OrderType.MARKET,
1220
+ side: OrderSide.BUY,
1221
+ reduce_only: false
1222
+ }
1223
+ ]
1224
+ );
1225
+ const ws = useWebSocketClient();
1226
+ const markPrice = useObservable(
1227
+ (_, input$) => input$.pipe(
1228
+ switchMap(([symbol2]) => {
1229
+ return ws.observe(`${symbol2}@markprice`).pipe(
1230
+ map((data) => data.price)
1231
+ // takeWhile(() => type === OrderType.MARKET)
1232
+ );
1233
+ })
1234
+ ),
1235
+ 0,
1236
+ [symbol]
1237
+ );
1238
+ const formik = useFormik({
1239
+ initialValues: __spreadValues({
1240
+ // order_type: OrderType.MARKET,
1241
+ // side: OrderSide.BUY,
1242
+ order_quantity: "",
1243
+ total: "",
1244
+ order_price: "",
1245
+ visible_quantity: 1
1246
+ }, initialValue),
1247
+ validate: (values) => {
1248
+ const creator = OrderFactory.create(orderExtraValues.order_type);
1249
+ return creator == null ? void 0 : creator.validate(values, {
1250
+ symbol: symbolInfo[symbol](),
1251
+ token: tokenInfo[symbol](),
1252
+ maxQty,
1253
+ markPrice
1254
+ });
1255
+ },
1256
+ onSubmit: (values) => {
1257
+ console.log(values);
1258
+ }
1259
+ });
1260
+ const maxQty = useMaxQty(
1261
+ symbol,
1262
+ orderExtraValues.side,
1263
+ orderExtraValues.reduce_only
1264
+ );
1265
+ const formFieldds = useMemo(() => {
1266
+ return ["order_quantity", "order_price", "total"];
1267
+ }, []);
1268
+ const setValue = (field, value) => {
1269
+ if (formFieldds.indexOf(field) < 0) {
1270
+ valuesUpdate({ field, value });
1271
+ return;
1272
+ }
1273
+ const fieldHandler = getCalculateHandler(field);
1274
+ const newValues = compose(
1275
+ head,
1276
+ orderEntityFormatHandle(),
1277
+ fieldHandler,
1278
+ baseInputHandle
1279
+ )([
1280
+ __spreadValues(__spreadValues({}, formik.values), orderExtraValues),
1281
+ field,
1282
+ value,
1283
+ markPrice,
1284
+ { baseDP, quoteDP }
1285
+ ]);
1286
+ formik.setValues(newValues, true);
1287
+ };
1288
+ const onSubmit = (values) => {
1289
+ values = values || formik.values;
1290
+ if (typeof values.order_type === "undefined" || values.order_type !== OrderType.MARKET && values.order_type !== OrderType.LIMIT) {
1291
+ throw new Error("order_type is error");
1292
+ }
1293
+ return Promise.resolve().then(() => {
1294
+ const orderCreator = OrderFactory.create(
1295
+ !!values.order_type_ext ? values.order_type_ext : values.order_type
1296
+ );
1297
+ if (!orderCreator) {
1298
+ throw new Error("orderCreator is null");
1299
+ }
1300
+ if (!symbol) {
1301
+ throw new Error("symbol is null");
1302
+ }
1303
+ const data = orderCreator.create(values);
1304
+ console.log("orderentry data:::", data);
1305
+ formik.setSubmitting(true);
1306
+ return mutation(__spreadProps(__spreadValues({}, data), {
1307
+ symbol
1308
+ })).finally(() => {
1309
+ formik.setSubmitting(false);
1310
+ });
1311
+ });
1312
+ };
1313
+ useEffect(() => {
1314
+ formik.resetForm();
1315
+ }, [symbol]);
1316
+ return {
1317
+ maxQty,
1318
+ // formState,
1319
+ values: __spreadValues(__spreadValues({}, formik.values), orderExtraValues),
1320
+ errors: formik.errors,
1321
+ freeCollateral,
1322
+ markPrice,
1323
+ setValue,
1324
+ onSubmit,
1325
+ isSubmitting: formik.isSubmitting,
1326
+ resetForm: formik.resetForm,
1327
+ validateForm: formik.validateForm,
1328
+ submitCount: formik.submitCount,
1329
+ symbolConfig: symbolInfo[symbol]()
1330
+ };
1331
+ };
1332
+ var useFetures = () => {
1333
+ const { data, isLoading, error } = useQuery(`/public/futures`);
1334
+ const [sortedData, setSortedData] = useState(data);
1335
+ const ws = useWebSocketClient();
1336
+ useEffect(() => {
1337
+ const sub = ws.observe(`tickers`).subscribe((value) => {
1338
+ console.log("useTickers", value);
1339
+ });
1340
+ return () => {
1341
+ sub.unsubscribe();
1342
+ };
1343
+ }, []);
1344
+ useEffect(() => {
1345
+ if (data) {
1346
+ const sortedData2 = data.sort((a, b) => {
1347
+ return 0;
1348
+ });
1349
+ setSortedData(sortedData2);
1350
+ }
1351
+ }, [data]);
1352
+ const sortBy = useCallback((key) => {
1353
+ }, [data]);
1354
+ const filterBy = useCallback((key) => {
1355
+ }, [data]);
1356
+ return {
1357
+ // ...data,
1358
+ data: sortedData,
1359
+ sortBy,
1360
+ filterBy,
1361
+ isLoading,
1362
+ error
1363
+ };
1364
+ };
1365
+ var useMarketsStream = () => {
1366
+ const ws = useWebSocketClient();
1367
+ const { data } = useQuery(`/public/futures`);
1368
+ const value = useObservable(
1369
+ (_, input$) => ws.observe("tickers").pipe(
1370
+ startWith([]),
1371
+ withLatestFrom(input$.pipe(map((args) => args[0]))),
1372
+ map((args) => {
1373
+ if (args[0].length === 0) {
1374
+ return args[1];
1375
+ }
1376
+ return args[1].map((item) => {
1377
+ const ticker = args[0].find(
1378
+ (t) => t.symbol === item.symbol
1379
+ );
1380
+ if (ticker) {
1381
+ return __spreadProps(__spreadValues({}, item), {
1382
+ ["24h_close"]: ticker.close,
1383
+ ["24h_open"]: ticker.open,
1384
+ ["24h_volumn"]: ticker.volume,
1385
+ change: 0
1386
+ });
1387
+ }
1388
+ return item;
1389
+ });
1390
+ })
1391
+ ),
1392
+ null,
1393
+ [data]
1394
+ );
1395
+ return { data: value };
1396
+ };
1397
+ var useFundingRate = (symbol) => {
1398
+ if (!symbol) {
1399
+ throw new Error("useFuturesForSymbol requires a symbol");
1400
+ }
1401
+ const [countDown, setCountDown] = useState("00:00:00");
1402
+ const { data } = useQuery(`/public/funding_rate/${symbol}`, {
1403
+ fallbackData: {
1404
+ est_funding_rate: 0,
1405
+ next_funing_time: 0
1406
+ }
1407
+ });
1408
+ useEffect(() => {
1409
+ if (!data)
1410
+ return;
1411
+ const { next_funding_time } = data;
1412
+ if (!next_funding_time || next_funding_time <= 0) {
1413
+ return;
1414
+ }
1415
+ const timer = setInterval(() => {
1416
+ const diff = new Date(next_funding_time).getTime() - Date.now();
1417
+ const result = timeConvertString(diff);
1418
+ if (result.length === 3) {
1419
+ setCountDown(
1420
+ `${result[0].toString().padStart(2, "0")}:${result[1].toString().padStart(2, "0")}:${result[2].toString().padStart(2, "0")}`
1421
+ );
1422
+ }
1423
+ }, 1e3);
1424
+ return () => {
1425
+ clearInterval(timer);
1426
+ };
1427
+ }, [data]);
1428
+ return __spreadProps(__spreadValues({}, data), {
1429
+ countDown
1430
+ });
1431
+ };
1432
+
1433
+ // src/apis/index.ts
1434
+ var apis_exports = {};
1435
+ __export(apis_exports, {
1436
+ useFundingRate: () => useFundingRate2,
1437
+ useFundingRateBySymbol: () => useFundingRateBySymbol,
1438
+ useInfo: () => useInfo,
1439
+ useToken: () => useToken
1440
+ });
1441
+
1442
+ // src/apis/useInfo.ts
1443
+ var useInfo = () => {
1444
+ return useQuery("/public/info", {
1445
+ // refreshInterval: 1000 * 60 * 60 * 24,
1446
+ });
1447
+ };
1448
+
1449
+ // src/apis/useToken.ts
1450
+ var useToken = () => {
1451
+ return useQuery("/public/token");
1452
+ };
1453
+
1454
+ // src/apis/useFundingRateBySymbol.ts
1455
+ var useFundingRateBySymbol = (symbol) => {
1456
+ if (!symbol) {
1457
+ throw new Error("symbol is required");
1458
+ }
1459
+ return useQuery(`/public/funding_rate/${symbol}`);
1460
+ };
1461
+
1462
+ // src/apis/useFundingRate.ts
1463
+ var useFundingRate2 = (symbol) => {
1464
+ return useQuery(`/public/funding_rate`);
1465
+ };
1466
+
1467
+ export { OrderStatus, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useCollateral, useFetures, useFundingRate, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbook, usePositionStream, usePrivateObserve, usePrivateQuery, useQuery, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradingView, useWebSocketClient };
1468
+ //# sourceMappingURL=out.js.map
1469
+ //# sourceMappingURL=index.mjs.map