forked from decred/dcrdex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexchange_adaptor.go
3842 lines (3361 loc) · 112 KB
/
exchange_adaptor.go
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
// This code is available on the terms of the project LICENSE.md file,
// also available online at https://blueoakcouncil.org/license/1.0.0.
package mm
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"decred.org/dcrdex/client/asset"
"decred.org/dcrdex/client/core"
"decred.org/dcrdex/client/mm/libxc"
"decred.org/dcrdex/client/orderbook"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/calc"
"decred.org/dcrdex/dex/order"
"decred.org/dcrdex/dex/utils"
)
// BotBalance keeps track of the amount of funds available for a
// bot's use, locked to fund orders, and pending.
type BotBalance struct {
Available uint64 `json:"available"`
Locked uint64 `json:"locked"`
Pending uint64 `json:"pending"`
Reserved uint64 `json:"reserved"`
}
func (b *BotBalance) copy() *BotBalance {
return &BotBalance{
Available: b.Available,
Locked: b.Locked,
Pending: b.Pending,
Reserved: b.Reserved,
}
}
// OrderFees represents the fees that will be required for a single lot of a
// dex order.
type OrderFees struct {
*LotFeeRange
Funding uint64 `json:"funding"`
// bookingFeesPerLot is the amount of fee asset that needs to be reserved
// for fees, per ordered lot. For all assets, this will include
// LotFeeRange.Max.Swap. For non-token EVM assets (eth, matic) Max.Refund
// will be added. If the asset is the parent chain of a token counter-asset,
// Max.Redeem is added. This is a commonly needed sum in various validation
// and optimization functions.
BookingFeesPerLot uint64 `json:"bookingFeesPerLot"`
}
// botCoreAdaptor is an interface used by bots to access DEX related
// functions. Common functionality used by multiple market making
// strategies is implemented here. The functions in this interface
// do not need to take assetID parameters, as the bot will only be
// trading on a single DEX market.
type botCoreAdaptor interface {
SyncBook(host string, base, quote uint32) (*orderbook.OrderBook, core.BookFeed, error)
Cancel(oidB dex.Bytes) error
DEXTrade(rate, qty uint64, sell bool) (*core.Order, error)
ExchangeMarket(host string, baseID, quoteID uint32) (*core.Market, error)
ExchangeRateFromFiatSources() uint64
OrderFeesInUnits(sell, base bool, rate uint64) (uint64, error) // estimated fees, not max
SubscribeOrderUpdates() (updates <-chan *core.Order)
SufficientBalanceForDEXTrade(rate, qty uint64, sell bool) (bool, error)
}
// botCexAdaptor is an interface used by bots to access CEX related
// functions. Common functionality used by multiple market making
// strategies is implemented here. The functions in this interface
// take assetID parameters, unlike botCoreAdaptor, to support a
// multi-hop strategy.
type botCexAdaptor interface {
CancelTrade(ctx context.Context, baseID, quoteID uint32, tradeID string) error
SubscribeMarket(ctx context.Context, baseID, quoteID uint32) error
SubscribeTradeUpdates() <-chan *libxc.Trade
CEXTrade(ctx context.Context, baseID, quoteID uint32, sell bool, rate, qty uint64) (*libxc.Trade, error)
SufficientBalanceForCEXTrade(baseID, quoteID uint32, sell bool, rate, qty uint64) bool
MidGap(baseID, quoteID uint32) uint64
Book() (buys, sells []*core.MiniOrder, _ error)
}
// BalanceEffects represents the effects that a market making event has on
// the bot's balances.
type BalanceEffects struct {
Settled map[uint32]int64 `json:"settled"`
Locked map[uint32]uint64 `json:"locked"`
Pending map[uint32]uint64 `json:"pending"`
Reserved map[uint32]uint64 `json:"reserved"`
}
func newBalanceEffects() *BalanceEffects {
return &BalanceEffects{
Settled: make(map[uint32]int64),
Locked: make(map[uint32]uint64),
Pending: make(map[uint32]uint64),
Reserved: make(map[uint32]uint64),
}
}
type balanceEffectsDiff struct {
settled map[uint32]int64
locked map[uint32]int64
pending map[uint32]int64
reserved map[uint32]int64
}
func newBalanceEffectsDiff() *balanceEffectsDiff {
return &balanceEffectsDiff{
settled: make(map[uint32]int64),
locked: make(map[uint32]int64),
pending: make(map[uint32]int64),
reserved: make(map[uint32]int64),
}
}
func (b *BalanceEffects) sub(other *BalanceEffects) *balanceEffectsDiff {
res := newBalanceEffectsDiff()
for assetID, v := range b.Settled {
res.settled[assetID] = v
}
for assetID, v := range b.Locked {
res.locked[assetID] = int64(v)
}
for assetID, v := range b.Pending {
res.pending[assetID] = int64(v)
}
for assetID, v := range b.Reserved {
res.reserved[assetID] = int64(v)
}
for assetID, v := range other.Settled {
res.settled[assetID] -= v
}
for assetID, v := range other.Locked {
res.locked[assetID] -= int64(v)
}
for assetID, v := range other.Pending {
res.pending[assetID] -= int64(v)
}
for assetID, v := range other.Reserved {
res.reserved[assetID] -= int64(v)
}
return res
}
// pendingWithdrawal represents a withdrawal from a CEX that has been
// initiated, but the DEX has not yet received.
type pendingWithdrawal struct {
eventLogID uint64
timestamp int64
withdrawalID string
assetID uint32
// amtWithdrawn is the amount the CEX balance is decreased by.
// It will not be the same as the amount received in the dex wallet.
amtWithdrawn uint64
txMtx sync.RWMutex
txID string
tx *asset.WalletTransaction
}
func withdrawalBalanceEffects(tx *asset.WalletTransaction, cexDebit uint64, assetID uint32) (dex, cex *BalanceEffects) {
dex = newBalanceEffects()
cex = newBalanceEffects()
cex.Settled[assetID] = -int64(cexDebit)
if tx != nil {
if tx.Confirmed {
dex.Settled[assetID] += int64(tx.Amount)
} else {
dex.Pending[assetID] += tx.Amount
}
} else {
dex.Pending[assetID] += cexDebit
}
return
}
func (w *pendingWithdrawal) balanceEffects() (dex, cex *BalanceEffects) {
w.txMtx.RLock()
defer w.txMtx.RUnlock()
return withdrawalBalanceEffects(w.tx, w.amtWithdrawn, w.assetID)
}
// pendingDeposit represents a deposit to a CEX that has not yet been
// confirmed.
type pendingDeposit struct {
eventLogID uint64
timestamp int64
assetID uint32
amtConventional float64
mtx sync.RWMutex
tx *asset.WalletTransaction
feeConfirmed bool
cexConfirmed bool
amtCredited uint64
}
func depositBalanceEffects(assetID uint32, tx *asset.WalletTransaction, cexConfirmed bool) (dex, cex *BalanceEffects) {
feeAsset := assetID
token := asset.TokenInfo(assetID)
if token != nil {
feeAsset = token.ParentID
}
dex, cex = newBalanceEffects(), newBalanceEffects()
dex.Settled[assetID] -= int64(tx.Amount)
dex.Settled[feeAsset] -= int64(tx.Fees)
if cexConfirmed {
cex.Settled[assetID] += int64(tx.Amount)
} else {
cex.Pending[assetID] += tx.Amount
}
return dex, cex
}
func (d *pendingDeposit) balanceEffects() (dex, cex *BalanceEffects) {
d.mtx.RLock()
defer d.mtx.RUnlock()
return depositBalanceEffects(d.assetID, d.tx, d.cexConfirmed)
}
type dexOrderState struct {
dexBalanceEffects *BalanceEffects
cexBalanceEffects *BalanceEffects
order *core.Order
counterTradeRate uint64
}
// pendingDEXOrder keeps track of the balance effects of a pending DEX order.
// The actual order is not stored here, only its effects on the balance.
type pendingDEXOrder struct {
eventLogID uint64
timestamp int64
// swaps, redeems, and refunds are caches of transactions. This avoids
// having to query the wallet for transactions that are already confirmed.
txsMtx sync.RWMutex
swaps map[string]*asset.WalletTransaction
redeems map[string]*asset.WalletTransaction
refunds map[string]*asset.WalletTransaction
// txsMtx is required to be locked for writes to state
state atomic.Value // *dexOrderState
// placementIndex/counterTradeRate are used by MultiTrade to know
// which orders to place/cancel.
placementIndex uint64
counterTradeRate uint64
}
func (p *pendingDEXOrder) cexBalanceEffects() *BalanceEffects {
return p.currentState().cexBalanceEffects
}
// currentState can be called without locking, but to get a consistent view of
// the transactions and the state, txsMtx should be read locked.
func (p *pendingDEXOrder) currentState() *dexOrderState {
return p.state.Load().(*dexOrderState)
}
// counterTradeAsset is the asset that the bot will need to trade on the CEX
// to arbitrage matches on the DEX.
func (p *pendingDEXOrder) counterTradeAsset() uint32 {
o := p.currentState().order
if o.Sell {
return o.QuoteID
}
return o.BaseID
}
type pendingCEXOrder struct {
eventLogID uint64
timestamp int64
tradeMtx sync.RWMutex
trade *libxc.Trade
}
// market is the market-related data for the unifiedExchangeAdaptor and the
// calculators. market provides a number of methods for conversions and
// formatting.
type market struct {
host string
name string
rateStep uint64
lotSize uint64
baseID uint32
baseTicker string
bui dex.UnitInfo
baseFeeID uint32
baseFeeUI dex.UnitInfo
quoteID uint32
quoteTicker string
qui dex.UnitInfo
quoteFeeID uint32
quoteFeeUI dex.UnitInfo
}
func parseMarket(host string, mkt *core.Market) (*market, error) {
bui, err := asset.UnitInfo(mkt.BaseID)
if err != nil {
return nil, err
}
baseFeeID := mkt.BaseID
baseFeeUI := bui
if tkn := asset.TokenInfo(mkt.BaseID); tkn != nil {
baseFeeID = tkn.ParentID
baseFeeUI, err = asset.UnitInfo(tkn.ParentID)
if err != nil {
return nil, err
}
}
qui, err := asset.UnitInfo(mkt.QuoteID)
if err != nil {
return nil, err
}
quoteFeeID := mkt.QuoteID
quoteFeeUI := qui
if tkn := asset.TokenInfo(mkt.QuoteID); tkn != nil {
quoteFeeID = tkn.ParentID
quoteFeeUI, err = asset.UnitInfo(tkn.ParentID)
if err != nil {
return nil, err
}
}
return &market{
host: host,
name: mkt.Name,
rateStep: mkt.RateStep,
lotSize: mkt.LotSize,
baseID: mkt.BaseID,
baseTicker: bui.Conventional.Unit,
bui: bui,
baseFeeID: baseFeeID,
baseFeeUI: baseFeeUI,
quoteID: mkt.QuoteID,
quoteTicker: qui.Conventional.Unit,
qui: qui,
quoteFeeID: quoteFeeID,
quoteFeeUI: quoteFeeUI,
}, nil
}
func (m *market) fmtRate(msgRate uint64) string {
r := calc.ConventionalRate(msgRate, m.bui, m.qui)
s := strconv.FormatFloat(r, 'f', 8, 64)
if strings.Contains(s, ".") {
s = strings.TrimRight(strings.TrimRight(s, "0"), ".")
}
return s
}
func (m *market) fmtBase(atoms uint64) string {
return m.bui.FormatAtoms(atoms)
}
func (m *market) fmtQuote(atoms uint64) string {
return m.qui.FormatAtoms(atoms)
}
func (m *market) fmtQty(assetID uint32, atoms uint64) string {
if assetID == m.baseID {
return m.fmtBase(atoms)
}
return m.fmtQuote(atoms)
}
func (m *market) fmtBaseFees(atoms uint64) string {
return m.baseFeeUI.FormatAtoms(atoms)
}
func (m *market) fmtQuoteFees(atoms uint64) string {
return m.quoteFeeUI.FormatAtoms(atoms)
}
func (m *market) fmtFees(assetID uint32, atoms uint64) string {
if assetID == m.baseID {
return m.fmtBaseFees(atoms)
}
return m.fmtQuoteFees(atoms)
}
func (m *market) msgRate(convRate float64) uint64 {
return calc.MessageRate(convRate, m.bui, m.qui)
}
// unifiedExchangeAdaptor implements both botCoreAdaptor and botCexAdaptor.
type unifiedExchangeAdaptor struct {
*market
clientCore
libxc.CEX
ctx context.Context
wg sync.WaitGroup
botID string
log dex.Logger
fiatRates atomic.Value // map[uint32]float64
orderUpdates atomic.Value // chan *core.Order
mwh *MarketWithHost
eventLogDB eventLogDB
botCfgV atomic.Value // *BotConfig
initialBalances map[uint32]uint64
baseTraits asset.WalletTrait
quoteTraits asset.WalletTrait
botLooper dex.Connector
botLoop *dex.ConnectionMaster
paused atomic.Bool
autoRebalanceCfg *AutoRebalanceConfig
subscriptionIDMtx sync.RWMutex
subscriptionID *int
feesMtx sync.RWMutex
buyFees *OrderFees
sellFees *OrderFees
startTime atomic.Int64
eventLogID atomic.Uint64
balancesMtx sync.RWMutex
// baseDEXBalance/baseCEXBalance are the balances the bots have before
// taking into account any pending actions. These are updated whenever
// a pending action is completed. They may become negative if a balance
// is decreased during an update while there are pending actions that
// positively affect the available balance.
baseDexBalances map[uint32]int64
baseCexBalances map[uint32]int64
pendingDEXOrders map[order.OrderID]*pendingDEXOrder
pendingCEXOrders map[string]*pendingCEXOrder
pendingWithdrawals map[string]*pendingWithdrawal
pendingDeposits map[string]*pendingDeposit
inventoryMods map[uint32]int64
// If pendingBaseRebalance/pendingQuoteRebalance are true, it means
// there is a pending deposit/withdrawal of the base/quote asset,
// and no other deposits/withdrawals of that asset should happen
// until it is complete.
pendingBaseRebalance atomic.Bool
pendingQuoteRebalance atomic.Bool
// The following are updated whenever a pending action is complete.
// For accurate run stats, the pending actions must be taken into
// account.
runStats struct {
completedMatches atomic.Uint32
tradedUSD struct {
sync.Mutex
v float64
}
feeGapStats atomic.Value
}
epochReport atomic.Value // *EpochReport
cexProblemsMtx sync.RWMutex
cexProblems *CEXProblems
}
var _ botCoreAdaptor = (*unifiedExchangeAdaptor)(nil)
var _ botCexAdaptor = (*unifiedExchangeAdaptor)(nil)
func (u *unifiedExchangeAdaptor) botCfg() *BotConfig {
return u.botCfgV.Load().(*BotConfig)
}
// botLooper is just a dex.Connector for a function.
type botLooper func(context.Context) (*sync.WaitGroup, error)
func (f botLooper) Connect(ctx context.Context) (*sync.WaitGroup, error) {
return f(ctx)
}
// setBotLoop sets the loop that must be shut down for configuration updates.
// Every bot should call setBotLoop during construction.
func (u *unifiedExchangeAdaptor) setBotLoop(f botLooper) {
u.botLooper = f
}
func (u *unifiedExchangeAdaptor) runBotLoop(ctx context.Context) error {
if u.botLooper == nil {
return errors.New("no bot looper set")
}
u.botLoop = dex.NewConnectionMaster(u.botLooper)
return u.botLoop.ConnectOnce(ctx)
}
// withPause runs a function with the bot loop paused.
func (u *unifiedExchangeAdaptor) withPause(f func() error) error {
if !u.paused.CompareAndSwap(false, true) {
return errors.New("already paused")
}
defer u.paused.Store(false)
u.botLoop.Disconnect()
if err := f(); err != nil {
return err
}
if u.ctx.Err() != nil { // Make sure we weren't shut down during pause.
return u.ctx.Err()
}
return u.botLoop.ConnectOnce(u.ctx)
}
// logBalanceAdjustments logs a trace log of balance adjustments and updated
// settled balances.
//
// balancesMtx must be read locked when calling this function.
func (u *unifiedExchangeAdaptor) logBalanceAdjustments(dexDiffs, cexDiffs map[uint32]int64, reason string) {
if u.log.Level() > dex.LevelTrace {
return
}
var msg strings.Builder
writeLine := func(s string, a ...interface{}) {
msg.WriteString("\n" + fmt.Sprintf(s, a...))
}
writeLine("")
writeLine("Balance adjustments(%s):", reason)
format := func(assetID uint32, v int64, plusSign bool) string {
ui, err := asset.UnitInfo(assetID)
if err != nil {
return "<what the asset?>"
}
return ui.FormatSignedAtoms(v, plusSign)
}
if len(dexDiffs) > 0 {
writeLine(" DEX:")
for assetID, dexDiff := range dexDiffs {
writeLine(" " + format(assetID, dexDiff, true))
}
}
if len(cexDiffs) > 0 {
writeLine(" CEX:")
for assetID, cexDiff := range cexDiffs {
writeLine(" " + format(assetID, cexDiff, true))
}
}
writeLine("Updated settled balances:")
writeLine(" DEX:")
for assetID, bal := range u.baseDexBalances {
writeLine(" " + format(assetID, bal, false))
}
if len(u.baseCexBalances) > 0 {
writeLine(" CEX:")
for assetID, bal := range u.baseCexBalances {
writeLine(" " + format(assetID, bal, false))
}
}
dexPending := make(map[uint32]uint64)
addDexPending := func(assetID uint32) {
if v := u.dexBalance(assetID).Pending; v > 0 {
dexPending[assetID] = v
}
}
cexPending := make(map[uint32]uint64)
addCexPending := func(assetID uint32) {
if v := u.cexBalance(assetID).Pending; v > 0 {
cexPending[assetID] = v
}
}
addDexPending(u.baseID)
addCexPending(u.baseID)
addDexPending(u.quoteID)
addCexPending(u.quoteID)
if u.baseFeeID != u.baseID {
addCexPending(u.baseFeeID)
addCexPending(u.baseFeeID)
}
if u.quoteFeeID != u.quoteID && u.quoteFeeID != u.baseID {
addCexPending(u.quoteFeeID)
addCexPending(u.quoteFeeID)
}
if len(dexPending) > 0 {
writeLine(" DEX pending:")
for assetID, v := range dexPending {
writeLine(" " + format(assetID, int64(v), true))
}
}
if len(cexPending) > 0 {
writeLine(" CEX pending:")
for assetID, v := range cexPending {
writeLine(" " + format(assetID, int64(v), true))
}
}
writeLine("")
u.log.Tracef(msg.String())
}
// SufficientBalanceForDEXTrade returns whether the bot has sufficient balance
// to place a DEX trade.
func (u *unifiedExchangeAdaptor) SufficientBalanceForDEXTrade(rate, qty uint64, sell bool) (bool, error) {
fromAsset, fromFeeAsset, toAsset, toFeeAsset := orderAssets(u.baseID, u.quoteID, sell)
balances := map[uint32]uint64{}
for _, assetID := range []uint32{fromAsset, fromFeeAsset, toAsset, toFeeAsset} {
if _, found := balances[assetID]; !found {
bal := u.DEXBalance(assetID)
balances[assetID] = bal.Available
}
}
buyFees, sellFees, err := u.orderFees()
if err != nil {
return false, err
}
fees, fundingFees := buyFees.Max, buyFees.Funding
if sell {
fees, fundingFees = sellFees.Max, sellFees.Funding
}
if balances[fromFeeAsset] < fundingFees {
return false, nil
}
balances[fromFeeAsset] -= fundingFees
fromQty := qty
if !sell {
fromQty = calc.BaseToQuote(rate, qty)
}
if balances[fromAsset] < fromQty {
return false, nil
}
balances[fromAsset] -= fromQty
numLots := qty / u.lotSize
if balances[fromFeeAsset] < numLots*fees.Swap {
return false, nil
}
balances[fromFeeAsset] -= numLots * fees.Swap
if u.isAccountLocker(fromAsset) {
if balances[fromFeeAsset] < numLots*fees.Refund {
return false, nil
}
balances[fromFeeAsset] -= numLots * fees.Refund
}
if u.isAccountLocker(toAsset) {
if balances[toFeeAsset] < numLots*fees.Redeem {
return false, nil
}
balances[toFeeAsset] -= numLots * fees.Redeem
}
return true, nil
}
// SufficientBalanceOnCEXTrade returns whether the bot has sufficient balance
// to place a CEX trade.
func (u *unifiedExchangeAdaptor) SufficientBalanceForCEXTrade(baseID, quoteID uint32, sell bool, rate, qty uint64) bool {
var fromAssetID uint32
var fromAssetQty uint64
if sell {
fromAssetID = u.baseID
fromAssetQty = qty
} else {
fromAssetID = u.quoteID
fromAssetQty = calc.BaseToQuote(rate, qty)
}
fromAssetBal := u.CEXBalance(fromAssetID)
return fromAssetBal.Available >= fromAssetQty
}
// dexOrderInfo is used by MultiTrade to keep track of the placement index
// and counter trade rate of an order.
type dexOrderInfo struct {
placementIndex uint64
counterTradeRate uint64
placement *core.QtyRate
}
// updateDEXOrderEvent updates the event log with the current state of a
// pending DEX order and sends an event notification.
func (u *unifiedExchangeAdaptor) updateDEXOrderEvent(o *pendingDEXOrder, complete bool) {
o.txsMtx.RLock()
transactions := make([]*asset.WalletTransaction, 0, len(o.swaps)+len(o.redeems)+len(o.refunds))
addTxs := func(txs map[string]*asset.WalletTransaction) {
for _, tx := range txs {
transactions = append(transactions, tx)
}
}
addTxs(o.swaps)
addTxs(o.redeems)
addTxs(o.refunds)
state := o.currentState()
o.txsMtx.RUnlock()
e := &MarketMakingEvent{
ID: o.eventLogID,
TimeStamp: o.timestamp,
Pending: !complete,
BalanceEffects: combineBalanceEffects(state.dexBalanceEffects, state.cexBalanceEffects),
DEXOrderEvent: &DEXOrderEvent{
ID: state.order.ID.String(),
Rate: state.order.Rate,
Qty: state.order.Qty,
Sell: state.order.Sell,
Transactions: transactions,
},
}
u.eventLogDB.storeEvent(u.startTime.Load(), u.mwh, e, u.balanceState())
u.notifyEvent(e)
}
func cexOrderEvent(trade *libxc.Trade, eventID uint64, timestamp int64) *MarketMakingEvent {
return &MarketMakingEvent{
ID: eventID,
TimeStamp: timestamp,
Pending: !trade.Complete,
BalanceEffects: cexTradeBalanceEffects(trade),
CEXOrderEvent: &CEXOrderEvent{
ID: trade.ID,
Rate: trade.Rate,
Qty: trade.Qty,
Sell: trade.Sell,
BaseFilled: trade.BaseFilled,
QuoteFilled: trade.QuoteFilled,
},
}
}
// updateCEXOrderEvent updates the event log with the current state of a
// pending CEX order and sends an event notification.
func (u *unifiedExchangeAdaptor) updateCEXOrderEvent(trade *libxc.Trade, eventID uint64, timestamp int64) {
event := cexOrderEvent(trade, eventID, timestamp)
u.eventLogDB.storeEvent(u.startTime.Load(), u.mwh, event, u.balanceState())
u.notifyEvent(event)
}
// updateDepositEvent updates the event log with the current state of a
// pending deposit and sends an event notification.
func (u *unifiedExchangeAdaptor) updateDepositEvent(deposit *pendingDeposit) {
deposit.mtx.RLock()
e := &MarketMakingEvent{
ID: deposit.eventLogID,
TimeStamp: deposit.timestamp,
BalanceEffects: combineBalanceEffects(depositBalanceEffects(deposit.assetID, deposit.tx, deposit.cexConfirmed)),
Pending: !deposit.cexConfirmed || !deposit.feeConfirmed,
DepositEvent: &DepositEvent{
AssetID: deposit.assetID,
Transaction: deposit.tx,
CEXCredit: deposit.amtCredited,
},
}
deposit.mtx.RUnlock()
u.eventLogDB.storeEvent(u.startTime.Load(), u.mwh, e, u.balanceState())
u.notifyEvent(e)
}
func (u *unifiedExchangeAdaptor) updateConfigEvent(updatedCfg *BotConfig) {
e := &MarketMakingEvent{
ID: u.eventLogID.Add(1),
TimeStamp: time.Now().Unix(),
UpdateConfig: updatedCfg,
}
u.eventLogDB.storeEvent(u.startTime.Load(), u.mwh, e, u.balanceState())
}
func (u *unifiedExchangeAdaptor) updateInventoryEvent(inventoryMods map[uint32]int64) {
e := &MarketMakingEvent{
ID: u.eventLogID.Add(1),
TimeStamp: time.Now().Unix(),
UpdateInventory: &inventoryMods,
}
u.eventLogDB.storeEvent(u.startTime.Load(), u.mwh, e, u.balanceState())
}
func combineBalanceEffects(dex, cex *BalanceEffects) *BalanceEffects {
effects := newBalanceEffects()
for assetID, v := range dex.Settled {
effects.Settled[assetID] += v
}
for assetID, v := range dex.Locked {
effects.Locked[assetID] += v
}
for assetID, v := range dex.Pending {
effects.Pending[assetID] += v
}
for assetID, v := range dex.Reserved {
effects.Reserved[assetID] += v
}
for assetID, v := range cex.Settled {
effects.Settled[assetID] += v
}
for assetID, v := range cex.Locked {
effects.Locked[assetID] += v
}
for assetID, v := range cex.Pending {
effects.Pending[assetID] += v
}
for assetID, v := range cex.Reserved {
effects.Reserved[assetID] += v
}
return effects
}
// updateWithdrawalEvent updates the event log with the current state of a
// pending withdrawal and sends an event notification.
func (u *unifiedExchangeAdaptor) updateWithdrawalEvent(withdrawal *pendingWithdrawal, tx *asset.WalletTransaction) {
complete := tx != nil && tx.Confirmed
e := &MarketMakingEvent{
ID: withdrawal.eventLogID,
TimeStamp: withdrawal.timestamp,
BalanceEffects: combineBalanceEffects(withdrawal.balanceEffects()),
Pending: !complete,
WithdrawalEvent: &WithdrawalEvent{
AssetID: withdrawal.assetID,
ID: withdrawal.withdrawalID,
Transaction: tx,
CEXDebit: withdrawal.amtWithdrawn,
},
}
u.eventLogDB.storeEvent(u.startTime.Load(), u.mwh, e, u.balanceState())
u.notifyEvent(e)
}
// groupedBookedOrders returns pending dex orders grouped by the placement
// index used to create them when they were placed with MultiTrade.
func (u *unifiedExchangeAdaptor) groupedBookedOrders(sells bool) (orders map[uint64][]*pendingDEXOrder) {
orders = make(map[uint64][]*pendingDEXOrder)
groupPendingOrder := func(pendingOrder *pendingDEXOrder) {
o := pendingOrder.currentState().order
if o.Status > order.OrderStatusBooked {
return
}
pi := pendingOrder.placementIndex
if sells == o.Sell {
if orders[pi] == nil {
orders[pi] = []*pendingDEXOrder{}
}
orders[pi] = append(orders[pi], pendingOrder)
}
}
u.balancesMtx.RLock()
defer u.balancesMtx.RUnlock()
for _, pendingOrder := range u.pendingDEXOrders {
groupPendingOrder(pendingOrder)
}
return
}
// rateCausesSelfMatchFunc returns a function that can be called to determine
// whether a rate would cause a self match. The sell parameter indicates whether
// the returned function will support sell or buy orders.
func (u *unifiedExchangeAdaptor) rateCausesSelfMatchFunc(sell bool) func(rate uint64) bool {
var highestExistingBuy, lowestExistingSell uint64 = 0, math.MaxUint64
for _, groupedOrders := range u.groupedBookedOrders(!sell) {
for _, o := range groupedOrders {
order := o.currentState().order
if sell && order.Rate > highestExistingBuy {
highestExistingBuy = order.Rate
}
if !sell && order.Rate < lowestExistingSell {
lowestExistingSell = order.Rate
}
}
}
return func(rate uint64) bool {
if sell {
return rate <= highestExistingBuy
}
return rate >= lowestExistingSell
}
}
// reservedForCounterTrade returns the amount that is required to be reserved
// on the CEX in order for this order to be counter traded when matched.
func reservedForCounterTrade(sellOnDEX bool, counterTradeRate, remainingQty uint64) uint64 {
if counterTradeRate == 0 {
return 0
}
if sellOnDEX {
return calc.BaseToQuote(counterTradeRate, remainingQty)
}
return remainingQty
}
func withinTolerance(rate, target uint64, driftTolerance float64) bool {
tolerance := uint64(float64(target) * driftTolerance)
lowerBound := target - tolerance
upperBound := target + tolerance
return rate >= lowerBound && rate <= upperBound
}
func (u *unifiedExchangeAdaptor) placeMultiTrade(placements []*dexOrderInfo, sell bool) []*core.MultiTradeResult {
corePlacements := make([]*core.QtyRate, 0, len(placements))
for _, p := range placements {
corePlacements = append(corePlacements, p.placement)
}
botCfg := u.botCfg()
var walletOptions map[string]string
if sell {
walletOptions = botCfg.BaseWalletOptions
} else {
walletOptions = botCfg.QuoteWalletOptions
}
fromAsset, fromFeeAsset, toAsset, toFeeAsset := orderAssets(u.baseID, u.quoteID, sell)
multiTradeForm := &core.MultiTradeForm{
Host: u.host,
Base: u.baseID,
Quote: u.quoteID,
Sell: sell,
Placements: corePlacements,
Options: walletOptions,
MaxLock: u.DEXBalance(fromAsset).Available,
}
newPendingDEXOrders := make([]*pendingDEXOrder, 0, len(placements))
defer func() {
// defer until u.balancesMtx is unlocked
for _, o := range newPendingDEXOrders {
u.updateDEXOrderEvent(o, false)
}
u.sendStatsUpdate()
}()
u.balancesMtx.Lock()
defer u.balancesMtx.Unlock()
results := u.clientCore.MultiTrade([]byte{}, multiTradeForm)
if len(placements) != len(results) {
u.log.Errorf("unexpected number of results. expected %d, got %d", len(placements), len(results))
return results
}
for i, res := range results {
if res.Error != nil {
u.log.Errorf("incomplete multi-trade, couldn't make a placement: %s", res.Error)
continue
}
o := res.Order
var orderID order.OrderID
copy(orderID[:], o.ID)
dexEffects, cexEffects := newBalanceEffects(), newBalanceEffects()
dexEffects.Settled[fromAsset] -= int64(o.LockedAmt)
dexEffects.Settled[fromFeeAsset] -= int64(o.ParentAssetLockedAmt + o.RefundLockedAmt)
dexEffects.Settled[toFeeAsset] -= int64(o.RedeemLockedAmt)
dexEffects.Locked[fromAsset] += o.LockedAmt
dexEffects.Locked[fromFeeAsset] += o.ParentAssetLockedAmt + o.RefundLockedAmt
dexEffects.Locked[toFeeAsset] += o.RedeemLockedAmt
if o.FeesPaid != nil && o.FeesPaid.Funding > 0 {
dexEffects.Settled[fromFeeAsset] -= int64(o.FeesPaid.Funding)
}
reserved := reservedForCounterTrade(o.Sell, placements[i].counterTradeRate, o.Qty)
cexEffects.Settled[toAsset] -= int64(reserved)
cexEffects.Reserved[toAsset] = reserved
pendingOrder := &pendingDEXOrder{
eventLogID: u.eventLogID.Add(1),
timestamp: time.Now().Unix(),
swaps: make(map[string]*asset.WalletTransaction),