-
Notifications
You must be signed in to change notification settings - Fork 84
/
markets.js
2150 lines (1984 loc) · 71.8 KB
/
markets.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Doc, { WalletIcons } from './doc'
import State from './state'
import BasePage from './basepage'
import OrderBook from './orderbook'
import { DepthChart } from './charts'
import { postJSON } from './http'
import { NewWalletForm, bindOpenWallet, bind as bindForm } from './forms'
import * as Order from './orderutil'
import ws from './ws'
let app
const bind = Doc.bind
const bookRoute = 'book'
const bookOrderRoute = 'book_order'
const unbookOrderRoute = 'unbook_order'
const updateRemainingRoute = 'update_remaining'
const epochOrderRoute = 'epoch_order'
const bookUpdateRoute = 'bookupdate'
const unmarketRoute = 'unmarket'
const lastMarketKey = 'selectedMarket'
const chartRatioKey = 'chartRatio'
const depthZoomKey = 'depthZoom'
const animationLength = 500
const anHour = 60 * 60 * 1000 // milliseconds
const check = document.createElement('span')
check.classList.add('ico-check')
export default class MarketsPage extends BasePage {
constructor (application, main, data) {
super()
app = application
const page = this.page = Doc.parsePage(main, [
// Templates, loaders, chart div...
'marketLoader', 'marketList', 'rowTemplate', 'buyRows', 'sellRows',
'marketSearch', 'rightSide',
// Registration status
'registrationStatus', 'regStatusTitle', 'regStatusMessage', 'regStatusConfsDisplay',
'regStatusDex', 'confReq',
// Order form
'orderForm', 'priceBox', 'buyBttn', 'sellBttn', 'limitBttn', 'marketBttn',
'tifBox', 'submitBttn', 'qtyField', 'rateField', 'orderErr',
'baseWalletIcons', 'quoteWalletIcons', 'lotSize', 'rateStep', 'lotField',
'tifNow', 'mktBuyBox', 'mktBuyLots', 'mktBuyField', 'minMktBuy', 'qtyBox',
'loaderMsg', 'balanceTable', 'orderPreview',
// Wallet unlock form
'forms', 'openForm', 'uwAppPass',
// Order submission is verified with the user's password.
'verifyForm', 'vHeader', 'vSideHeader', 'vSide', 'vQty', 'vBase', 'vRate',
'vTotal', 'vQuote', 'vPass', 'vSideSubmit', 'vBaseSubmit', 'vSubmit', 'verifyLimit', 'verifyMarket',
'vmTotal', 'vmAsset', 'vmLots', 'mktBuyScore',
// Create wallet form
'walletForm',
// Active orders
'liveTemplate', 'liveList', 'liveTable',
// Cancel order form
'cancelForm', 'cancelRemain', 'cancelUnit', 'cancelPass', 'cancelSubmit',
// Chart and legend
'marketChart', 'chartResizer', 'sellBookedBase', 'sellBookedQuote',
'buyBookedBase', 'buyBookedQuote', 'hoverData', 'hoverPrice',
'hoverVolume', 'chartLegend', 'chartErrMsg',
// Max order section
'maxOrd', 'maxLbl', 'maxFromLots', 'maxFromAmt', 'maxFromTicker',
'maxToAmt', 'maxToTicker', 'maxAboveZero', 'maxLotBox', 'maxFromLotsLbl',
'maxBox'
])
this.main = main
this.loaded = app.loading(this.main.parentElement)
this.maxLoaded = null
this.market = null
this.registrationStatus = {}
this.currentForm = null
this.openAsset = null
this.openFunc = null
this.currentCreate = null
this.preorderTimer = null
this.book = null
this.cancelData = null
this.metaOrders = {}
this.depthLines = {
hover: [],
input: []
}
this.activeMarkerRate = null
this.hovers = []
// 'Your Orders' list sort key and direction.
this.ordersSortKey = 'stamp'
// 1 if sorting ascendingly, -1 if sorting descendingly.
this.ordersSortDirection = 1
// store original title so we can re-append it when updating market value.
this.ogTitle = document.title
const reporters = {
click: p => { this.reportClick(p) },
volume: d => { this.reportVolume(d) },
mouse: d => { this.reportMousePosition(d) },
zoom: z => { this.reportZoom(z) }
}
this.chart = new DepthChart(page.marketChart, reporters, State.fetch(depthZoomKey))
// Set up the BalanceWidget.
{
const wgt = this.balanceWgt = new BalanceWidget(page.balanceTable)
const baseIcons = wgt.base.stateIcons.icons
const quoteIcons = wgt.quote.stateIcons.icons
bind(wgt.base.connect, 'click', () => { this.showOpen(this.market.base, this.walletUnlocked) })
bind(wgt.quote.connect, 'click', () => { this.showOpen(this.market.quote, this.walletUnlocked) })
bind(wgt.base.expired, 'click', () => { this.showOpen(this.market.base, this.walletUnlocked) })
bind(wgt.quote.expired, 'click', () => { this.showOpen(this.market.quote, this.walletUnlocked) })
bind(baseIcons.sleeping, 'click', () => { this.showOpen(this.market.base, this.walletUnlocked) })
bind(quoteIcons.sleeping, 'click', () => { this.showOpen(this.market.quote, this.walletUnlocked) })
bind(baseIcons.locked, 'click', () => { this.showOpen(this.market.base, this.walletUnlocked) })
bind(quoteIcons.locked, 'click', () => { this.showOpen(this.market.quote, this.walletUnlocked) })
bind(wgt.base.newWalletBttn, 'click', () => { this.showCreate(this.market.base) })
bind(wgt.quote.newWalletBttn, 'click', () => { this.showCreate(this.market.quote) })
}
// Prepare templates for the buy and sell tables and the user's order table.
cleanTemplates(page.rowTemplate, page.liveTemplate)
// Prepare the list of markets.
this.marketList = new MarketList(page.marketList)
for (const xc of this.marketList.xcSections) {
for (const mkt of xc.marketRows) {
bind(mkt.row, 'click', () => {
this.setMarket(xc.host, mkt.baseID, mkt.quoteID)
})
}
}
// Store the elements that need their ticker changed when the market
// changes.
this.quoteUnits = main.querySelectorAll('[data-unit=quote]')
this.baseUnits = main.querySelectorAll('[data-unit=base]')
// Buttons to set order type and side.
bind(page.buyBttn, 'click', () => {
swapBttns(page.sellBttn, page.buyBttn)
page.submitBttn.classList.remove('sellred')
page.submitBttn.classList.add('buygreen')
page.maxLbl.textContent = 'Buy'
this.setOrderBttnText()
this.setOrderVisibility()
this.drawChartLines()
})
bind(page.sellBttn, 'click', () => {
swapBttns(page.buyBttn, page.sellBttn)
page.submitBttn.classList.add('sellred')
page.submitBttn.classList.remove('buygreen')
page.maxLbl.textContent = 'Sell'
this.setOrderBttnText()
this.setOrderVisibility()
this.drawChartLines()
})
bind(page.limitBttn, 'click', () => {
swapBttns(page.marketBttn, page.limitBttn)
this.setOrderVisibility()
if (!page.rateField.value) return
this.depthLines.input = [{
rate: page.rateField.value,
color: this.isSell() ? this.chart.theme.sellLine : this.chart.theme.buyLine
}]
this.drawChartLines()
})
bind(page.marketBttn, 'click', () => {
swapBttns(page.limitBttn, page.marketBttn)
this.setOrderVisibility()
this.setMarketBuyOrderEstimate()
this.depthLines.input = []
this.drawChartLines()
})
bind(page.maxOrd, 'click', () => {
if (this.isSell()) page.lotField.value = this.market.maxSell.swap.lots
else page.lotField.value = this.market.maxBuys[this.adjustedRate()].swap.lots
this.lotChanged()
})
Doc.disableMouseWheel(page.rateField, page.lotField, page.qtyField, page.mktBuyField)
// Handle the full orderbook sent on the 'book' route.
ws.registerRoute(bookRoute, data => { this.handleBookRoute(data) })
// Handle the new order for the order book on the 'book_order' route.
ws.registerRoute(bookOrderRoute, data => { this.handleBookOrderRoute(data) })
// Remove the order sent on the 'unbook_order' route from the orderbook.
ws.registerRoute(unbookOrderRoute, data => { this.handleUnbookOrderRoute(data) })
// Update the remaining quantity on a booked order.
ws.registerRoute(updateRemainingRoute, data => { this.handleUpdateRemainingRoute(data) })
// Handle the new order for the order book on the 'epoch_order' route.
ws.registerRoute(epochOrderRoute, data => { this.handleEpochOrderRoute(data) })
// Bind the wallet unlock form.
bindOpenWallet(app, page.openForm, async () => { this.openFunc() })
// Create a wallet
this.walletForm = new NewWalletForm(app, page.walletForm, async () => { this.createWallet() })
// Main order form.
bindForm(page.orderForm, page.submitBttn, async () => { this.stepSubmit() })
// Order verification form.
bindForm(page.verifyForm, page.vSubmit, async () => { this.submitOrder() })
// Cancel order form.
bindForm(page.cancelForm, page.cancelSubmit, async () => { this.submitCancel() })
// Bind active orders list's header sort events.
page.liveTable.querySelectorAll('[data-ordercol]')
.forEach(th => bind(th, 'click', () => setOrdersSortCol(th.dataset.ordercol)))
const setOrdersSortCol = (key) => {
// First unset header's current sorted col classes.
unsetOrdersSortColClasses()
// If already sorting by key change sort direction.
if (this.ordersSortKey === key) {
this.ordersSortDirection *= -1
} else {
// Otherwise update sort key and set default direction to ascending.
this.ordersSortKey = key
this.ordersSortDirection = 1
}
this.refreshActiveOrders()
// Set header's new sorted col classes.
setOrdersSortColClasses()
}
const sortClassByDirection = () => {
if (this.ordersSortDirection === 1) return 'sorted-asc'
return 'sorted-dsc'
}
const unsetOrdersSortColClasses = () => {
page.liveTable.querySelectorAll('[data-ordercol]')
.forEach(th => th.classList.remove('sorted-asc', 'sorted-dsc'))
}
const setOrdersSortColClasses = () => {
const key = this.ordersSortKey
const sortCls = sortClassByDirection()
page.liveTable.querySelector(`[data-ordercol=${key}]`).classList.add(sortCls)
}
// Set default's sorted col header classes.
setOrdersSortColClasses()
const closePopups = () => {
Doc.hide(page.forms)
page.vPass.value = ''
page.cancelPass.value = ''
}
// If the user clicks outside of a form, it should close the page overlay.
bind(page.forms, 'mousedown', e => {
if (!Doc.mouseInElement(e, this.currentForm)) {
closePopups()
}
})
this.keyup = e => {
if (e.key === 'Escape') {
closePopups()
}
}
bind(document, 'keyup', this.keyup)
page.forms.querySelectorAll('.form-closer').forEach(el => {
Doc.bind(el, 'click', () => { closePopups() })
})
// Event listeners for interactions with the various input fields.
bind(page.lotField, 'change', () => { this.lotChanged() })
bind(page.lotField, 'keyup', () => { this.lotChanged() })
bind(page.qtyField, 'change', () => { this.quantityChanged(true) })
bind(page.qtyField, 'keyup', () => { this.quantityChanged(false) })
bind(page.mktBuyField, 'change', () => { this.marketBuyChanged() })
bind(page.mktBuyField, 'keyup', () => { this.marketBuyChanged() })
bind(page.rateField, 'change', () => { this.rateFieldChanged() })
bind(page.rateField, 'keyup', () => { this.previewQuoteAmt(true) })
// Market search input bindings.
bind(page.marketSearch, 'change', () => { this.filterMarkets() })
bind(page.marketSearch, 'keyup', () => { this.filterMarkets() })
const clearChartLines = () => {
this.depthLines.hover = []
this.drawChartLines()
}
bind(page.buyRows, 'mouseleave', clearChartLines)
bind(page.sellRows, 'mouseleave', clearChartLines)
bind(page.liveList, 'mouseleave', () => {
this.activeMarkerRate = null
this.setMarkers()
})
// Load the user's layout preferences.
const setChartRatio = r => {
if (r > 0.7) r = 0.7
else if (r < 0.25) r = 0.25
const h = r * (this.main.clientHeight - app.header.offsetHeight)
page.marketChart.style.height = `${h}px`
this.chart.resize(h)
}
const chartDivRatio = State.fetch(chartRatioKey)
if (chartDivRatio) {
setChartRatio(chartDivRatio)
}
// Bind chart resizing.
bind(page.chartResizer, 'mousedown', e => {
if (e.button !== 0) return
e.preventDefault()
let chartRatio
const trackMouse = ee => {
ee.preventDefault()
const box = page.rightSide.getBoundingClientRect()
const h = box.bottom - box.top
chartRatio = (ee.pageY - box.top) / h
setChartRatio(chartRatio)
}
bind(document, 'mousemove', trackMouse)
bind(document, 'mouseup', () => {
if (chartRatio) State.store(chartRatioKey, chartRatio)
Doc.unbind(document, 'mousemove', trackMouse)
})
})
// Notification filters.
this.notifiers = {
order: note => { this.handleOrderNote(note) },
epoch: note => { this.handleEpochNote(note) },
conn: note => { this.handleConnNote(note) },
balance: note => { this.handleBalanceNote(note) },
feepayment: note => { this.handleFeePayment(note) },
walletstate: note => { this.handleWalletStateNote(note) }
}
// Fetch the first market in the list, or the users last selected market, if
// it exists.
let selected
if (data && data.host && typeof data.base !== 'undefined' && typeof data.quote !== 'undefined') {
selected = makeMarket(data.host, parseInt(data.base), parseInt(data.quote))
} else {
selected = State.fetch(lastMarketKey)
}
if (!selected || !this.marketList.exists(selected.host, selected.base, selected.quote)) {
selected = this.marketList.first()
}
this.setMarket(selected.host, selected.base, selected.quote)
// Start a ticker to update time-since values.
this.secondTicker = setInterval(() => {
for (const metaOrder of Object.values(this.metaOrders)) {
const td = Doc.tmplElement(metaOrder.row, 'age')
td.textContent = Doc.timeSince(metaOrder.order.stamp)
}
}, 1000)
// set the initial state for the registration status
this.setRegistrationStatusVisibility()
this.setBalanceVisibility()
}
/* isSell is true if the user has selected sell in the order options. */
isSell () {
return this.page.sellBttn.classList.contains('selected')
}
/* isLimit is true if the user has selected the "limit order" tab. */
isLimit () {
return this.page.limitBttn.classList.contains('selected')
}
/* hasFeePending is true if the fee payment is pending */
hasFeePending () {
const dex = this.market.dex
return typeof dex.confs === 'number' && dex.confs < dex.confsrequired
}
/* assetsAreSupported is true if all the assets of the current market are
* supported
*/
assetsAreSupported () {
const [b, q] = [this.market.base, this.market.quote]
return b && q
}
/*
* setOrderVisibility sets which form is visible based on the specified
* options.
*/
setOrderVisibility () {
const page = this.page
if (this.isLimit()) {
Doc.show(page.priceBox, page.tifBox, page.qtyBox, page.maxBox)
Doc.hide(page.mktBuyBox)
this.previewQuoteAmt(true)
} else {
Doc.hide(page.tifBox, page.maxBox, page.priceBox)
if (this.isSell()) {
Doc.hide(page.mktBuyBox)
Doc.show(page.qtyBox)
this.previewQuoteAmt(true)
} else {
Doc.show(page.mktBuyBox)
Doc.hide(page.qtyBox)
this.previewQuoteAmt(false)
}
}
}
/* resolveOrderFormVisibility displays or hides the 'orderForm' based on
* a set of conditions to be met.
*/
resolveOrderFormVisibility () {
const page = this.page
// By default the order form should be hidden, and only if market is set
// and ready for trading the form should show up.
Doc.hide(page.orderForm)
const feePaid = !this.hasFeePending()
const assetsAreSupported = this.assetsAreSupported()
const base = this.market.base
const quote = this.market.quote
const hasWallets = base && app.assets[base.id].wallet && quote && app.assets[quote.id].wallet
if (feePaid && assetsAreSupported && hasWallets) {
Doc.show(page.orderForm)
}
}
/* setLoaderMsgVisibility displays a message in case a dex asset is not
* supported
*/
setLoaderMsgVisibility () {
const page = this.page
const { base, quote } = this.market
if (this.assetsAreSupported()) {
// make sure to hide the loader msg
Doc.hide(page.loaderMsg)
return
}
const symbol = (!base && this.market.baseCfg.symbol) || (!quote && this.market.quoteCfg.symbol)
page.loaderMsg.textContent = `${symbol.toUpperCase()} is not supported`
Doc.show(page.loaderMsg)
}
/* setRegistrationStatusView sets the text content and class for the
* registration status view
*/
setRegistrationStatusView (titleContent, confStatusMsg, titleClass) {
const page = this.page
page.regStatusTitle.textContent = titleContent
page.regStatusConfsDisplay.textContent = confStatusMsg
page.registrationStatus.classList.remove('completed', 'error', 'waiting')
page.registrationStatus.classList.add(titleClass)
}
/*
* updateRegistrationStatusView updates the view based on the current
* registration status
*/
updateRegistrationStatusView (dexAddr, feePaid, confirmationsRequired, confirmations) {
const page = this.page
page.confReq.textContent = confirmationsRequired
page.regStatusDex.textContent = dexAddr
if (feePaid) {
this.setRegistrationStatusView('Registration fee payment successful!', '', 'completed')
return
}
const confStatusMsg = `${confirmations} / ${confirmationsRequired}`
this.setRegistrationStatusView('Waiting for confirmations...', confStatusMsg, 'waiting')
}
/*
* setRegistrationStatusVisibility toggles the registration status view based
* on the dex data.
*/
setRegistrationStatusVisibility () {
const { page, market: { dex } } = this
const { confs, confsrequired } = dex
const feePending = this.hasFeePending()
// If dex is not connected to server, is not possible to know fee
// registration status.
if (!dex.connected) return
this.updateRegistrationStatusView(dex.host, !feePending, confsrequired, confs)
if (feePending) {
Doc.show(page.registrationStatus)
} else {
const toggle = () => {
Doc.hide(page.registrationStatus)
this.resolveOrderFormVisibility()
}
if (Doc.isHidden(page.orderForm)) {
// wait a couple of seconds before showing the form so the success
// message is shown to the user
setTimeout(toggle, 5000)
return
}
toggle()
}
}
setOrderBttnText () {
if (this.isSell()) {
this.page.submitBttn.textContent = `Place order to sell ${this.market.base.symbol.toUpperCase()}`
} else this.page.submitBttn.textContent = `Place order to buy ${this.market.base.symbol.toUpperCase()}`
}
/* setMarket sets the currently displayed market. */
async setMarket (host, base, quote) {
const dex = app.user.exchanges[host]
const page = this.page
// If we have not yet connected, there is no dex.assets or any other
// exchange data, so just put up a message and wait for the connection to be
// established, at which time handleConnNote will refresh and reload.
if (!dex.connected) {
this.market = { dex: dex }
page.chartErrMsg.textContent = 'Connection to dex server failed. ' +
'You can close dexc and try again later or wait for it to reconnect.'
Doc.show(page.chartErrMsg)
this.loaded()
this.main.style.opacity = 1
Doc.hide(page.marketLoader)
return
}
const baseCfg = dex.assets[base]
const quoteCfg = dex.assets[quote]
Doc.hide(page.maxOrd, page.chartErrMsg)
if (this.preorderTimer) {
window.clearTimeout(this.preorderTimer)
this.preorderTimer = null
}
const mktId = marketID(baseCfg.symbol, quoteCfg.symbol)
this.market = {
dex: dex,
sid: mktId, // A string market identifier used by the DEX.
cfg: dex.markets[mktId],
// app.assets is a map of core.SupportedAsset type, which can be found at
// client/core/types.go.
base: app.assets[base],
quote: app.assets[quote],
// dex.assets is a map of dex.Asset type, which is defined at
// dex/asset.go.
baseCfg: baseCfg,
quoteCfg: quoteCfg,
maxSell: null,
maxBuys: {}
}
page.marketLoader.classList.remove('d-none')
ws.request('loadmarket', makeMarket(host, base, quote))
this.setLoaderMsgVisibility()
this.setRegistrationStatusVisibility()
this.resolveOrderFormVisibility()
this.setOrderBttnText()
}
/*
* reportClick is a callback used by the DepthChart when the user clicks
* on the chart area. The rate field is set to the x-value of the click.
*/
reportClick (p) {
this.page.rateField.value = p.toFixed(8)
this.rateFieldChanged()
}
/*
* reportVolume accepts a volume report from the DepthChart and sets the
* values in the chart legend.
*/
reportVolume (d) {
const page = this.page
page.sellBookedBase.textContent = Doc.formatCoinValue(d.sellBase)
page.sellBookedQuote.textContent = Doc.formatCoinValue(d.sellQuote)
page.buyBookedBase.textContent = Doc.formatCoinValue(d.buyBase)
page.buyBookedQuote.textContent = Doc.formatCoinValue(d.buyQuote)
}
/*
* reportMousePosition accepts informations about the mouse position on the
* chart area.
*/
reportMousePosition (d) {
while (this.hovers.length) this.hovers.shift().classList.remove('hover')
const page = this.page
if (!d) {
Doc.hide(page.hoverData)
return
}
// If the user is hovered to within a small percent (based on chart width)
// of a user order, highlight that order's row.
const markers = d.hoverMarkers.map(v => Math.round(v * 1e8))
for (const metaOrd of Object.values(this.metaOrders)) {
const [row, ord] = [metaOrd.row, metaOrd.order]
if (ord.status !== Order.StatusBooked) continue
if (markers.indexOf(ord.rate) > -1) {
row.classList.add('hover')
this.hovers.push(row)
}
}
page.hoverPrice.textContent = Doc.formatCoinValue(d.rate)
page.hoverVolume.textContent = Doc.formatCoinValue(d.depth)
page.hoverVolume.style.color = d.dotColor
page.chartLegend.style.left = `${d.yAxisWidth}px`
Doc.show(page.hoverData)
}
/*
* reportZoom accepts informations about the current depth chart zoom level.
* This information is saved to disk so that the zoom level can be maintained
* across reloads.
*/
reportZoom (zoom) {
State.store(depthZoomKey, zoom)
}
/*
* parseOrder pulls the order information from the form fields. Data is not
* validated in any way.
*/
parseOrder () {
const page = this.page
let qtyField = page.qtyField
const limit = this.isLimit()
const sell = this.isSell()
const market = this.market
if (!limit && !sell) {
qtyField = page.mktBuyField
}
return {
host: market.dex.host,
isLimit: limit,
sell: sell,
base: market.base.id,
quote: market.quote.id,
qty: asAtoms(qtyField.value),
rate: asAtoms(page.rateField.value), // message-rate
tifnow: page.tifNow.checked
}
}
/**
* previewQuoteAmt shows quote amount when rate or quantity input are changed
*/
previewQuoteAmt (show) {
const page = this.page
const order = this.parseOrder()
const adjusted = this.adjustedRate()
page.orderErr.textContent = ''
if (adjusted) {
if (order.sell) this.preSell()
else this.preBuy()
}
this.depthLines.input = []
if (adjusted && this.isLimit()) {
this.depthLines.input = [{
rate: order.rate / 1e8,
color: order.sell ? this.chart.theme.sellLine : this.chart.theme.buyLine
}]
}
this.drawChartLines()
if (!show || !adjusted || !order.qty) {
page.orderPreview.textContent = ''
this.drawChartLines()
return
}
const quoteAsset = app.assets[order.quote]
const total = Doc.formatCoinValue(order.rate / 1e8 * order.qty / 1e8)
page.orderPreview.textContent = `Total: ${total} ${quoteAsset.symbol.toUpperCase()}`
if (this.isSell()) this.preSell()
else this.preBuy()
}
/**
* preSell populates the max order message for the largest available sell.
*/
preSell () {
const mkt = this.market
const baseWallet = app.assets[mkt.base.id].wallet
if (baseWallet.available < mkt.cfg.lotsize) {
this.setMaxOrder({ lots: 0 }, this.adjustedRate() / 1e8)
return
}
if (mkt.maxSell) {
this.setMaxOrder(mkt.maxSell.swap, this.adjustedRate() / 1e8)
return
}
// We only fetch pre-sell once per balance update, so don't delay.
this.schedulePreOrder('/api/maxsell', {}, 0, res => {
mkt.maxSell = res.maxSell
mkt.sellBalance = baseWallet.balance.available
this.setMaxOrder(res.maxSell.swap, this.adjustedRate() / 1e8)
})
}
/**
* preBuy populates the max order message for the largest available buy.
*/
preBuy () {
const mkt = this.market
const rate = this.adjustedRate()
const quoteWallet = app.assets[mkt.quote.id].wallet
const aLot = mkt.cfg.lotsize * (rate / 1e8)
if (quoteWallet.balance.available < aLot) {
this.setMaxOrder({ lots: 0 }, 1e8 / rate)
return
}
if (mkt.maxBuys[rate]) {
this.setMaxOrder(mkt.maxBuys[rate].swap, 1e8 / rate)
return
}
// 0 delay for first fetch after balance update or market change, otherwise
// meter these at 1 / sec.
const delay = mkt.maxBuys ? 1000 : 0
this.schedulePreOrder('/api/maxbuy', { rate: rate }, delay, res => {
mkt.maxBuys[rate] = res.maxBuy
mkt.buyBalance = app.assets[mkt.quote.id].wallet.balance.available
this.setMaxOrder(res.maxBuy.swap, 1e8 / rate)
})
}
/**
* schedulePreorder shows the loading icon and schedules a call to an order
* estimate api endpoint. If another call to schedulePreorder is made before
* this one is fired (after delay), this call will be canceled.
*/
schedulePreOrder (path, args, delay, success) {
const page = this.page
if (!this.maxLoaded) this.maxLoaded = app.loading(page.maxOrd)
const [bid, qid] = [this.market.base.id, this.market.quote.id]
const [bWallet, qWallet] = [app.assets[bid].wallet, app.assets[qid].wallet]
if (!bWallet || !bWallet.running || !qWallet || !qWallet.running) return
if (this.preorderTimer) window.clearTimeout(this.preorderTimer)
Doc.show(page.maxOrd, page.maxLotBox)
Doc.hide(page.maxAboveZero)
page.maxFromLots.textContent = 'calculating...'
page.maxFromLotsLbl.textContent = ''
this.preorderTimer = window.setTimeout(async () => {
this.preorderTimer = null
const res = await postJSON(path, {
host: this.market.dex.host,
base: bid,
quote: qid,
...args
})
// If a new timer is set, a change was made while fetching the pre-order.
// Abandon this result.
if (this.preorderTimer) return
this.maxLoaded()
this.maxLoaded = null
if (!app.checkResponse(res, true)) {
console.warn('max order estimate not available:', res)
page.maxFromLots.textContent = 'estimate unavailable'
return
}
success(res)
}, delay)
}
/* setMaxOrder sets the max order text. */
setMaxOrder (maxOrder, rate) {
const page = this.page
Doc.show(page.maxOrd, page.maxLotBox, page.maxAboveZero)
const sell = this.isSell()
page.maxFromLots.textContent = maxOrder.lots.toString()
page.maxFromLotsLbl.textContent = maxOrder.lots === 1 ? 'lot' : 'lots'
if (maxOrder.lots === 0) {
Doc.hide(page.maxAboveZero)
return
}
// Could add the maxOrder.estimatedFees here, but that might also be
// confusing.
page.maxFromAmt.textContent = Doc.formatCoinValue(maxOrder.value / 1e8)
page.maxFromTicker.textContent = sell ? this.market.base.symbol : this.market.quote.symbol.toUpperCase()
// Could subtract the maxOrder.redemptionFees here.
page.maxToAmt.textContent = Doc.formatCoinValue(maxOrder.value / 1e8 * rate)
page.maxToTicker.textContent = sell ? this.market.quote.symbol : this.market.base.symbol.toUpperCase()
}
/*
* validateOrder performs some basic order sanity checks, returning boolean
* true if the order appears valid.
*/
validateOrder (order) {
const page = this.page
if (order.isLimit && !order.rate) {
Doc.show(page.orderErr)
page.orderErr.textContent = 'zero rate not allowed'
return false
}
if (!order.qty) {
Doc.show(page.orderErr)
page.orderErr.textContent = 'zero quantity not allowed'
return false
}
return true
}
/* handleBook accepts the data sent in the 'book' notification. */
handleBook (data) {
const [b, q] = [this.market.baseCfg, this.market.quoteCfg]
this.book = new OrderBook(data, b.symbol, q.symbol)
this.loadTable()
for (const order of (data.book.epoch || [])) {
if (order.rate > 0) this.book.add(order)
this.addTableOrder(order)
}
if (!this.book) {
this.chart.clear()
Doc.empty(this.page.buyRows)
Doc.empty(this.page.sellRows)
return
}
this.chart.set(this.book, this.market.cfg.lotsize, this.market.cfg.ratestep)
}
/*
* midGap returns the value in the middle of the best buy and best sell. If
* either one of the buy or sell sides are empty, midGap returns the best
* rate from the other side. If both sides are empty, midGap returns the
* value null.
*/
midGap () {
const book = this.book
if (!book) return
if (book.buys && book.buys.length) {
if (book.sells && book.sells.length) {
return (book.buys[0].rate + book.sells[0].rate) / 2
}
return book.buys[0].rate
}
if (book.sells && book.sells.length) {
return book.sells[0].rate
}
return null
}
/*
* setMarketBuyOrderEstimate sets the "min. buy" display for the current
* market.
*/
setMarketBuyOrderEstimate () {
const market = this.market
const lotSize = market.cfg.lotsize
const xc = app.user.exchanges[market.dex.host]
const buffer = xc.markets[market.sid].buybuffer
const gap = this.midGap()
if (gap) {
this.page.minMktBuy.textContent = Doc.formatCoinValue(lotSize * buffer * gap / 1e8)
}
}
/*
* ordersSortCompare returns sort compare function according to the active
* sort key and direction.
*/
ordersSortCompare () {
switch (this.ordersSortKey) {
case 'stamp':
return (a, b) => this.ordersSortDirection * (b.stamp - a.stamp)
case 'rate':
return (a, b) => this.ordersSortDirection * (a.rate - b.rate)
case 'qty':
return (a, b) => this.ordersSortDirection * (a.qty - b.qty)
case 'type':
return (a, b) => this.ordersSortDirection *
Order.typeString(a).localeCompare(Order.typeString(b))
case 'sell':
return (a, b) => this.ordersSortDirection *
(Order.sellString(a)).localeCompare(Order.sellString(b))
case 'status':
return (a, b) => this.ordersSortDirection *
(Order.statusString(a)).localeCompare(Order.statusString(b))
case 'settled':
return (a, b) => this.ordersSortDirection *
((Order.settled(a) * 100 / a.qty) - (Order.settled(b) * 100 / b.qty))
case 'filled':
return (a, b) => this.ordersSortDirection *
((a.filled * 100 / a.qty) - (b.filled * 100 / b.qty))
}
}
/* refreshActiveOrders refreshes the user's active order list. */
refreshActiveOrders () {
const page = this.page
const metaOrders = this.metaOrders
const market = this.market
for (const oid in metaOrders) delete metaOrders[oid]
const orders = app.orders(market.dex.host, marketID(market.baseCfg.symbol, market.quoteCfg.symbol))
// Sort orders by sort key.
const compare = this.ordersSortCompare()
orders.sort(compare)
Doc.empty(page.liveList)
for (const ord of orders) {
const row = page.liveTemplate.cloneNode(true)
metaOrders[ord.id] = {
row: row,
order: ord
}
Doc.bind(row, 'mouseenter', e => {
this.activeMarkerRate = ord.rate
this.setMarkers()
})
updateUserOrderRow(row, ord)
if (ord.type === Order.Limit && (ord.tif === Order.StandingTiF && ord.status < Order.StatusExecuted)) {
const icon = Doc.tmplElement(row, 'cancelBttn')
Doc.show(icon)
bind(icon, 'click', e => {
e.stopPropagation()
this.showCancel(row, ord.id)
})
}
const side = Doc.tmplElement(row, 'side')
side.classList.add(ord.sell ? 'sellcolor' : 'buycolor')
const link = Doc.tmplElement(row, 'link')
link.href = `order/${ord.id}`
app.bindInternalNavigation(row)
page.liveList.appendChild(row)
app.bindTooltips(row)
}
this.setMarkers()
}
/* setMarkers sets the depth chart markers for booked orders. */
setMarkers () {
const markers = {
buys: [],
sells: []
}
for (const mo of Object.values(this.metaOrders)) {
const ord = mo.order
if (ord.rate && ord.status === Order.StatusBooked) {
if (ord.sell) {
markers.sells.push({
rate: ord.rate / 1e8,
active: ord.rate === this.activeMarkerRate
})
} else {
markers.buys.push({
rate: ord.rate / 1e8,
active: ord.rate === this.activeMarkerRate
})
}
}
}
this.chart.setMarkers(markers)
if (this.book) this.chart.draw()
}
/* updateTitle update the browser title based on the midgap value and the
* selected assets.
*/
updateTitle () {
// gets first price value from buy or from sell, so we can show it on
// title.
const midGapValue = this.midGap()
if (!midGapValue) return
const market = this.market
const [b, q] = [market.baseCfg, market.quoteCfg]
const baseSymb = b.symbol.toUpperCase()
const quoteSymb = q.symbol.toUpperCase()
// more than 6 numbers it gets too big for the title.
document.title = `${midGapValue.toFixed(6)} | ${baseSymb}${quoteSymb} | ${this.ogTitle}`
}
/* handleBookRoute is the handler for the 'book' notification, which is sent
* in response to a new market subscription. The data received will contain
* the entire order book.
*/
handleBookRoute (note) {
app.log('book', 'handleBookRoute:', note)
const mktBook = note.payload
const market = this.market
const page = this.page
const host = market.dex.host
const [b, q] = [market.baseCfg, market.quoteCfg]
if (mktBook.base !== b.id || mktBook.quote !== q.id) return
this.refreshActiveOrders()
this.handleBook(mktBook)
this.updateTitle()
page.marketLoader.classList.add('d-none')
this.marketList.select(host, b.id, q.id)
State.store(lastMarketKey, {
host: note.host,
base: mktBook.base,