Repository navigation
Expand file tree
/
Copy pathbiz.go
More file actions
1832 lines (1705 loc) · 51.1 KB
/
Copy pathbiz.go
File metadata and controls
1832 lines (1705 loc) · 51.1 KB
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
package banexg
import (
"bytes"
"compress/gzip"
"context"
"encoding/gob"
"fmt"
"io"
"maps"
"math"
"math/rand"
"net/http"
"net/url"
"os"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/banbox/banexg/errs"
"github.com/banbox/banexg/log"
"github.com/banbox/banexg/utils"
"github.com/banbox/bntp"
"github.com/sasha-s/go-deadlock"
"github.com/shopspring/decimal"
"go.uber.org/zap"
)
// globalProxy holds the process-wide HTTP proxy function set via SetProxy.
// It is applied by NewHttpClient and as a fallback in Exchange.Init.
var globalProxy func(*http.Request) (*url.URL, error)
// SetProxy sets a process-wide HTTP proxy. It also patches
// http.DefaultTransport so that any code using http.Get / http.DefaultClient
// automatically goes through the proxy.
// - "no" : explicitly disable proxy
// - "" : if globalProxy is already set, keep it; otherwise try
// HTTPS_PROXY / HTTP_PROXY env, then system proxy
// - other : use as proxy URL
func SetProxy(proxyUrl string) *errs.Error {
if proxyUrl == "no" {
globalProxy = nil
if t, ok := http.DefaultTransport.(*http.Transport); ok {
t.Proxy = http.ProxyFromEnvironment
}
return nil
}
if proxyUrl == "" {
if globalProxy != nil {
return nil
}
// 尝试从环境变量和系统代理中解析
proxyUrl = utils.GetSystemEnvProxy()
if proxyUrl == "" {
prx, err := utils.GetSystemProxy()
if err != nil {
log.Error("GetSystemProxy fail, skip", zap.Error(err))
} else if prx != nil {
proxyUrl = fmt.Sprintf("%s://%s:%s", prx.Protocol, prx.Host, prx.Port)
}
}
if proxyUrl == "" {
return nil
}
}
parsed, err := url.Parse(proxyUrl)
if err != nil {
return errs.New(errs.CodeParamInvalid, err)
}
globalProxy = http.ProxyURL(parsed)
if t, ok := http.DefaultTransport.(*http.Transport); ok {
t.Proxy = globalProxy
}
return nil
}
// GetProxy returns the current global proxy URL string, or empty if not set.
func GetProxy() string {
if globalProxy == nil {
return ""
}
u, err := globalProxy(nil)
if err != nil || u == nil {
return ""
}
return u.String()
}
// NewHttpClient creates an *http.Client that inherits the global proxy set
// via SetProxy. Callers may further customise the returned client.
func NewHttpClient() *http.Client {
client := &http.Client{}
if globalProxy != nil {
client.Transport = &http.Transport{Proxy: globalProxy}
}
return client
}
func (e *Exchange) Init() *errs.Error {
e.HttpClient = &http.Client{}
e.wsCheckStop = make(chan struct{})
// 代理解析:优先传入Proxy(no表示禁用),其次全局代理(含env/system自动检测)
proxyUrl := utils.GetMapVal(e.Options, OptProxy, "")
if proxyUrl == "no" {
// 显式禁用代理
} else if proxyUrl != "" {
proxy, err := url.Parse(proxyUrl)
if err != nil {
return errs.New(errs.CodeParamInvalid, err)
}
e.Proxy = http.ProxyURL(proxy)
e.HttpClient.Transport = &http.Transport{Proxy: e.Proxy}
} else {
// 空字符串:尝试触发全局自动检测,然后使用全局代理
_ = SetProxy("")
if globalProxy != nil {
e.Proxy = globalProxy
e.HttpClient.Transport = &http.Transport{Proxy: globalProxy}
}
}
e.parseOptCreds()
utils.SetFieldBy(&e.UserAgent, e.Options, OptUserAgent, "")
if e.EnableRateLimit == BoolNull {
e.EnableRateLimit = BoolTrue
}
e.CalcRateLimiterCost = makeCalcRateLimiterCost(e)
e.ReqHeaders = DefReqHeaders
reqHeaders := utils.GetMapVal(e.Options, OptReqHeaders, map[string]string{})
for k, v := range reqHeaders {
e.ReqHeaders[k] = v
}
e.WsIntvs = DefWsIntvs
wsIntvs := utils.GetMapVal(e.Options, OptWsIntvs, map[string]int{})
for k, v := range wsIntvs {
e.WsIntvs[k] = v
}
e.Retries = DefRetries
retries := utils.GetMapVal(e.Options, OptRetries, map[string]int{})
for k, v := range retries {
e.Retries[k] = v
}
// 更新api缓存时间
apiCaches := utils.GetMapVal(e.Options, OptApiCaches, map[string]int{})
var failCaches []string
for k, v := range apiCaches {
if api, ok := e.Apis[k]; ok {
api.CacheSecs = v
} else {
failCaches = append(failCaches, k)
}
}
if len(failCaches) > 0 {
log.Error("invalid api keys for OptApiCaches", zap.Strings("keys", failCaches))
}
err := e.SetDump(utils.GetMapVal(e.Options, OptDumpPath, ""))
if err != nil {
return err
}
err = e.SetReplay(utils.GetMapVal(e.Options, OptReplayPath, ""))
if err != nil {
return err
}
apiEnv := utils.GetMapVal(e.Options, OptEnv, "")
if apiEnv == "test" {
e.Hosts.TestNet = true
}
// 更新手续费比率
fees := utils.GetMapVal(e.Options, OptFees, map[string]map[string]float64{})
e.SetFees(fees)
utils.SetFieldBy(&e.CareMarkets, e.Options, OptCareMarkets, nil)
utils.SetFieldBy(&e.MarketType, e.Options, OptMarketType, MarketSpot)
utils.SetFieldBy(&e.ContractType, e.Options, OptContractType, "")
utils.SetFieldBy(&e.TimeInForce, e.Options, OptTimeInForce, DefTimeInForce)
utils.SetFieldBy(&e.DebugWS, e.Options, OptDebugWs, false)
utils.SetFieldBy(&e.DebugAPI, e.Options, OptDebugApi, false)
utils.SetFieldBy(&e.WsBatchSize, e.Options, OptDumpBatchSize, 1000)
utils.SetFieldBy(&e.WsTimeout, e.Options, OptWsTimeout, 15000)
e.CurrByCodeLock.Lock()
e.CurrByIdLock.Lock()
e.CurrCodeMap = DefCurrCodeMap
e.CurrenciesById = map[string]*Currency{}
e.CurrenciesByCode = map[string]*Currency{}
e.WSClients = map[string]*WsClient{}
e.WsOutChans = map[string]interface{}{}
e.WsChanRefs = map[string]map[string]struct{}{}
e.OrderBooks = map[string]*OrderBook{}
e.MarkPrices = map[string]map[string]float64{}
e.KeyTimeStamps = map[string]int64{}
e.ExgInfo.Min1mHole = 1
e.CurrByIdLock.Unlock()
e.CurrByCodeLock.Unlock()
return nil
}
/**************************** Business Functions *******************************/
func (e *Exchange) SafeCurrency(currId string) *Currency {
if currId == "" {
return &Currency{}
}
if e.CurrenciesById != nil {
e.CurrByIdLock.Lock()
curr, ok := e.CurrenciesById[currId]
e.CurrByIdLock.Unlock()
if ok {
return curr
}
}
code := currId
if mapped, ok := e.CurrCodeMap[strings.ToUpper(currId)]; ok {
code = mapped
}
return &Currency{
ID: currId,
Code: code,
}
}
func (e *Exchange) SetFees(fees map[string]map[string]float64) {
if len(fees) == 0 {
return
}
if e.Fees == nil {
e.Fees = &ExgFee{}
}
for market, feeMap := range fees {
var target *TradeFee
if market == "linear" {
if e.Fees.Linear == nil {
e.Fees.Linear = &TradeFee{}
}
target = e.Fees.Linear
} else if market == "inverse" {
if e.Fees.Inverse == nil {
e.Fees.Inverse = &TradeFee{}
}
target = e.Fees.Inverse
} else {
if e.Fees.Main == nil {
e.Fees.Main = &TradeFee{}
}
target = e.Fees.Main
}
for field, rate := range feeMap {
field = strings.ToLower(field)
if field == "taker" {
target.Taker = rate
} else if field == "maker" {
target.Maker = rate
} else {
log.Warn("unknown fee Field, expect: maker/taker", zap.String("val", field))
}
}
}
}
func (e *Exchange) SafeCurrencyCode(currId string) string {
return e.SafeCurrency(currId).Code
}
func doLoadMarkets(e *Exchange, params map[string]interface{}) {
var markets MarketMap
var currencies CurrencyMap
var err *errs.Error
markets, currencies = e.getMarketsCache(true)
if markets == nil {
markets, currencies, err = e.fetchMarketsCurrs(params)
if err != nil {
e.MarketsWait <- err
return
}
}
// 更新Markets
e.setMarkets(markets)
// 更新currencies
e.setCurrencies(currencies, markets)
e.MarketsWait <- markets
}
func (e *Exchange) fetchMarketsCurrs(params map[string]interface{}) (MarketMap, CurrencyMap, *errs.Error) {
var markets MarketMap
var currencies CurrencyMap
var err *errs.Error
// 设置写入锁
marketsLock.Lock()
defer marketsLock.Unlock()
ts, ok := exgMarketTS[e.Name]
delayMins := int((e.MilliSeconds() - ts) / 60000)
if ok && delayMins == 0 {
// 并发写入,其他线程已写入
markets, currencies = e.getMarketsCache(false)
if markets != nil {
return markets, currencies, nil
}
}
if e.HasApi(ApiFetchCurrencies, "") {
currencies, err = e.FetchCurrencies(params)
if err != nil {
return nil, nil, err
}
}
cares := e.getAllCareMarkets()
markets, err = e.FetchMarkets(cares, params)
if err != nil {
return nil, nil, err
}
// 写入到缓存
exgMarketTS[e.Name] = e.MilliSeconds()
exgCacheCurrs[e.Name] = currencies
exgCacheMarkets[e.Name] = markets
exgCareMarkets[e.Name] = cares
return markets, currencies, nil
}
func (e *Exchange) setMarkets(markets MarketMap) {
// 现货的放在前面
items := make([]*Market, 0, len(markets))
for _, v := range markets {
items = append(items, v)
}
sort.Slice(items, func(i, j int) bool {
var iv, ij = 0, 0
if items[i].Spot {
iv = 1
}
if items[j].Spot {
ij = 1
}
return iv > ij
})
marketsById := make(MarketArrMap)
var symbols = make([]string, len(markets))
var IDs = make([]string, 0, len(markets)/2)
for i, item := range items {
symbols[i] = item.Symbol
if list, ok := marketsById[item.ID]; ok {
marketsById[item.ID] = append(list, item)
} else {
marketsById[item.ID] = []*Market{item}
IDs = append(IDs, item.ID)
}
}
sort.Strings(symbols)
sort.Strings(IDs)
// 按固定顺序获取锁,防止死锁
e.MarketsLock.Lock()
e.MarketsByIdLock.Lock()
e.Markets = markets
e.MarketsById = marketsById
e.Symbols = symbols
e.IDs = IDs
e.MarketsByIdLock.Unlock()
e.MarketsLock.Unlock()
}
func (e *Exchange) setCurrencies(currencies CurrencyMap, markets MarketMap) {
var currByCode CurrencyMap
var currById CurrencyMap
if currencies == nil {
var currs = make([]*Currency, 0)
var defCurrPrec, defCurrPrecMode = float64(8), PrecModeDecimalPlace
for _, market := range markets {
if market.Base != "" {
curr := Currency{
ID: market.BaseID,
Code: market.Base,
Precision: market.Precision.Base,
PrecMode: market.Precision.ModeBase,
}
if curr.ID == "" {
curr.ID = market.Base
}
if curr.Precision == 0 {
if market.Precision.Amount > 0 {
curr.Precision = market.Precision.Amount
curr.PrecMode = market.Precision.ModeAmount
} else {
curr.Precision = defCurrPrec
curr.PrecMode = defCurrPrecMode
}
}
currs = append(currs, &curr)
}
if market.Quote == "" {
curr := Currency{
ID: market.QuoteID,
Code: market.Quote,
Precision: market.Precision.Quote,
PrecMode: market.Precision.ModeQuote,
}
if curr.ID == "" {
curr.ID = market.Quote
}
if curr.Precision == 0 {
if market.Precision.Price > 0 {
curr.Precision = market.Precision.Price
curr.PrecMode = market.Precision.ModePrice
} else {
curr.Precision = defCurrPrec
curr.PrecMode = defCurrPrecMode
}
}
currs = append(currs, &curr)
}
}
var highPrecs = make(map[string]*Currency)
for _, curr := range currs {
if old, ok := highPrecs[curr.Code]; ok {
if old.PrecMode == PrecModeTickSize {
if curr.Precision < old.Precision {
highPrecs[curr.Code] = curr
}
} else if curr.Precision > old.Precision {
highPrecs[curr.Code] = curr
}
} else {
highPrecs[curr.Code] = curr
}
}
// 先复制现有的 CurrenciesByCode
e.CurrByCodeLock.Lock()
currByCode = make(CurrencyMap, len(e.CurrenciesByCode)+len(highPrecs))
for k, v := range e.CurrenciesByCode {
currByCode[k] = v
}
e.CurrByCodeLock.Unlock()
for _, v := range highPrecs {
if old, ok := currByCode[v.Code]; ok {
old.ID = v.ID
old.Precision = v.Precision
old.PrecMode = v.PrecMode
} else {
currByCode[v.Code] = v
}
}
} else {
currByCode = currencies
}
currById = make(CurrencyMap, len(currByCode))
for _, v := range currByCode {
currById[v.ID] = v
}
// 按固定顺序获取锁,防止死锁
e.CurrByCodeLock.Lock()
e.CurrByIdLock.Lock()
e.CurrenciesByCode = currByCode
e.CurrenciesById = currById
e.CurrByIdLock.Unlock()
e.CurrByCodeLock.Unlock()
}
func (e *Exchange) getMarketsCache(lock bool) (MarketMap, CurrencyMap) {
// 检查时间戳未过期
if lock {
marketsLock.RLock()
defer marketsLock.RUnlock()
}
ts, ok := exgMarketTS[e.Name]
delayMins := int((e.MilliSeconds() - ts) / 60000)
if !ok || delayMins < exgMarketExpireMins {
return nil, nil
}
// 检查是否缓存了所有所需的市场类型
if len(e.CareMarkets) < len(e.getAllCareMarkets()) {
return nil, nil
}
// 检查有缓存结果
markets, ok := exgCacheMarkets[e.Name]
if !ok || len(markets) == 0 {
return nil, nil
}
currs, ok := exgCacheCurrs[e.Name]
if !ok || len(currs) == 0 {
return nil, nil
}
return markets, currs
}
/*
将当前交易所的CareMarkets和全局所有交易所的ExgCareMarkets合并返回。
用于刷新全部市场信息
*/
func (e *Exchange) getAllCareMarkets() []string {
careArr, ok := exgCareMarkets[e.Name]
if !ok || len(careArr) == 0 {
return e.CareMarkets
}
cares := map[string]struct{}{}
for _, mar := range careArr {
cares[mar] = struct{}{}
}
for _, mar := range e.CareMarkets {
cares[mar] = struct{}{}
}
var res = make([]string, 0, len(cares))
for key := range cares {
res = append(res, key)
}
return res
}
func (e *Exchange) LoadMarkets(reload bool, params map[string]interface{}) (MarketMap, *errs.Error) {
if reload || e.Markets == nil {
if e.MarketsWait == nil {
e.MarketsWait = make(chan interface{})
log.Debug("try load markets", zap.Int64("stamp", e.MilliSeconds()))
go doLoadMarkets(e, params)
}
result := <-e.MarketsWait
e.MarketsWait = nil
if mars, ok := result.(MarketMap); ok && mars != nil {
return mars, nil
}
if err, ok := result.(*errs.Error); ok && err != nil {
return nil, err
}
return nil, errs.NewMsg(errs.CodeUnsupportMarket, "unknown markets type: %t", result)
}
return e.Markets, nil
}
func (e *Exchange) GetPriceOnePip(pair string) (float64, *errs.Error) {
markets, err := e.LoadMarkets(false, nil)
if err != nil {
return 0, err
}
if mar, ok := markets[pair]; ok {
precision := mar.Precision.Price
if mar.Precision.ModePrice == PrecModeTickSize {
return precision, nil
} else {
return 1 / math.Pow(10, precision), nil
}
}
return 0, errs.NewMsg(errs.CodeNoMarketForPair, "no market found for pair")
}
func (e *Exchange) GetCurMarkets() MarketMap {
result := make(MarketMap)
fltFut := e.IsContract(e.MarketType)
isSwap := e.ContractType == MarketSwap
e.MarketsLock.Lock()
for key, mar := range e.Markets {
if !mar.Active || mar.Type != e.MarketType {
continue
}
if fltFut && isSwap && !mar.Swap {
continue
}
result[key] = mar
}
e.MarketsLock.Unlock()
return result
}
func (e *Exchange) GetMarketBy(symbol string) (*Market, bool) {
var mar *Market
var ok bool
e.MarketsLock.Lock()
if len(e.Markets) > 0 {
mar, ok = e.Markets[symbol]
}
e.MarketsLock.Unlock()
return mar, ok
}
/*
GetMarket 获取市场信息
symbol ccxt的symbol、交易所的ID,必须严格正确,如果可能错误,
根据当前的MarketType和MarketInverse过滤匹配
*/
func (e *Exchange) GetMarket(symbol string) (*Market, *errs.Error) {
if e.Markets == nil {
return nil, errs.NewMsg(errs.CodeMarketNotLoad, "markets not loaded")
}
if mar, ok := e.GetMarketBy(symbol); ok {
if mar.Spot && e.IsContract("") {
// 当前是合约模式,返回合约的Market
settle := mar.Quote
if e.MarketType == MarketInverse {
settle = mar.Base
}
futureSymbol := symbol + ":" + settle
if mar, ok = e.GetMarketBy(futureSymbol); ok {
return mar, nil
}
return nil, errs.NewMsg(errs.CodeNoMarketForPair, "no market found: %v - %v - %v",
e.ExgInfo.Name, e.ExgInfo.MarketType, symbol)
}
return mar, nil
} else {
market := e.GetMarketById(symbol, "")
if market != nil {
return market, nil
}
}
return nil, errs.NewMsg(errs.CodeNoMarketForPair, "no market found: %v - %v - %v",
e.ExgInfo.Name, e.ExgInfo.MarketType, symbol)
}
func (e *Exchange) MapMarket(exgSID string, year int) (*Market, *errs.Error) {
mar := e.GetMarketById(exgSID, "")
if mar == nil {
return nil, errs.NewMsg(errs.CodeNoMarketForPair, "no market found: %v - %v - %v",
e.ExgInfo.Name, e.ExgInfo.MarketType, exgSID)
}
return mar, nil
}
/*
GetMarketID
从CCXT的symbol得到交易所ID
*/
func (e *Exchange) GetMarketID(symbol string) (string, *errs.Error) {
market, err := e.GetMarket(symbol)
if err != nil {
return "", err
}
return market.ID, nil
}
func (e *Exchange) GetMarketIDByArgs(args map[string]interface{}, required bool) (string, *errs.Error) {
symbol := utils.PopMapVal(args, ParamSymbol, "")
if symbol == "" {
if required {
return "", errs.NewMsg(errs.CodeParamRequired, "symbol required")
}
return "", nil
}
return e.GetMarketID(symbol)
}
/*
GetMarketById get market by exchange id (Upper Required!)
*/
func (e *Exchange) GetMarketById(marketId, marketType string) *Market {
if e.MarketsById == nil {
return nil
}
e.MarketsByIdLock.Lock()
mars, ok := e.MarketsById[marketId]
e.MarketsByIdLock.Unlock()
if ok {
// 这里不能判断有一个时直接返回,有可能市场不一致:bybit现货市场信息不含SEC,但现货tickers含SEC
if marketType == "" {
marketType = e.MarketType
}
for _, mar := range mars {
if mar.Type == marketType {
return mar
} else if mar.Margin && marketType == MarketMargin {
mar2 := *mar
mar2.Type = MarketMargin
return &mar2
}
}
}
return nil
}
/*
SafeMarket
从交易所品种ID转为规范化市场信息
*/
func (e *Exchange) SafeMarket(marketId, delimiter, marketType string) *Market {
// GetMarketById 内部已有锁保护
market := e.GetMarketById(marketId, marketType)
if market != nil {
return market
}
result := &Market{
ID: marketId,
}
if delimiter != "" {
parts := strings.Split(marketId, delimiter)
if len(parts) == 2 {
result.BaseID = parts[0]
result.QuoteID = parts[1]
result.Base = e.SafeCurrencyCode(result.BaseID)
result.Quote = e.SafeCurrencyCode(result.QuoteID)
result.Symbol = result.Base + "/" + result.Quote
}
}
return result
}
/*
SafeSymbol 将交易所品种ID转为规范化品种ID
marketType TradeSpot/TradeMargin/TradeSwap/TradeFuture/TradeOption
linear/inverse
*/
func (e *Exchange) SafeSymbol(marketId, delimiter, marketType string) string {
return e.SafeMarket(marketId, delimiter, marketType).Symbol
}
/*
CheckSymbols
split valid and invalid symbols
*/
func (e *Exchange) CheckSymbols(symbols ...string) ([]string, []string) {
var items = make(map[string]struct{})
for _, symbol := range symbols {
items[symbol] = struct{}{}
}
e.MarketsLock.Lock()
var valids = make([]string, 0, len(symbols))
var fails = make([]string, 0, len(symbols)/5)
for symbol := range items {
if _, ok := e.Markets[symbol]; ok {
valids = append(valids, symbol)
} else {
fails = append(fails, symbol)
}
}
e.MarketsLock.Unlock()
return valids, fails
}
func (e *Exchange) Info() *ExgInfo {
return e.ExgInfo
}
func (e *Exchange) FetchOHLCV(symbol, timeframe string, since int64, limit int, params map[string]interface{}) ([]*Kline, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchBalance(params map[string]interface{}) (*Balances, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchPositions(symbols []string, params map[string]interface{}) ([]*Position, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchAccountPositions(symbols []string, params map[string]interface{}) ([]*Position, *errs.Error) {
return nil, nil
}
func (e *Exchange) FetchTicker(symbol string, params map[string]interface{}) (*Ticker, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchTickers(symbols []string, params map[string]interface{}) ([]*Ticker, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchTickerPrice(symbol string, params map[string]interface{}) (map[string]float64, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchOrder(symbol, orderId string, params map[string]interface{}) (*Order, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchOrders(symbol string, since int64, limit int, params map[string]interface{}) ([]*Order, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchOpenOrders(symbol string, since int64, limit int, params map[string]interface{}) ([]*Order, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchIncomeHistory(inType string, symbol string, since int64, limit int, params map[string]interface{}) ([]*Income, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchFundingRate(symbol string, params map[string]interface{}) (*FundingRateCur, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchFundingRates(symbols []string, params map[string]interface{}) ([]*FundingRateCur, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchFundingRateHistory(symbol string, since int64, limit int, params map[string]interface{}) ([]*FundingRate, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchLastPrices(symbols []string, params map[string]interface{}) ([]*LastPrice, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) FetchOrderBook(symbol string, limit int, params map[string]interface{}) (*OrderBook, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) CreateOrder(symbol, odType, side string, amount float64, price float64, params map[string]interface{}) (*Order, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) EditOrder(symbol, orderId, side string, amount, price float64, params map[string]interface{}) (*Order, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) CancelOrder(id string, symbol string, params map[string]interface{}) (*Order, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) SetLeverage(leverage float64, symbol string, params map[string]interface{}) (map[string]interface{}, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) LoadLeverageBrackets(reload bool, params map[string]interface{}) *errs.Error {
return errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) GetLeverage(symbol string, notional float64, account string) (float64, float64) {
return 0, 0
}
func (e *Exchange) CalcMaintMargin(symbol string, cost float64) (float64, *errs.Error) {
return 0, nil
}
func (e *Exchange) InitLeverageBrackets() *errs.Error {
return nil
}
func (e *Exchange) Call(method string, params map[string]interface{}) (*HttpRes, *errs.Error) {
params = utils.SafeParams(params)
tryNum := utils.PopMapVal(params, ParamRetry, -1)
if tryNum < 0 {
tryNum = e.GetRetryNum(method, 1)
}
rsp := e.RequestApiRetry(context.Background(), method, params, tryNum)
if rsp.Error != nil {
return nil, rsp.Error
}
return rsp, nil
}
func (e *Exchange) WatchOrderBooks(symbols []string, limit int, params map[string]interface{}) (chan *OrderBook, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) UnWatchOrderBooks(symbols []string, params map[string]interface{}) *errs.Error {
return errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) WatchOHLCVs(jobs [][2]string, params map[string]interface{}) (chan *PairTFKline, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) UnWatchOHLCVs(jobs [][2]string, params map[string]interface{}) *errs.Error {
return errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) WatchMarkPrices(symbols []string, params map[string]interface{}) (chan map[string]float64, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) UnWatchMarkPrices(symbols []string, params map[string]interface{}) *errs.Error {
return errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) WatchTrades(symbols []string, params map[string]interface{}) (chan *Trade, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) UnWatchTrades(symbols []string, params map[string]interface{}) *errs.Error {
return errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) WatchMyTrades(params map[string]interface{}) (chan *MyTrade, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) WatchBalance(params map[string]interface{}) (chan *Balances, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) WatchPositions(params map[string]interface{}) (chan []*Position, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) WatchAccountConfig(params map[string]interface{}) (chan *AccountConfig, *errs.Error) {
return nil, errs.NewMsg(errs.CodeNotImplement, "method not implement")
}
func (e *Exchange) CloseWsFile() {
if e.WsFile != nil {
err_ := e.WsFile.Close()
if err_ != nil {
log.Error("close ws file fail", zap.Error(err_))
}
e.WsFile = nil
}
}
func (e *Exchange) SetDump(path string) *errs.Error {
if path == "" {
if e.WsEncoder != nil {
if len(e.WsCache) > 0 {
err_ := e.WsEncoder.Encode(e.WsCache)
if err_ != nil {
log.Error("dump ws cache fail", zap.Error(err_))
}
}
e.WsEncoder = nil
err_ := e.WsWriter.Close()
if err_ != nil {
log.Error("write ws cache fail", zap.Error(err_))
}
e.WsWriter = nil
e.CloseWsFile()
}
return nil
}
if e.WsDecoder != nil {
return errs.NewMsg(errs.CodeRunTime, "cannot dump in replay mode")
}
// dump websocket messages for replay later
file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return errs.New(errs.CodeIOWriteFail, err)
}
e.WsFile = file
e.WsCache = nil
e.WsWriter = gzip.NewWriter(file)
e.WsEncoder = gob.NewEncoder(e.WsWriter)
return nil
}
func (e *Exchange) SetReplay(path string) *errs.Error {
if path == "" {
if e.WsDecoder != nil {
e.WsDecoder = nil
err := e.WsReader.Close()
if err != nil {
return errs.New(errs.CodeIOReadFail, err)
}
e.WsReader = nil
e.CloseWsFile()
}
return nil
}
// replay ws message with dumped file
if e.WsEncoder != nil {
return errs.NewMsg(errs.CodeRunTime, "cannot set replay in dump mode !")
}
file, err := os.Open(path)
if err != nil {
return errs.New(errs.CodeIOReadFail, err)
}
e.WsFile = file
e.WsCache = nil
e.WsReader, err = gzip.NewReader(file)
if err != nil {
return errs.New(errs.CodeIOReadFail, err)
}
e.WsDecoder = gob.NewDecoder(e.WsReader)
return nil
}
func (e *Exchange) DumpWS(name string, data interface{}) {
if e.WsEncoder == nil || data == nil {
return
}
dataStr, err_ := utils.MarshalString(data)
if err_ != nil {
log.Warn("marshal data fail for DumpWs", zap.String("name", name), zap.Error(err_))
return
}
item := &WsLog{
Name: name,
TimeMS: bntp.UTCStamp(),
Content: dataStr,
}
e.WsCache = append(e.WsCache, item)
if len(e.WsCache) > e.WsBatchSize {
rows := e.WsCache
e.WsCache = nil
go func() {
e.wsCacheLock.Lock()
defer e.wsCacheLock.Unlock()
err := e.WsEncoder.Encode(rows)
if err != nil {
log.Error("dump ws cache fail", zap.Error(err))
}
}()
}
}
func (e *Exchange) GetReplayTo() int64 {
if e.WsNextMS == 0 {
if len(e.WsCache) == 0 {
e.WsCache = make([]*WsLog, 0, e.WsBatchSize)
if err := e.WsDecoder.Decode(&e.WsCache); err != nil {
e.WsNextMS = math.MaxInt64
return e.WsNextMS
}
}
if len(e.WsCache) > 0 {