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