-
Notifications
You must be signed in to change notification settings - Fork 789
/
okcoin.go
1762 lines (1666 loc) · 66.8 KB
/
okcoin.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 (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/crypto"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/account"
"github.com/thrasher-corp/gocryptotrader/exchanges/kline"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
const (
apiPath = "/api/"
okcoinAPIURL = "https://www.okcoin.com"
okcoinAPIVersion = apiPath + "v5/"
okcoinExchangeName = "Okcoin"
okcoinWebsocketURL = "wss://real.okcoin.com:8443/ws/v5/public"
okcoinPrivateWebsocketURL = "wss://real.okcoin.com:8443/ws/v5/private"
)
// Okcoin is the overarching type used for Okcoin's exchange API implementation
type Okcoin struct {
exchange.Base
// Spot and contract market error codes
ErrorCodes map[string]error
}
var (
errNilArgument = errors.New("nil argument")
errInvalidAmount = errors.New("invalid amount value")
errInvalidPrice = errors.New("invalid price value")
errAddressMustNotBeEmptyString = errors.New("address must be a non-empty string")
errSubAccountNameRequired = errors.New("sub-account name is required")
errNoValidResponseFromServer = errors.New("no valid response")
errTransferIDOrClientIDRequired = errors.New("either transfer id or client id is required")
errInvalidWithdrawalMethod = errors.New("withdrawal method must be specified")
errInvalidTransactionFeeValue = errors.New("invalid transaction fee value")
errWithdrawalIDMissing = errors.New("withdrawal id is missing")
errTradeModeIsRequired = errors.New("trade mode is required")
errInstrumentTypeMissing = errors.New("instrument type is required")
errChannelIDRequired = errors.New("channel id is required")
errBankAccountNumberIsRequired = errors.New("bank account number is required")
errMissingInstrumentID = errors.New("missing instrument id")
errAlgoIDRequired = errors.New("algo ID is required")
errNoOrderbookData = errors.New("no orderbook data found")
errOrderIDOrClientOrderIDRequired = errors.New("order id or client order id is required")
errSizeOrPriceRequired = errors.New("valid size or price has to be specified")
errPriceRatioOrPriceSpreadRequired = errors.New("either price ratio or price variance is required")
errSizeLimitRequired = errors.New("size limit is required")
errPriceLimitRequired = errors.New("price limit is required")
errStopLossOrTakeProfitOrderPriceRequired = errors.New("either parameter 'stop loss order price' or 'take profit order price' is required")
errStopLossTriggerPriceRequired = errors.New("stop-loss-order-price is required")
errTakeProfitOrderPriceRequired = errors.New("tp-order-price is required")
errTpTriggerOrderPriceTypeRequired = errors.New("'take-profit-order-price-type' is required")
errStopLossTriggerPriceTypeRequired = errors.New("'stop-loss-trigger-price' is required")
errCallbackRatioOrCallbackSpeedRequired = errors.New("either Callback ration or callback spread is required")
errTimeIntervalInformationRequired = errors.New("time interval information is required")
errOrderTypeRequired = errors.New("order type is required")
errNoAccountDepositAddress = errors.New("no account deposit address")
errQuoteIDRequired = errors.New("quote id is required")
errClientRequestIDRequired = errors.New("client supplied request ID is required")
)
const (
// endpoint types
typeAccounts = "account"
typeFiat = "fiat"
typeOtc = "otc"
typeAssets = "asset"
typeMarket = "market"
typePublic = "public"
typeSystem = "system"
typeTrade = "trade"
typeUser = "users"
)
// GetInstruments Get market data. This endpoint provides the snapshots of market data and can be used without verifications.
// List trading pairs and get the trading limit, price, and more information of different trading pairs.
func (o *Okcoin) GetInstruments(ctx context.Context, instrumentType, instrumentID string) ([]Instrument, error) {
params := url.Values{}
if instrumentType == "" {
return nil, errInstrumentTypeMissing
}
params.Set("instType", instrumentType)
if instrumentID != "" {
params.Set("instId", instrumentID)
}
var resp []Instrument
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getInstrumentsEPL, http.MethodGet, typePublic, common.EncodeURLValues("instruments", params), nil, &resp, false)
}
// GetSystemStatus system maintenance status,scheduled: waiting; ongoing: processing; pre_open: pre_open; completed: completed ;canceled: canceled.
// Generally, pre_open last about 10 minutes. There will be pre_open when the time of upgrade is too long.
// If this parameter is not filled, the data with status scheduled, ongoing and pre_open will be returned by default
func (o *Okcoin) GetSystemStatus(ctx context.Context, state string) ([]SystemStatus, error) {
params := url.Values{}
if state != "" {
params.Set("state", state)
}
var resp []SystemStatus
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getSystemStatusEPL, http.MethodGet, typeSystem, common.EncodeURLValues("status", params), nil, &resp, false)
}
// GetSystemTime retrieve API server time.
func (o *Okcoin) GetSystemTime(ctx context.Context) (time.Time, error) {
timestampResponse := []struct {
Timestamp okcoinTime `json:"ts"`
}{}
err := o.SendHTTPRequest(ctx, exchange.RestSpot, getSystemTimeEPL, http.MethodGet, typePublic, "time", nil, ×tampResponse, false)
if err != nil {
return time.Time{}, err
}
return timestampResponse[0].Timestamp.Time(), nil
}
// GetTickers retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours.
func (o *Okcoin) GetTickers(ctx context.Context, instrumentType string) ([]TickerData, error) {
params := url.Values{}
if instrumentType == "" {
return nil, errInstrumentTypeMissing
}
params.Set("instType", instrumentType)
var resp []TickerData
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getTickersEPL, http.MethodGet, typeMarket, common.EncodeURLValues("tickers", params), nil, &resp, false)
}
// GetTicker retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours.
func (o *Okcoin) GetTicker(ctx context.Context, instrumentID string) (*TickerData, error) {
if instrumentID == "" {
return nil, errMissingInstrumentID
}
var resp []TickerData
err := o.SendHTTPRequest(ctx, exchange.RestSpot, getTickerEPL, http.MethodGet, typeMarket, "ticker"+"?instId="+instrumentID, nil, &resp, false)
if err != nil {
return nil, err
} else if len(resp) == 0 {
return nil, errors.New("instrument not found")
}
return &resp[0], nil
}
// GetOrderbook retrieve order book of the instrument.
func (o *Okcoin) GetOrderbook(ctx context.Context, instrumentID string, sideDepth int64) (*GetOrderBookResponse, error) {
if instrumentID == "" {
return nil, errMissingInstrumentID
}
params := url.Values{}
params.Set("instId", instrumentID)
if sideDepth > 0 {
params.Set("sz", strconv.FormatInt(sideDepth, 10))
}
var resp []GetOrderBookResponse
err := o.SendHTTPRequest(ctx, exchange.RestSpot, getOrderbookEPL, http.MethodGet, typeMarket, common.EncodeURLValues("books", params), nil, &resp, false)
if err != nil {
return nil, err
} else if len(resp) == 0 {
return nil, fmt.Errorf("%w for instrument %s", errNoOrderbookData, instrumentID)
}
return &resp[0], nil
}
// GetCandlesticks retrieve the candlestick charts. This endpoint can retrieve the latest 1,440 data entries. Charts are returned in groups based on the requested bar.
func (o *Okcoin) GetCandlesticks(ctx context.Context, instrumentID string, interval kline.Interval, after, before time.Time, limit int64, utcOpeningPrice bool) ([]CandlestickData, error) {
if instrumentID == "" {
return nil, errMissingInstrumentID
}
params := url.Values{}
params.Set("instId", instrumentID)
var err error
if interval != kline.Interval(0) {
var intervalString string
intervalString, err = intervalToString(interval, utcOpeningPrice)
if err != nil {
return nil, err
}
params.Set("bar", intervalString)
}
if !after.IsZero() {
params.Set("after", strconv.FormatInt(after.UnixMilli(), 10))
}
if !before.IsZero() {
params.Set("before", strconv.FormatInt(before.UnixMilli(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var resp []candlestickItemResponse
err = o.SendHTTPRequest(ctx, exchange.RestSpot, getCandlesticksEPL, http.MethodGet, typeMarket, common.EncodeURLValues("candles", params), nil, &resp, false)
if err != nil {
return nil, err
}
return ExtractCandlesticks(resp)
}
// GetCandlestickHistory retrieve history candlestick charts from recent years.
func (o *Okcoin) GetCandlestickHistory(ctx context.Context, instrumentID string, start, end time.Time, bar kline.Interval, limit int64) ([]CandlestickData, error) {
if instrumentID == "" {
return nil, errMissingInstrumentID
}
params := url.Values{}
params.Set("instId", instrumentID)
var err error
if bar != kline.Interval(0) {
var intervalString string
intervalString, err = intervalToString(bar, true)
if err != nil {
return nil, err
}
params.Set("bar", intervalString)
}
if !start.IsZero() {
params.Set("start", strconv.FormatInt(start.UnixNano(), 10))
}
if !end.IsZero() {
params.Set("end", strconv.FormatInt(end.UnixNano(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var resp []candlestickItemResponse
err = o.SendHTTPRequest(ctx, exchange.RestSpot, getCandlestickHistoryEPL, http.MethodGet, typeMarket, common.EncodeURLValues("history-candles", params), nil, &resp, false)
if err != nil {
return nil, err
}
return ExtractCandlesticks(resp)
}
// GetTrades retrieve the recent transactions of an instrument.
func (o *Okcoin) GetTrades(ctx context.Context, instrumentID string, limit int64) ([]SpotTrade, error) {
if instrumentID == "" {
return nil, errMissingInstrumentID
}
params := url.Values{}
params.Set("instId", instrumentID)
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var resp []SpotTrade
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getPublicTradesEPL, http.MethodGet, typeMarket, common.EncodeURLValues("trades", params), nil, &resp, false)
}
// GetTradeHistory retrieve the recent transactions of an instrument from the last 3 months with pagination.
func (o *Okcoin) GetTradeHistory(ctx context.Context, instrumentID, paginationType string, before, after time.Time, limit int64) ([]SpotTrade, error) {
if instrumentID == "" {
return nil, errMissingInstrumentID
}
params := url.Values{}
params.Set("instId", instrumentID)
if paginationType != "" {
params.Set("type", paginationType)
}
if !after.IsZero() {
params.Set("after", strconv.FormatInt(after.UnixMilli(), 10))
}
if !before.IsZero() {
params.Set("before", strconv.FormatInt(before.UnixMilli(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var resp []SpotTrade
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getPublicTradeHistroryEPL, http.MethodGet, typeMarket, common.EncodeURLValues("history-trades", params), nil, &resp, false)
}
// Get24HourTradingVolume returns the 24-hour trading volume is calculated on a rolling basis, using USD as the pricing unit.
func (o *Okcoin) Get24HourTradingVolume(ctx context.Context) ([]TradingVolume, error) {
var resp []TradingVolume
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, get24HourTradingVolumeEPL, http.MethodGet, typeMarket, "platform-24-volume", nil, &resp, false)
}
// GetOracle retrieves the crypto price of signing using Open Oracle smart contract.
func (o *Okcoin) GetOracle(ctx context.Context) (*Oracle, error) {
var resp *Oracle
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getOracleEPL, http.MethodGet, typeMarket, "open-oracle", nil, &resp, false)
}
// GetExchangeRate provides the average exchange rate data for 2 weeks
func (o *Okcoin) GetExchangeRate(ctx context.Context) ([]ExchangeRate, error) {
var resp []ExchangeRate
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getExchangeRateEPL, http.MethodGet, typeMarket, "exchange-rate", nil, &resp, false)
}
func intervalToString(interval kline.Interval, utcOpeningPrice bool) (string, error) {
intervalMap := map[kline.Interval]string{
kline.OneMin: "1m",
kline.ThreeMin: "3m",
kline.FiveMin: "5m",
kline.FifteenMin: "15m",
kline.ThirtyMin: "30m",
kline.OneHour: "1H",
kline.TwoHour: "2H",
kline.FourHour: "4H",
kline.SixHour: "6H",
kline.TwelveHour: "12H",
kline.OneDay: "1D",
kline.TwoDay: "2D",
kline.ThreeDay: "3D",
kline.OneWeek: "1W",
kline.OneMonth: "1M",
kline.ThreeMonth: "3M",
}
str, ok := intervalMap[interval]
if !ok {
return "", kline.ErrUnsupportedInterval
}
if utcOpeningPrice && (interval == kline.SixHour ||
interval == kline.TwelveHour ||
interval == kline.OneDay ||
interval == kline.TwoDay ||
interval == kline.ThreeDay ||
interval == kline.OneWeek ||
interval == kline.OneMonth ||
interval == kline.ThreeMonth) {
str += "utc"
}
return str, nil
}
// ------------ Funding endpoints --------------------------------
// GetCurrencies retrieves all list of currencies
func (o *Okcoin) GetCurrencies(ctx context.Context, ccy currency.Code) ([]CurrencyInfo, error) {
params := url.Values{}
if !ccy.IsEmpty() {
params.Set("ccy", ccy.Upper().String())
}
var resp []CurrencyInfo
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getFundingCurrenciesEPL, http.MethodGet, typeAssets, common.EncodeURLValues("currencies", params), nil, &resp, true)
}
// GetBalance retrieve the funding account balances of all the assets and the amount that is available or on hold.
func (o *Okcoin) GetBalance(ctx context.Context, ccy currency.Code) ([]CurrencyBalance, error) {
params := url.Values{}
if !ccy.IsEmpty() {
params.Set("ccy", ccy.String())
}
var resp []CurrencyBalance
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getFundingAccountBalanceEPL, http.MethodGet, typeAssets, common.EncodeURLValues("balances", params), nil, &resp, true)
}
// GetAccountAssetValuation view account asset valuation
func (o *Okcoin) GetAccountAssetValuation(ctx context.Context, ccy currency.Code) ([]AccountAssetValuation, error) {
params := url.Values{}
if !ccy.IsEmpty() {
params.Set("ccy", ccy.String())
}
var resp []AccountAssetValuation
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getAccountAssetValuationEPL, http.MethodGet, typeAssets, common.EncodeURLValues("asset-valuation", params), nil, &resp, true)
}
// FundsTransfer transfer of funds between your funding account and trading account, and from the master account to sub-accounts.
func (o *Okcoin) FundsTransfer(ctx context.Context, arg *FundingTransferRequest) (*FundingTransferItem, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.Currency.IsEmpty() {
return nil, currency.ErrCurrencyCodeEmpty
}
if arg.Amount <= 0 {
return nil, fmt.Errorf("%w %f", errInvalidAmount, arg.Amount)
}
if arg.From == "" {
return nil, fmt.Errorf("%w, 'from' address", errAddressMustNotBeEmptyString)
}
if arg.To == "" {
return nil, fmt.Errorf("%w, 'to' address", errAddressMustNotBeEmptyString)
}
if arg.TransferType == 1 || arg.TransferType == 2 && arg.SubAccount == "" {
return nil, fmt.Errorf("for transfer type is 1 or 2, %w", errSubAccountNameRequired)
}
var resp []FundingTransferItem
err := o.SendHTTPRequest(ctx, exchange.RestSpot, fundingTransferEPL, http.MethodPost, typeAssets, "transfer", arg, &resp, true)
if err != nil {
return nil, err
}
if len(resp) == 0 {
return nil, errNoValidResponseFromServer
}
return &resp[0], nil
}
// GetFundsTransferState retrieve the transfer state data of the last 2 weeks.
func (o *Okcoin) GetFundsTransferState(ctx context.Context, transferID, clientID, transferType string) ([]FundingTransferItem, error) {
params := url.Values{}
if transferID == "" && clientID == "" {
return nil, errTransferIDOrClientIDRequired
}
if transferID != "" {
params.Set("transId", transferID)
}
if clientID != "" {
params.Set("clientId", clientID)
}
if transferType != "" {
params.Set("type", transferType)
}
var resp []FundingTransferItem
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getFundsTransferStateEPL, http.MethodGet, typeAssets, common.EncodeURLValues("transfer-state", params), nil, &resp, true)
}
// GetAssetBillsDetail query the billing record. You can get the latest 1 month historical data.
// Bill type 1: Deposit 2: Withdrawal 13: Canceled withdrawal 20: Transfer to sub account 21: Transfer from sub account
// 22: Transfer out from sub to master account 23: Transfer in from master to sub account 37: Transfer to spot 38: Transfer from spot
func (o *Okcoin) GetAssetBillsDetail(ctx context.Context, ccy currency.Code, billType, clientSuppliedID string, before, after time.Time, limit int64) ([]AssetBillDetail, error) {
params := url.Values{}
if !ccy.IsEmpty() {
params.Set("ccy", ccy.String())
}
if billType != "" {
params.Set("type", billType)
}
if clientSuppliedID != "" {
params.Set("clientId", clientSuppliedID)
}
if !after.IsZero() {
params.Set("after", strconv.FormatInt(after.UnixMilli(), 10))
}
if !before.IsZero() && after.Before(before) {
params.Set("before", strconv.FormatInt(before.UnixMilli(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var resp []AssetBillDetail
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, assetBillsDetailEPL, http.MethodGet, typeAssets, common.EncodeURLValues("bills", params), nil, &resp, true)
}
// GetLightningDeposits retrieves lightning deposit instances
func (o *Okcoin) GetLightningDeposits(ctx context.Context, ccy currency.Code, amount float64, to string) ([]LightningDepositDetail, error) {
params := url.Values{}
if ccy.IsEmpty() {
return nil, currency.ErrCurrencyCodeEmpty
}
params.Set("ccy", ccy.String())
if amount < 0.000001 || amount > 0.1 {
return nil, fmt.Errorf("%w, deposit amount must be between 0.000001 - 0.1", errInvalidAmount)
}
params.Set("amt", strconv.FormatFloat(amount, 'f', -1, 64))
if to != "" {
params.Set("to", to)
}
var resp []LightningDepositDetail
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, lightningDepositsEPL, http.MethodGet, typeAssets, common.EncodeURLValues("deposit-lightning", params), nil, &resp, true)
}
// GetCurrencyDepositAddresses retrieve the deposit addresses of currencies, including previously-used addresses.
func (o *Okcoin) GetCurrencyDepositAddresses(ctx context.Context, ccy currency.Code) ([]DepositAddress, error) {
params := url.Values{}
if ccy.IsEmpty() {
return nil, currency.ErrCurrencyCodeEmpty
}
params.Set("ccy", ccy.String())
var resp []DepositAddress
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getAssetDepositAddressEPL, http.MethodGet, typeAssets, common.EncodeURLValues("deposit-address", params), nil, &resp, true)
}
// GetDepositHistory retrieve the deposit records according to the currency, deposit status, and time range in reverse chronological order. The 100 most recent records are returned by default.
func (o *Okcoin) GetDepositHistory(ctx context.Context, ccy currency.Code, depositID, transactionID, depositType, state string, after, before time.Time, limit int64) ([]DepositHistoryItem, error) {
params := url.Values{}
if !ccy.IsEmpty() {
params.Set("ccy", ccy.String())
}
if depositID != "" {
params.Set("depId", depositID)
}
if transactionID != "" {
params.Set("txId", transactionID)
}
if depositType != "" {
params.Set("type", depositType)
}
if state != "" {
params.Set("state", state)
}
if !after.IsZero() {
params.Set("after", strconv.FormatInt(after.UnixMilli(), 10))
}
if !before.IsZero() && after.Before(before) {
params.Set("before", strconv.FormatInt(before.UnixMilli(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var resp []DepositHistoryItem
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getDepositHistoryEPL, http.MethodGet, typeAssets, common.EncodeURLValues("deposit-history", params), nil, &resp, true)
}
// Withdrawal apply withdrawal of tokens. Sub-account does not support withdrawal.
// Withdrawal method
// 3: 'internal' using email, phone or login account name.
// 4: 'on chain' a trusted crypto currency address.
func (o *Okcoin) Withdrawal(ctx context.Context, arg *WithdrawalRequest) ([]WithdrawalResponse, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.Ccy.IsEmpty() {
return nil, currency.ErrCurrencyCodeEmpty
}
if arg.Amount <= 0 {
return nil, fmt.Errorf("%w %f", errInvalidAmount, arg.Amount)
}
if arg.WithdrawalMethod == "" {
return nil, errInvalidWithdrawalMethod
}
if arg.ToAddress == "" {
return nil, fmt.Errorf("%w, 'toAddr' address", errAddressMustNotBeEmptyString)
}
if arg.TransactionFee < 0 {
return nil, fmt.Errorf("%w, transaction fee: %f", errInvalidTransactionFeeValue, arg.TransactionFee)
}
var resp []WithdrawalResponse
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, postWithdrawalEPL, http.MethodPost, typeAssets, "withdrawal", arg, &resp, true)
}
// SubmitLightningWithdrawals the maximum withdrawal amount is 0.1 BTC per request, and 1 BTC in 24 hours.
// The minimum withdrawal amount is approximately 0.000001 BTC. Sub-account does not support withdrawal.
func (o *Okcoin) SubmitLightningWithdrawals(ctx context.Context, arg *LightningWithdrawalsRequest) ([]LightningWithdrawals, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.Ccy.IsEmpty() {
return nil, currency.ErrCurrencyCodeEmpty
}
if arg.Invoice == "" {
return nil, errors.New("missing invoice text")
}
var resp []LightningWithdrawals
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, postLightningWithdrawalEPL, http.MethodPost, typeAssets, "withdrawal-lightning", arg, &resp, true)
}
// CancelWithdrawal cancel normal withdrawal requests, but you cannot cancel withdrawal requests on Lightning.
func (o *Okcoin) CancelWithdrawal(ctx context.Context, arg *WithdrawalCancellation) (*WithdrawalCancellation, error) {
var resp []WithdrawalCancellation
if arg.WithdrawalID == "" {
return nil, errWithdrawalIDMissing
}
err := o.SendHTTPRequest(ctx, exchange.RestSpot, cancelWithdrawalEPL, http.MethodPost, typeAssets, "cancel-withdrawal", arg, &resp, true)
if err != nil {
return nil, err
}
if len(resp) == 0 {
return nil, errNoValidResponseFromServer
}
return &resp[0], nil
}
// GetWithdrawalHistory retrieve the withdrawal records according to the currency, withdrawal status, and time range in reverse chronological order. The 100 most recent records are returned by default.
func (o *Okcoin) GetWithdrawalHistory(ctx context.Context, ccy currency.Code, withdrawalID, clientID, transactionID, withdrawalType, state string, after, before time.Time, limit int64) ([]WithdrawalOrderItem, error) {
params := url.Values{}
if !ccy.IsEmpty() {
params.Set("ccy", ccy.String())
}
if withdrawalID != "" {
params.Set("wdId", withdrawalID)
}
if clientID != "" {
params.Set("clientId", clientID)
}
if transactionID != "" {
params.Set("txId", transactionID)
}
if withdrawalType != "" {
params.Set("type", withdrawalType)
}
if state != "" {
params.Set("state", state)
}
if !after.IsZero() {
params.Set("after", strconv.FormatInt(after.UnixMilli(), 10))
}
if !before.IsZero() {
params.Set("before", strconv.FormatInt(before.UnixMilli(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var resp []WithdrawalOrderItem
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getAssetWithdrawalHistoryEPL, http.MethodGet, typeAssets, common.EncodeURLValues("withdrawal-history", params), nil, &resp, true)
}
// ------------------------ Account Endpoints --------------------
// GetAccountBalance retrieve a list of assets (with non-zero balance), remaining balance, and available amount in the trading account.
func (o *Okcoin) GetAccountBalance(ctx context.Context, currencies ...currency.Code) ([]AccountBalanceInformation, error) {
params := url.Values{}
if len(currencies) > 0 {
currencyString := ""
var x int
for x = range currencies {
if x > 0 {
currencyString += ","
}
if currencies[x].IsEmpty() {
return nil, currency.ErrCurrencyPairEmpty
}
}
if len(currencies) > 0 {
params.Set("ccy", currencyString)
}
}
var resp []AccountBalanceInformation
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getAccountBalanceEPL, http.MethodGet, typeAccounts, common.EncodeURLValues("balance", params), nil, &resp, true)
}
// GetBillsDetails retrieve the bills of the account. The bill refers to all transaction records that result in changing the balance of an account. Pagination is supported, and the response is sorted with the most recent first.
// For the last 7 days.
func (o *Okcoin) GetBillsDetails(ctx context.Context, ccy currency.Code, instrumentType, billType, billSubType, afterBillID, beforeBillID string, begin, end time.Time, limit int64) ([]BillsDetail, error) {
params := url.Values{}
if !ccy.IsEmpty() {
params.Set("ccy", ccy.String())
}
if instrumentType != "" {
params.Set("instType", instrumentType)
}
if billType != "" {
params.Set("type", billType)
}
if billSubType != "" {
params.Set("subType", billSubType)
}
if afterBillID != "" {
params.Set("after", afterBillID)
}
if beforeBillID != "" {
params.Set("before", beforeBillID)
}
if !begin.IsZero() {
params.Set("before", strconv.FormatInt(begin.UnixMilli(), 10))
}
if !end.IsZero() {
params.Set("end", strconv.FormatInt(end.UnixMilli(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var resp []BillsDetail
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getBillsDetailLast3MonthEPL, http.MethodGet, typeAccounts, common.EncodeURLValues("bills", params), nil, &resp, true)
}
// GetBillsDetailsFor3Months retrieve the bills of the account. The bill refers to all transaction records that result in changing the balance of an account. Pagination is supported, and the response is sorted with the most recent first.
// For the last 3 months.
func (o *Okcoin) GetBillsDetailsFor3Months(ctx context.Context, ccy currency.Code, instrumentType, billType, billSubType, afterBillID, beforeBillID string, begin, end time.Time, limit int64) ([]BillsDetail, error) {
params := url.Values{}
if !ccy.IsEmpty() {
params.Set("ccy", ccy.String())
}
if instrumentType != "" {
params.Set("instType", instrumentType)
}
if billType != "" {
params.Set("type", billType)
}
if billSubType != "" {
params.Set("subType", billSubType)
}
if afterBillID != "" {
params.Set("after", afterBillID)
}
if beforeBillID != "" {
params.Set("before", beforeBillID)
}
if !begin.IsZero() {
params.Set("before", strconv.FormatInt(begin.UnixMilli(), 10))
}
if !end.IsZero() {
params.Set("end", strconv.FormatInt(end.UnixMilli(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var resp []BillsDetail
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getBillsDetailEPL, http.MethodGet, typeAccounts, common.EncodeURLValues("bills-archive", params), nil, &resp, true)
}
// GetAccountConfigurations retrieves current account configuration information.
func (o *Okcoin) GetAccountConfigurations(ctx context.Context) ([]AccountConfiguration, error) {
var resp []AccountConfiguration
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getAccountConfigurationEPL, http.MethodGet, typeAccounts, "config", nil, &resp, true)
}
// GetMaximumBuySellOrOpenAmount retrieves maximum buy, sell, or open amount information.
// Single instrument or multiple instruments (no more than 5) separated with comma, e.g. BTC-USD
// Trade mode 'cash'
// Price When the price is not specified, it will be calculated according to the last traded price.
// optional parameter
func (o *Okcoin) GetMaximumBuySellOrOpenAmount(ctx context.Context, instrumentID, tradeMode string, price float64) ([]MaxBuySellResp, error) {
params := url.Values{}
if instrumentID == "" {
return nil, errMissingInstrumentID
}
params.Set("instId", instrumentID)
if tradeMode == "" {
return nil, errTradeModeIsRequired
}
params.Set("tdMode", tradeMode)
if price != 0 {
params.Set("price", strconv.FormatFloat(price, 'f', -1, 64))
}
var resp []MaxBuySellResp
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getMaxBuySellAmountOpenAmountEPL, http.MethodGet, typeAccounts, common.EncodeURLValues("max-size", params), nil, &resp, true)
}
// GetMaximumAvailableTradableAmount retrieves maximum available tradable amount.
// Single instrument or multiple instruments (no more than 5) separated with comma, e.g. BTC-USDT,ETH-USDT
// Trade mode 'cash'
func (o *Okcoin) GetMaximumAvailableTradableAmount(ctx context.Context, tradeMode string, instrumentIDs ...string) ([]AvailableTradableAmount, error) {
params := url.Values{}
if len(instrumentIDs) == 0 {
return nil, errMissingInstrumentID
} else if len(instrumentIDs) > 5 {
return nil, errors.New("instrument IDs can not be more than 5")
}
params.Set("instId", strings.Join(instrumentIDs, ","))
if tradeMode == "" {
return nil, errTradeModeIsRequired
}
params.Set("tdMode", tradeMode)
var resp []AvailableTradableAmount
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getMaxAvailableTradableAmountEPL, http.MethodGet, typeAccounts, common.EncodeURLValues("max-avail-size", params), nil, &resp, true)
}
// GetFeeRates retrieves instrument trading fee information.
func (o *Okcoin) GetFeeRates(ctx context.Context, instrumentType, instrumentID string) ([]FeeRate, error) {
params := url.Values{}
if instrumentType == "" {
return nil, errInstrumentTypeMissing
}
params.Set("instType", instrumentType)
if instrumentID != "" {
params.Set("instId", instrumentID)
}
var resp []FeeRate
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getFeeRatesEPL, http.MethodGet, typeAccounts, common.EncodeURLValues("trade-fee", params), nil, &resp, true)
}
// GetMaximumWithdrawals retrieve the maximum transferable amount from trading account to funding account. If no currency is specified, the transferable amount of all owned currencies will be returned.
func (o *Okcoin) GetMaximumWithdrawals(ctx context.Context, ccy currency.Code) ([]MaximumWithdrawal, error) {
params := url.Values{}
if !ccy.IsEmpty() {
params.Set("ccy", ccy.String())
}
var resp []MaximumWithdrawal
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getMaxWithdrawalsEPL, http.MethodGet, typeAccounts, common.EncodeURLValues("max-withdrawal", params), nil, &resp, true)
}
// ------------------------------------ OTC-Desk RFQ --------------------------------
// GetAvailableRFQPairs retrieves a list of RFQ instruments.
func (o *Okcoin) GetAvailableRFQPairs(ctx context.Context) ([]AvailableRFQPair, error) {
var resp []AvailableRFQPair
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getAvailablePairsEPL, http.MethodGet, typeOtc, "rfq/instruments", nil, &resp, true)
}
// RequestQuote query current market quotation information
func (o *Okcoin) RequestQuote(ctx context.Context, arg *QuoteRequestArg) ([]RFQQuoteResponse, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.BaseCurrency.IsEmpty() {
return nil, fmt.Errorf("%w, base currency", currency.ErrCurrencyCodeEmpty)
}
if arg.QuoteCurrency.IsEmpty() {
return nil, fmt.Errorf("%w, quote currency", currency.ErrCurrencyCodeEmpty)
}
if arg.Side == "" {
return nil, fmt.Errorf("%w, empty order side", order.ErrSideIsInvalid)
}
if arg.RfqSize <= 0 {
return nil, fmt.Errorf("%w, RFQ size must be greater than 0", errInvalidAmount)
}
if arg.RfqSzCurrency.IsEmpty() {
return nil, fmt.Errorf("%w, rfqSzCurrency currency", currency.ErrCurrencyCodeEmpty)
}
var resp []RFQQuoteResponse
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, requestQuotesEPL, http.MethodPost, typeOtc, "rfq/quote", arg, &resp, true)
}
// PlaceRFQOrder submit RFQ order
func (o *Okcoin) PlaceRFQOrder(ctx context.Context, arg *PlaceRFQOrderRequest) ([]RFQOrderResponse, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.ClientDefinedTradeRequestID == "" {
return nil, errClientRequestIDRequired
}
if arg.QuoteID == "" {
return nil, errQuoteIDRequired
}
if arg.BaseCurrency.IsEmpty() {
return nil, fmt.Errorf("%w, base currency is required", currency.ErrCurrencyCodeEmpty)
}
if arg.QuoteCurrency.IsEmpty() {
return nil, fmt.Errorf("%w, quote currency is required", currency.ErrCurrencyCodeEmpty)
}
if arg.Side == "" {
return nil, fmt.Errorf("%w, order side is required", order.ErrSideIsInvalid)
}
if arg.Size <= 0 {
return nil, fmt.Errorf("%w, size can not be less than or equal to zero", errInvalidAmount)
}
if arg.SizeCurrency.IsEmpty() {
return nil, fmt.Errorf("%w, token is required", currency.ErrCurrencyCodeEmpty)
}
if arg.ClientRFQSendingTime == 0 {
arg.ClientRFQSendingTime = time.Now().UnixMilli()
}
var resp []RFQOrderResponse
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, placeRFQOrderEPL, http.MethodPost, typeOtc, "rfq/trade", arg, &resp, true)
}
// GetRFQOrderDetails retrieves an RFQ order details.
func (o *Okcoin) GetRFQOrderDetails(ctx context.Context, clientDefinedID, tradeOrderID string) ([]RFQOrderDetail, error) {
params := url.Values{}
if clientDefinedID != "" {
params.Set("clTReqId", clientDefinedID)
}
if tradeOrderID != "" {
params.Set("tradeId", tradeOrderID)
}
var resp []RFQOrderDetail
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getRFQTradeOrderDetailsEPL, http.MethodGet, typeOtc, common.EncodeURLValues("rfq/trade", params), nil, &resp, true)
}
// GetRFQOrderHistory retrieves an RFQ order history
func (o *Okcoin) GetRFQOrderHistory(ctx context.Context, begin, end time.Time, pageSize, pageIndex int64) ([]RFQOrderHistoryItem, error) {
params := url.Values{}
if !begin.IsZero() {
params.Set("begin", strconv.FormatInt(begin.UnixMilli(), 10))
}
if !end.IsZero() {
params.Set("end", strconv.FormatInt(end.UnixMilli(), 10))
}
if pageSize > 0 {
params.Set("pageSz", strconv.FormatInt(pageSize, 10))
}
if pageIndex > 0 {
params.Set("pageIdx", strconv.FormatInt(pageIndex, 10))
}
var resp []RFQOrderHistoryItem
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, getRFQTradeOrderHistoryEPL, http.MethodGet, typeOtc, common.EncodeURLValues("rfq/history", params), nil, &resp, true)
}
// ---------- Fiat ----------------------------------------------------------------
// Deposit posts a fiat deposit to an account
func (o *Okcoin) Deposit(ctx context.Context, arg *FiatDepositRequestArg) ([]FiatDepositResponse, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.ChannelID == "" {
return nil, errChannelIDRequired
}
if arg.Amount <= 0 {
return nil, fmt.Errorf("%w, amount %f", errInvalidAmount, arg.Amount)
}
if arg.BankAccountNumber == "" {
return nil, errBankAccountNumberIsRequired
}
var resp []FiatDepositResponse
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, fiatDepositEPL, http.MethodPost, typeFiat, "deposit", arg, &resp, true)
}
// CancelFiatDeposit cancels pending deposit requests.
func (o *Okcoin) CancelFiatDeposit(ctx context.Context, depositID string) (*CancelDepositAddressResp, error) {
if depositID == "" {
return nil, errors.New("deposit address required")
}
var resp []CancelDepositAddressResp
err := o.SendHTTPRequest(ctx, exchange.RestSpot, fiatCancelDepositEPL, http.MethodPost, typeFiat, "cancel-deposit", map[string]string{"depId": depositID}, &resp, true)
if err != nil {
return nil, err
}
if len(resp) == 0 {
return nil, errNoValidResponseFromServer
}
return &resp[0], nil
}
// GetFiatDepositHistory deposit history query requests can be filtered by the different elements, such as channels, deposit status, and currencies.
// Paging is also available during query and is stored in reverse order based on the transaction time, with the latest one at the top.
func (o *Okcoin) GetFiatDepositHistory(ctx context.Context, ccy currency.Code, channelID, depositState, depositID string, after, before time.Time, limit int64) ([]DepositHistoryResponse, error) {
params := url.Values{}
if channelID != "" {
params.Set("chanId", channelID)
}
if !ccy.IsEmpty() {
params.Set("ccy", ccy.String())
}
if depositState != "" {
params.Set("state", depositState)
}
if depositID != "" {
params.Set("depId", depositID)
}
if !after.IsZero() {
params.Set("after", strconv.FormatInt(after.UnixMilli(), 10))
}
if !before.IsZero() {
params.Set("before", strconv.FormatInt(before.UnixMilli(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var resp []DepositHistoryResponse
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, fiatDepositHistoryEPL, http.MethodGet, typeFiat, common.EncodeURLValues("deposit-history", params), nil, &resp, true)
}
// FiatWithdrawal submit fiat withdrawal operations.
func (o *Okcoin) FiatWithdrawal(ctx context.Context, arg *FiatWithdrawalParam) (*FiatWithdrawalResponse, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.ChannelID == "" {
return nil, errChannelIDRequired
}
if arg.Amount <= 0 {
return nil, fmt.Errorf("%w, amount must be greater than 0", errInvalidAmount)
}
if arg.BankAcctNumber == "" {
return nil, errBankAccountNumberIsRequired
}
var resp []FiatWithdrawalResponse
err := o.SendHTTPRequest(ctx, exchange.RestSpot, fiatWithdrawalEPL, http.MethodPost, typeFiat, "withdrawal", arg, &resp, true)
if err != nil {
return nil, err
}
if len(resp) == 0 {
return nil, errNoValidResponseFromServer
}
return &resp[0], nil
}
// FiatCancelWithdrawal cancels fiat withdrawal request
func (o *Okcoin) FiatCancelWithdrawal(ctx context.Context, withdrawalID string) (string, error) {
if withdrawalID == "" {
return "", errWithdrawalIDMissing
}
var resp []struct {
WithdrawalID string `json:"wdId"`
}
err := o.SendHTTPRequest(ctx, exchange.RestSpot, fiatCancelWithdrawalEPL, http.MethodPost, typeFiat, "cancel-withdrawal", map[string]string{"wdId": withdrawalID}, &resp, true)
if err != nil {
return "", err
}
if len(resp) == 0 {
return "", errNoValidResponseFromServer
}
return resp[0].WithdrawalID, nil
}
// GetFiatWithdrawalHistory retrieves a fiat withdrawal orders list
// Channel ID used in the transaction. 9:PrimeX; 28:PrimeX US; 21:PrimeX Europe; 3:Silvergate SEN; 27:Silvergate SEN HK
// Withdrawal state. -2:User canceled the order;-1:Withdrawal attempt has failed; 0:Withdrawal request submitted; 1:Withdrawal request is pending; 2:Withdrawal has been credited
func (o *Okcoin) GetFiatWithdrawalHistory(ctx context.Context, ccy currency.Code, channelID, withdrawalState, withdrawalID string, after, before time.Time, limit int64) ([]FiatWithdrawalHistoryItem, error) {
params := url.Values{}
if channelID != "" {
params.Set("chanId", channelID)
}
if !ccy.IsEmpty() {
params.Set("ccy", ccy.String())
}
if withdrawalState != "" {
params.Set("state", withdrawalState)
}
if withdrawalID != "" {
params.Set("wdId", withdrawalID)
}
if !after.IsZero() {
params.Set("after", strconv.FormatInt(after.UnixMilli(), 10))
}
if !before.IsZero() {
params.Set("before", strconv.FormatInt(before.UnixMilli(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var resp []FiatWithdrawalHistoryItem
return resp, o.SendHTTPRequest(ctx, exchange.RestSpot, fiatGetWithdrawalsEPL, http.MethodGet, typeFiat, common.EncodeURLValues("withdrawal-history", params), nil, &resp, true)
}
// GetChannelInfo retrieves channel detailed information given channel id.
func (o *Okcoin) GetChannelInfo(ctx context.Context, channelID string) ([]ChannelInfo, error) {
params := url.Values{}
if channelID != "" {
params.Set("chanId", channelID)
}
var resp []ChannelInfo