forked from nntaoli-project/goex
-
Notifications
You must be signed in to change notification settings - Fork 4
/
OKEx_V3.go
1618 lines (1404 loc) · 44.1 KB
/
OKEx_V3.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
package okcoin
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/deckarep/golang-set"
. "github.com/nntaoli-project/GoEx"
)
const (
V3_FUTURE_HOST_URL = "https://www.okex.com/"
V3_FUTURE_API_BASE_URL = "api/futures/v3/"
V3_SWAP_API_BASE_URL = "api/swap/v3/"
V3_FUTRUR_INSTRUMENTS_URL = "instruments"
V3_FUTURE_TICKER_URI = "instruments/%s/ticker"
V3_SWAP_DEPTH_URI = "instruments/%s/depth" //wtf api
V3_FUTURE_DEPTH_URI = "instruments/%s/book" //wtf api
V3_FUTURE_ESTIMATED_PRICE = "instruments/%s/estimated_price"
V3_FUTURE_INDEX_PRICE = "instruments/%s/index"
V3_FUTURE_USERINFOS_URI = "accounts/%s"
V3_FUTURE_CANCEL_URI = "cancel_order/%s/%s"
V3_FUTURE_ORDER_INFO_URI = "orders/%s/%s"
V3_FUTURE_ORDERS_INFO_URI = "orders/%s"
V3_FUTURE_POSITION_URI = "%s/position"
V3_FUTURE_ORDER_URI = "order"
V3_FUTURE_TRADES_URI = "instruments/%s/trades"
V3_FUTURE_FILLS_URI = "fills"
V3_EXCHANGE_RATE_URI = "instruments/%s/rate"
V3_GET_KLINE_URI = "instruments/%s/candles"
)
// common utils, maybe should be extracted in future
func timeStringToInt64(t string) (int64, error) {
timestamp, err := time.Parse(time.RFC3339, t)
if err != nil {
return 0, err
}
return timestamp.UnixNano() / int64(time.Millisecond), nil
}
func int64ToTime(ti int64) time.Time {
return time.Unix(0, ti*int64(time.Millisecond)).UTC()
}
func int64ToTimeString(ti int64) string {
t := int64ToTime(ti)
return t.Format(time.RFC3339)
}
// contract information
type futureContract struct {
InstrumentID string `json:"instrument_id"`
UnderlyingIndex string `json:"underlying_index"`
QuoteCurrency string `json:"quote_currency"`
Coin string `json:"coin"`
TickSize string `json:"tick_size"`
ContractVal string `json:"contract_val"`
Listing string `json:"listing"`
Delivery string `json:"delivery"`
SizeIncrement string `json:"size_increment"`
TradeIncrement string `json:"trade_increment"`
Alias string `json:"alias"`
}
var tail_zero_re = regexp.MustCompile("0+$")
func normalizeByIncrement(num float64, increment string) (string, error) {
precision := 0
i := strings.Index(increment, ".")
// increment is decimal
if i > -1 {
decimal := increment[i+1:]
trimTailZero := tail_zero_re.ReplaceAllString(decimal, "")
precision = len(trimTailZero)
return fmt.Sprintf("%."+fmt.Sprintf("%df", precision), num), nil
}
// increment is int
incrementInt, err := strconv.ParseInt(increment, 10, 64)
if err != nil {
return "", err
}
return strconv.Itoa(int(num) / int(incrementInt)), nil
}
func (fc futureContract) normalizePrice(price float64) (string, error) {
tickSize := fc.TickSize
if len(tickSize) == 0 {
return "", fmt.Errorf("no tick size info in contract %v", fc)
}
return normalizeByIncrement(price, tickSize)
}
func (fc futureContract) normalizePriceString(price string) (string, error) {
p, err := strconv.ParseFloat(price, 64)
if err != nil {
return "", err
}
return fc.normalizePrice(p)
}
func (fc futureContract) getSizeIncrement() string {
if len(fc.SizeIncrement) > 0 {
return fc.SizeIncrement
} else if len(fc.TradeIncrement) > 0 {
return fc.TradeIncrement
}
return ""
}
func (fc futureContract) normalizeAmount(amount float64) (string, error) {
increment := fc.getSizeIncrement()
if len(increment) == 0 {
return "", fmt.Errorf("no trade incrument info in contract %v", fc)
}
return normalizeByIncrement(amount, increment)
}
func (fc futureContract) normalizeAmountString(amount string) (string, error) {
a, err := strconv.ParseFloat(amount, 64)
if err != nil {
return "", err
}
return fc.normalizeAmount(a)
}
type futureContracts []futureContract
type futureContractsMapKey struct {
UnderlyingIndex string
QuoteCurrency string
Alias string
}
type futureContractsMap map[futureContractsMapKey]*futureContract
type futureContractsIDMap map[string]*futureContract
func newFutureContractsMap(contracts futureContracts) futureContractsMap {
contractsMap := futureContractsMap{}
for _, v := range contracts {
func(v futureContract) {
key := futureContractsMapKey{
UnderlyingIndex: v.UnderlyingIndex,
QuoteCurrency: v.QuoteCurrency,
Alias: v.Alias,
}
contractsMap[key] = &v
}(v)
}
return contractsMap
}
func newFutureContractsIDMap(contracts futureContracts) futureContractsIDMap {
contractsIDMap := futureContractsIDMap{}
for _, v := range contracts {
func(v futureContract) {
contractsIDMap[v.InstrumentID] = &v
}(v)
}
return contractsIDMap
}
// NOTE:
// contracts 默认五分钟更新一次。
// 由于V3没有自动合约日期的映射,到了周五交割的时候,最好还是手动平仓,关闭策略,交割完后重启。
type OKExV3 struct {
apiKey,
apiSecretKey,
passphrase,
endpoint string
dataParser *OKExV3DataParser
client *http.Client
contractsMap futureContractsMap
contractsIDMap map[string]*futureContract
contractsRW *sync.RWMutex
}
func NewOKExV3(client *http.Client, api_key, secret_key, passphrase, endpoint string) *OKExV3 {
okv3 := new(OKExV3)
okv3.apiKey = api_key
okv3.apiSecretKey = secret_key
okv3.client = client
okv3.passphrase = passphrase
okv3.contractsRW = &sync.RWMutex{}
okv3.dataParser = NewOKExV3DataParser(okv3)
okv3.endpoint = endpoint
contracts, err := okv3.getAllContracts()
if err != nil {
panic(err)
}
okv3.setContracts(contracts)
return okv3
}
func (okv3 *OKExV3) GetUrlRoot() (url string) {
if okv3.endpoint != "" {
url = okv3.endpoint
} else {
url = V3_FUTURE_HOST_URL
}
if url[len(url)-1] != '/' {
url = url + "/"
}
return
}
func (okv3 *OKExV3) setContracts(contracts futureContracts) {
contractsMap := newFutureContractsMap(contracts)
contractsIDMap := newFutureContractsIDMap(contracts)
okv3.contractsRW.Lock()
defer okv3.contractsRW.Unlock()
okv3.contractsMap = contractsMap
okv3.contractsIDMap = contractsIDMap
}
func (okv3 *OKExV3) getAllContracts() (futureContracts, error) {
var err error
var futureContracts, swapContracts futureContracts
wg := &sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
var err2 error
futureContracts, err2 = okv3.getFutureContracts()
if err2 != nil {
err = err2
}
}()
go func() {
defer wg.Done()
var err2 error
swapContracts, err2 = okv3.getSwapContracts()
if err2 != nil {
err = err2
}
}()
wg.Wait()
if err != nil {
return nil, err
}
return append(futureContracts, swapContracts...), nil
}
func (okv3 *OKExV3) getContractByKey(key futureContractsMapKey) (*futureContract, error) {
okv3.contractsRW.RLock()
defer okv3.contractsRW.RUnlock()
data, ok := okv3.contractsMap[key]
if !ok {
msg := fmt.Sprintf("no contract in okex contracts map for %v", key)
return nil, errors.New(msg)
}
return data, nil
}
func (okv3 *OKExV3) GetContract(currencyPair CurrencyPair, contractType string) (*futureContract, error) {
key := futureContractsMapKey{
UnderlyingIndex: currencyPair.CurrencyA.Symbol,
QuoteCurrency: currencyPair.CurrencyB.Symbol,
Alias: contractType,
}
return okv3.getContractByKey(key)
}
func (okv3 *OKExV3) GetContractID(currencyPair CurrencyPair, contractType string) (string, error) {
fallback := ""
contract, err := okv3.GetContract(currencyPair, contractType)
if err != nil {
return fallback, err
}
return contract.InstrumentID, nil
}
func (okv3 *OKExV3) ParseContractID(contractID string) (CurrencyPair, string, error) {
contract, err := okv3.getContractByID(contractID)
if err != nil {
return UNKNOWN_PAIR, "", err
}
currencyA := NewCurrency(contract.UnderlyingIndex, "")
currencyB := NewCurrency(contract.QuoteCurrency, "")
return NewCurrencyPair(currencyA, currencyB), contract.Alias, nil
}
func (okv3 *OKExV3) getContractByID(instrumentID string) (*futureContract, error) {
okv3.contractsRW.RLock()
defer okv3.contractsRW.RUnlock()
data, ok := okv3.contractsIDMap[instrumentID]
if !ok {
msg := fmt.Sprintf("no contract in okex contracts with id %s", instrumentID)
return nil, errors.New(msg)
}
return data, nil
}
func (okv3 *OKExV3) startUpdateContractsLoop() {
interval := 5 * time.Minute
go func() {
for {
time.Sleep(interval)
contracts, err := okv3.getAllContracts()
if err == nil {
okv3.setContracts(contracts)
}
}
}()
}
func (okv3 *OKExV3) GetExchangeName() string {
return OKEX_FUTURE
}
func (okv3 *OKExV3) getTimestamp() string {
return time.Now().UTC().Format(time.RFC3339)
}
func (okv3 *OKExV3) getSign(timestamp, method, url, body string) (string, error) {
relURL := "/" + strings.TrimPrefix(url, okv3.GetUrlRoot())
data := timestamp + method + relURL + body
return GetParamHmacSHA256Base64Sign(okv3.apiSecretKey, data)
}
func (okv3 *OKExV3) getSignedHTTPHeader(method, url string) (map[string]string, error) {
timestamp := okv3.getTimestamp()
sign, err := okv3.getSign(timestamp, method, url, "")
if err != nil {
return nil, err
}
return map[string]string{
"Content-Type": "application/json",
"OK-ACCESS-KEY": okv3.apiKey,
"OK-ACCESS-SIGN": sign,
"OK-ACCESS-TIMESTAMP": timestamp,
"OK-ACCESS-PASSPHRASE": okv3.passphrase,
}, nil
}
func (okv3 *OKExV3) getSignedHTTPHeader2(method, url, body string) (map[string]string, error) {
timestamp := okv3.getTimestamp()
sign, err := okv3.getSign(timestamp, method, url, body)
if err != nil {
return nil, err
}
return map[string]string{
"Content-Type": "application/json",
"OK-ACCESS-KEY": okv3.apiKey,
"OK-ACCESS-SIGN": sign,
"OK-ACCESS-TIMESTAMP": timestamp,
"OK-ACCESS-PASSPHRASE": okv3.passphrase,
}, nil
}
func (okv3 *OKExV3) getSignedHTTPHeader3(method, url string, postData map[string]string) (map[string]string, error) {
body, _ := json.Marshal(postData)
return okv3.getSignedHTTPHeader2(method, url, string(body))
}
func (okv3 *OKExV3) getSwapContracts() (futureContracts, error) {
url := okv3.GetUrlRoot() + V3_SWAP_API_BASE_URL + V3_FUTRUR_INSTRUMENTS_URL
headers, err := okv3.getSignedHTTPHeader("GET", url)
if err != nil {
return nil, err
}
body, err := HttpGet5(okv3.client, url, headers)
if err != nil {
return nil, err
}
contracts := futureContracts{}
err = json.Unmarshal(body, &contracts)
if err != nil {
return nil, err
}
for i := range contracts {
contracts[i].Alias = SWAP_CONTRACT
}
return contracts, nil
}
func (okv3 *OKExV3) getFutureContracts() (futureContracts, error) {
url := okv3.GetUrlRoot() + V3_FUTURE_API_BASE_URL + V3_FUTRUR_INSTRUMENTS_URL
headers, err := okv3.getSignedHTTPHeader("GET", url)
if err != nil {
return nil, err
}
body, err := HttpGet5(okv3.client, url, headers)
if err != nil {
return nil, err
}
contracts := futureContracts{}
err = json.Unmarshal(body, &contracts)
if err != nil {
return nil, err
}
return contracts, nil
}
func (okv3 *OKExV3) GetFutureDepth(currencyPair CurrencyPair, contractType string, size int) (*Depth, error) {
var url string
if contractType == SWAP_CONTRACT {
url = okv3.GetUrlRoot() + V3_SWAP_API_BASE_URL + V3_SWAP_DEPTH_URI
} else {
url = okv3.GetUrlRoot() + V3_FUTURE_API_BASE_URL + V3_FUTURE_DEPTH_URI
}
contract, err := okv3.GetContract(currencyPair, contractType)
if err != nil {
return nil, err
}
symbol := contract.InstrumentID
url = fmt.Sprintf(url, symbol)
if size > 0 {
url = fmt.Sprintf(url+"?size=%d", size)
}
headers, err := okv3.getSignedHTTPHeader("GET", url)
if err != nil {
return nil, err
}
body, err := HttpGet5(okv3.client, url, headers)
if err != nil {
return nil, err
}
// println(string(body))
bodyMap := make(map[string]interface{})
err = json.Unmarshal(body, &bodyMap)
if err != nil {
return nil, err
}
if bodyMap["code"] != nil {
log.Println(bodyMap)
return nil, errors.New(string(body))
} else if bodyMap["error_code"] != nil {
log.Println(bodyMap)
return nil, errors.New(string(body))
}
depth := new(Depth)
depth.Pair = currencyPair
depth.ContractType = contractType
return okv3.dataParser.ParseDepth(depth, bodyMap, size)
}
func (okv3 *OKExV3) GetFutureTicker(currencyPair CurrencyPair, contractType string) (*Ticker, error) {
var url string
if contractType == SWAP_CONTRACT {
url = okv3.GetUrlRoot() + V3_SWAP_API_BASE_URL + V3_FUTURE_TICKER_URI
} else {
url = okv3.GetUrlRoot() + V3_FUTURE_API_BASE_URL + V3_FUTURE_TICKER_URI
}
contract, err := okv3.GetContract(currencyPair, contractType)
if err != nil {
return nil, err
}
symbol := contract.InstrumentID
url = fmt.Sprintf(url, symbol)
headers, err := okv3.getSignedHTTPHeader("GET", url)
if err != nil {
return nil, err
}
body, err := HttpGet5(okv3.client, url, headers)
if err != nil {
return nil, err
}
//println(string(body))
bodyMap := make(map[string]interface{})
err = json.Unmarshal(body, &bodyMap)
if err != nil {
return nil, err
}
if bodyMap["code"] != nil {
log.Println(bodyMap)
return nil, errors.New(string(body))
} else if bodyMap["error_code"] != nil {
log.Println(bodyMap)
return nil, errors.New(string(body))
}
ticker := new(Ticker)
ticker.Pair = currencyPair
timestamp, _ := timeStringToInt64(bodyMap["timestamp"].(string))
ticker.Date = uint64(timestamp)
ticker.Buy, _ = strconv.ParseFloat(bodyMap["best_ask"].(string), 64)
ticker.Sell, _ = strconv.ParseFloat(bodyMap["best_bid"].(string), 64)
ticker.Last, _ = strconv.ParseFloat(bodyMap["last"].(string), 64)
ticker.High, _ = strconv.ParseFloat(bodyMap["high_24h"].(string), 64)
ticker.Low, _ = strconv.ParseFloat(bodyMap["low_24h"].(string), 64)
ticker.Vol, _ = strconv.ParseFloat(bodyMap["volume_24h"].(string), 64)
//fmt.Println(bodyMap)
return ticker, nil
}
func (okv3 *OKExV3) PlaceFutureOrder(currencyPair CurrencyPair, contractType, price, amount string, openType, matchPrice, leverRate int) (string, error) {
var requestURL string
if contractType == SWAP_CONTRACT {
requestURL = okv3.GetUrlRoot() + V3_SWAP_API_BASE_URL + V3_FUTURE_ORDER_URI
} else {
requestURL = okv3.GetUrlRoot() + V3_FUTURE_API_BASE_URL + V3_FUTURE_ORDER_URI
}
contract, err := okv3.GetContract(currencyPair, contractType)
if err != nil {
return "", err
}
symbol := contract.InstrumentID
price, err = contract.normalizePriceString(price)
if err != nil {
return "", err
}
amount, err = contract.normalizeAmountString(amount)
if err != nil {
return "", err
}
postData := make(map[string]string)
postData["instrument_id"] = symbol
postData["price"] = price
postData["size"] = amount
postData["type"] = strconv.Itoa(openType)
// postData["order_type"] = strconv.Itoa(2)
if contractType != SWAP_CONTRACT {
postData["leverage"] = strconv.Itoa(leverRate)
}
postData["match_price"] = strconv.Itoa(matchPrice)
headers, err := okv3.getSignedHTTPHeader3("POST", requestURL, postData)
if err != nil {
return "", err
}
body, err := HttpPostForm4(okv3.client, requestURL, postData, headers)
if err != nil {
return "", err
}
respMap := make(map[string]interface{})
err = json.Unmarshal(body, &respMap)
if err != nil {
return "", err
}
//println(string(body));
if respMap["error_code"] != nil {
errorCode, err := strconv.Atoi(respMap["error_code"].(string))
if err != nil || errorCode != 0 {
return "", errors.New(string(body))
}
}
return respMap["order_id"].(string), nil
}
func (okv3 *OKExV3) FutureCancelOrder(currencyPair CurrencyPair, contractType, orderID string) (bool, error) {
var requestURL string
if contractType == SWAP_CONTRACT {
requestURL = okv3.GetUrlRoot() + V3_SWAP_API_BASE_URL + V3_FUTURE_CANCEL_URI
} else {
requestURL = okv3.GetUrlRoot() + V3_FUTURE_API_BASE_URL + V3_FUTURE_CANCEL_URI
}
contract, err := okv3.GetContract(currencyPair, contractType)
if err != nil {
return false, err
}
symbol := contract.InstrumentID
requestURL = fmt.Sprintf(requestURL, symbol, orderID)
headers, err := okv3.getSignedHTTPHeader("POST", requestURL)
if err != nil {
return false, err
}
body, err := HttpPostForm3(okv3.client, requestURL, "", headers)
if err != nil {
return false, err
}
respMap := make(map[string]interface{})
err = json.Unmarshal(body, &respMap)
if err != nil {
return false, err
}
//println(string(body));
if respMap["error_code"] != nil {
errorCode, err := strconv.Atoi(respMap["error_code"].(string))
if err != nil || errorCode != 0 {
return false, errors.New(string(body))
}
}
// wtf api
switch v := respMap["result"].(type) {
case bool:
return v, nil
case string:
b, err := strconv.ParseBool(v)
return b, err
default:
return false, errors.New(string(body))
}
}
func (okv3 *OKExV3) parseOrder(respMap map[string]interface{}, currencyPair CurrencyPair, contractType string) (*FutureOrder, error) {
order, _, err := okv3.dataParser.ParseFutureOrder(respMap)
return order, err
}
func (okv3 *OKExV3) parseOrders(body []byte, currencyPair CurrencyPair, contractType string) ([]FutureOrder, error) {
respMap := make(map[string]interface{})
err := json.Unmarshal(body, &respMap)
if err != nil {
return nil, err
}
var result bool
if respMap["result"] != nil {
switch v := respMap["result"].(type) {
case bool:
result = v
case string:
b, err := strconv.ParseBool(v)
if err != nil {
b = false
}
result = b
default:
result = false
}
} else {
result = true // no result field, should look at order_info field
}
//{"error_message": "You have not uncompleted order at the moment",
// "result": false, "error_code": "32004", "order_id": "2924351754742784"}
if !result && respMap["error_code"] != nil {
log.Println(respMap["error_code"].(string))
if respMap["error_code"].(string) == "32004" {
return []FutureOrder{}, nil
}
}
if result && respMap["order_info"] != nil {
orderInfos := respMap["order_info"].([]interface{})
orders := make([]FutureOrder, 0, len(orderInfos))
for _, o := range orderInfos {
orderInfo := o.(map[string]interface{})
order, err := okv3.parseOrder(orderInfo, currencyPair, contractType)
if err != nil {
return nil, err
}
orders = append(orders, *order)
}
return orders, nil
}
return nil, errors.New(string(body))
}
func (okv3 *OKExV3) GetFutureOrder(orderID string, currencyPair CurrencyPair, contractType string) (*FutureOrder, error) {
var requestURL string
if contractType == SWAP_CONTRACT {
requestURL = okv3.GetUrlRoot() + V3_SWAP_API_BASE_URL + V3_FUTURE_ORDER_INFO_URI
} else {
requestURL = okv3.GetUrlRoot() + V3_FUTURE_API_BASE_URL + V3_FUTURE_ORDER_INFO_URI
}
contract, err := okv3.GetContract(currencyPair, contractType)
if err != nil {
return nil, err
}
symbol := contract.InstrumentID
requestURL = fmt.Sprintf(requestURL, symbol, orderID)
headers, err := okv3.getSignedHTTPHeader("GET", requestURL)
if err != nil {
return nil, err
}
body, err := HttpGet5(okv3.client, requestURL, headers)
if err != nil {
return nil, err
}
respMap := make(map[string]interface{})
err = json.Unmarshal(body, &respMap)
if err != nil {
return nil, err
}
//println(string(body));
if respMap["error_code"] != nil {
errorCode, err := strconv.Atoi(respMap["error_code"].(string))
if err != nil || errorCode != 0 {
return nil, errors.New(string(body))
}
}
return okv3.parseOrder(respMap, currencyPair, contractType)
}
var orderStateOrder = map[TradeStatus]int{
ORDER_UNFINISH: 0,
ORDER_PART_FINISH: 1,
ORDER_REJECT: 2,
ORDER_CANCEL_ING: 3,
ORDER_CANCEL: 4,
ORDER_FINISH: 5,
}
func (okv3 *OKExV3) mergeOrders(ordersList ...[]FutureOrder) []FutureOrder {
orderMap := make(map[string]FutureOrder)
for _, orders := range ordersList {
if orders != nil {
for _, order := range orders {
if o, ok := orderMap[order.OrderID2]; ok {
if orderStateOrder[o.Status] < orderStateOrder[order.Status] {
orderMap[order.OrderID2] = order
}
} else {
orderMap[order.OrderID2] = order
}
}
}
}
orders := make([]FutureOrder, 0, len(orderMap))
for _, value := range orderMap {
orders = append(orders, value)
}
return orders
}
func (okv3 *OKExV3) GetFutureOrders(orderIds []string, currencyPair CurrencyPair, contractType string) ([]FutureOrder, error) {
var err error
var orders1, orders2, orders3 []FutureOrder
// TODO: when cancelling orders via api which query orders, order maybe not valiable in all the state,
// api which query single order is more stable, so when orderIDs's length is less than 3~5,
// just using query sigle order api.
wg := &sync.WaitGroup{}
wg.Add(3)
go func() {
defer wg.Done()
var _err error
orders2, _err = okv3.GetUnfinishFutureOrdersByIDs(orderIds, currencyPair, contractType)
if _err != nil {
err = _err
}
}()
// cancelling orders
go func() {
defer wg.Done()
var _err error
orders3, _err = okv3.GetFutureOrdersByIDsAndState(orderIds, "4", currencyPair, contractType)
if _err != nil {
err = _err
}
}()
go func() {
defer wg.Done()
var _err error
orders1, _err = okv3.GetFinishedFutureOrdersByIDs(orderIds, currencyPair, contractType)
if _err != nil {
err = _err
}
}()
wg.Wait()
if err != nil {
return nil, err
}
return okv3.mergeOrders(orders1, orders2, orders3), nil
}
func (okv3 *OKExV3) filterOrdersByIDs(orderIDs []string, orders []FutureOrder) []FutureOrder {
//if no orderIDs specific, return all the orders
if len(orderIDs) == 0 {
return orders
}
orderSet := mapset.NewSet()
for _, o := range orderIDs {
orderSet.Add(o)
}
newOrders := make([]FutureOrder, 0, len(orderIDs))
for _, order := range orders {
if orderSet.Contains(order.OrderID2) {
newOrders = append(newOrders, order)
}
}
return newOrders
}
func (okv3 *OKExV3) GetFutureOrdersByIDsAndState(orderIDs []string, state string, currencyPair CurrencyPair, contractType string) ([]FutureOrder, error) {
var requestURL string
if contractType == SWAP_CONTRACT {
requestURL = okv3.GetUrlRoot() + V3_SWAP_API_BASE_URL + V3_FUTURE_ORDERS_INFO_URI
} else {
requestURL = okv3.GetUrlRoot() + V3_FUTURE_API_BASE_URL + V3_FUTURE_ORDERS_INFO_URI
}
postData := url.Values{}
if len(orderIDs) > 0 {
sort.Strings(orderIDs)
if contractType == SWAP_CONTRACT {
// 设计api像cxk, from 参数对应的订单竟然不包含在查询结果中
to, _ := strconv.ParseInt(orderIDs[0], 10, 64)
// to = to - 1
postData.Set("to", fmt.Sprintf("%d", to))
// from, _ := strconv.ParseInt(orderIDs[len(orderIDs) - 1], 10, 64)
// from = from + 1
// postData.Set("from", fmt.Sprintf("%d", from))
} else {
before, _ := strconv.ParseInt(orderIDs[0], 10, 64)
before = before - 1
postData.Set("before", fmt.Sprintf("%d", before))
after, _ := strconv.ParseInt(orderIDs[len(orderIDs)-1], 10, 64)
after = after + 1
postData.Set("after", fmt.Sprintf("%d", after))
}
}
postData.Set("state", state)
contract, err := okv3.GetContract(currencyPair, contractType)
if err != nil {
return nil, err
}
symbol := contract.InstrumentID
requestURL = fmt.Sprintf(requestURL, symbol) + "?" + postData.Encode()
headers, err := okv3.getSignedHTTPHeader("GET", requestURL)
if err != nil {
return nil, err
}
body, err := HttpGet5(okv3.client, requestURL, headers)
if err != nil {
return nil, err
}
orders, err := okv3.parseOrders(body, currencyPair, contractType)
if err != nil {
return nil, err
}
return okv3.filterOrdersByIDs(orderIDs, orders), nil
}
func (okv3 *OKExV3) GetUnfinishFutureOrdersByIDs(orderIDs []string, currencyPair CurrencyPair, contractType string) ([]FutureOrder, error) {
return okv3.GetFutureOrdersByIDsAndState(orderIDs, "6", currencyPair, contractType)
}
func (okv3 *OKExV3) GetUnfinishFutureOrders(currencyPair CurrencyPair, contractType string) ([]FutureOrder, error) {
return okv3.GetUnfinishFutureOrdersByIDs([]string{}, currencyPair, contractType)
}
func (okv3 *OKExV3) GetFutureOrdersByState(state string, currencyPair CurrencyPair, contractType string) ([]FutureOrder, error) {
return okv3.GetFutureOrdersByIDsAndState([]string{}, state, currencyPair, contractType)
}
func (okv3 *OKExV3) GetFinishedFutureOrdersByIDs(orderIDs []string, currencyPair CurrencyPair, contractType string) ([]FutureOrder, error) {
return okv3.GetFutureOrdersByIDsAndState(orderIDs, "7", currencyPair, contractType)
}
func (okv3 *OKExV3) GetFinishedFutureOrders(currencyPair CurrencyPair, contractType string) ([]FutureOrder, error) {
return okv3.GetFinishedFutureOrdersByIDs([]string{}, currencyPair, contractType)
}
var OKexOrderTypeMap = map[int]int{
ORDER_TYPE_LIMIT: 0,
ORDER_TYPE_POST_ONLY: 1,
ORDER_TYPE_FOK: 2,
ORDER_TYPE_FAK: 3,
}
func (okv3 *OKExV3) PlaceFutureOrder2(currencyPair CurrencyPair, contractType, price, amount string, orderType, openType, matchPrice, leverRate int) (string, error) {
var requestURL string
if contractType == SWAP_CONTRACT {
requestURL = okv3.GetUrlRoot() + V3_SWAP_API_BASE_URL + V3_FUTURE_ORDER_URI
} else {
requestURL = okv3.GetUrlRoot() + V3_FUTURE_API_BASE_URL + V3_FUTURE_ORDER_URI
}
contract, err := okv3.GetContract(currencyPair, contractType)
if err != nil {
return "", err
}
symbol := contract.InstrumentID
price, err = contract.normalizePriceString(price)
if err != nil {
return "", err
}
amount, err = contract.normalizeAmountString(amount)
if err != nil {
return "", err
}
postData := make(map[string]string)
postData["instrument_id"] = symbol
postData["price"] = price
postData["size"] = amount
postData["type"] = strconv.Itoa(openType)
if ot, ok := OKexOrderTypeMap[orderType]; ok {
postData["order_type"] = strconv.Itoa(ot)
} else {
return "", fmt.Errorf("unsupport order type %s in %s", OrderType(ot).String(), okv3.GetExchangeName())
}
if contractType != SWAP_CONTRACT {
postData["leverage"] = strconv.Itoa(leverRate)
}
postData["match_price"] = strconv.Itoa(matchPrice)
headers, err := okv3.getSignedHTTPHeader3("POST", requestURL, postData)
if err != nil {
return "", err
}
body, err := HttpPostForm4(okv3.client, requestURL, postData, headers)
if err != nil {
return "", err
}
respMap := make(map[string]interface{})
err = json.Unmarshal(body, &respMap)
if err != nil {
return "", err
}
//println(string(body));
if respMap["error_code"] != nil {
errorCode, err := strconv.Atoi(respMap["error_code"].(string))
if err != nil || errorCode != 0 {
return "", errors.New(string(body))
}
}
return respMap["order_id"].(string), nil
}
func (okv3 *OKExV3) GetDeliveryTime() (int, int, int, int) {
return 4, 16, 0, 0
}
func (okv3 *OKExV3) GetContractValue(currencyPair CurrencyPair) (float64, error) {
// seems contractType should be one of the function parameters.
contractType := QUARTER_CONTRACT
contract, err := okv3.GetContract(currencyPair, contractType)
if err != nil {
return -1, err
}
f, err := strconv.ParseFloat(contract.ContractVal, 64)
if err != nil {
return -1, err
}
return f, nil
}