-
Notifications
You must be signed in to change notification settings - Fork 789
/
okx.go
4375 lines (4151 loc) · 168 KB
/
okx.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 okx
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"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/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/kline"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
// Okx is the overarching type across this package
type Okx struct {
exchange.Base
WsResponseMultiplexer wsRequestDataChannelsMultiplexer
// WsRequestSemaphore channel is used to block write operation on the websocket connection to reduce contention; a kind of bounded parallelism.
// it is made to hold up to 20 integers so that up to 20 write operations can be called over the websocket connection at a time.
// and when the operation is completed the thread releases (consumes) one value from the channel so that the other waiting operation can enter.
// ok.WsRequestSemaphore <- 1
// defer func() { <-ok.WsRequestSemaphore }()
WsRequestSemaphore chan int
}
const (
baseURL = "https://www.okx.com/"
okxAPIURL = baseURL + okxAPIPath
okxAPIVersion = "/v5/"
tradeSpot = "trade-spot/"
tradeMargin = "trade-margin/"
tradeFutures = "trade-futures/"
tradePerps = "trade-swap/"
tradeOptions = "trade-option/"
okxAPIPath = "api" + okxAPIVersion
okxWebsocketURL = "wss://ws.okx.com:8443/ws" + okxAPIVersion
okxAPIWebsocketPublicURL = okxWebsocketURL + "public"
okxAPIWebsocketPrivateURL = okxWebsocketURL + "private"
// tradeEndpoints
tradeOrder = "trade/order"
placeMultipleOrderURL = "trade/batch-orders"
cancelTradeOrder = "trade/cancel-order"
cancelBatchTradeOrders = "trade/cancel-batch-orders"
amendOrder = "trade/amend-order"
amendBatchOrders = "trade/amend-batch-orders"
closePositionPath = "trade/close-position"
pendingTradeOrders = "trade/orders-pending"
tradeHistory = "trade/orders-history"
orderHistoryArchive = "trade/orders-history-archive"
tradeFills = "trade/fills"
tradeFillsHistory = "trade/fills-history"
assetBills = "asset/bills"
lightningDeposit = "asset/deposit-lightning"
assetDeposits = "asset/deposit-address"
pathToAssetDepositHistory = "asset/deposit-history"
assetWithdrawal = "asset/withdrawal"
assetLightningWithdrawal = "asset/withdrawal-lightning"
cancelWithdrawal = "asset/cancel-withdrawal"
withdrawalHistory = "asset/withdrawal-history"
smallAssetsConvert = "asset/convert-dust-assets"
// Algo order routes
cancelAlgoOrder = "trade/cancel-algos"
algoTradeOrder = "trade/order-algo"
cancelAdvancedAlgoOrder = "trade/cancel-advance-algos"
getAlgoOrders = "trade/orders-algo-pending"
algoOrderHistory = "trade/orders-algo-history"
easyConvertCurrencyList = "trade/easy-convert-currency-list"
easyConvertHistoryPath = "trade/easy-convert-history"
easyConvert = "trade/easy-convert"
oneClickRepayCurrencyListPath = "trade/one-click-repay-currency-list"
oneClickRepayHistory = "trade/one-click-repay-history"
oneClickRepay = "trade/one-click-repay"
// Funding account routes
assetCurrencies = "asset/currencies"
assetBalance = "asset/balances"
assetValuation = "asset/asset-valuation"
assetTransfer = "asset/transfer"
assetTransferState = "asset/transfer-state"
// Market Data
marketTickers = "market/tickers"
marketTicker = "market/ticker"
indexTickers = "market/index-tickers"
marketBooks = "market/books"
marketCandles = "market/candles"
marketCandlesHistory = "market/history-candles"
marketCandlesIndex = "market/index-candles"
marketPriceCandles = "market/mark-price-candles"
marketTrades = "market/trades"
marketTradesHistory = "market/history-trades"
marketPlatformVolumeIn24Hour = "market/platform-24-volume"
marketOpenOracles = "market/open-oracle"
marketExchangeRate = "market/exchange-rate"
marketIndexComponents = "market/index-components"
marketBlockTickers = "market/block-tickers"
marketBlockTicker = "market/block-ticker"
// Public endpoints
publicInstruments = "public/instruments"
publicDeliveryExerciseHistory = "public/delivery-exercise-history"
publicOpenInterestValues = "public/open-interest"
publicFundingRate = "public/funding-rate"
publicFundingRateHistory = "public/funding-rate-history"
publicLimitPath = "public/price-limit"
publicOptionalData = "public/opt-summary"
publicEstimatedPrice = "public/estimated-price"
publicDiscountRate = "public/discount-rate-interest-free-quota"
publicTime = "public/time"
publicLiquidationOrders = "public/liquidation-orders"
publicMarkPrice = "public/mark-price"
publicPositionTiers = "public/position-tiers"
publicInterestRateAndLoanQuota = "public/interest-rate-loan-quota"
publicVIPInterestRateAndLoanQuota = "public/vip-interest-rate-loan-quota"
publicUnderlyings = "public/underlying"
publicInsuranceFunds = "public/insurance-fund"
publicCurrencyConvertContract = "public/convert-contract-coin"
publicBlockTrades = "public/block-trades"
// Trading Endpoints
tradingDataSupportedCoins = "rubik/stat/trading-data/support-coin"
tradingTakerVolume = "rubik/stat/taker-volume"
tradingMarginLoanRatio = "rubik/stat/margin/loan-ratio"
longShortAccountRatio = "rubik/stat/contracts/long-short-account-ratio"
contractOpenInterestVolume = "rubik/stat/contracts/open-interest-volume"
optionOpenInterestVolume = "rubik/stat/option/open-interest-volume"
optionOpenInterestVolumeRatio = "rubik/stat/option/open-interest-volume-ratio"
optionOpenInterestVolumeExpiry = "rubik/stat/option/open-interest-volume-expiry"
optionOpenInterestVolumeStrike = "rubik/stat/option/open-interest-volume-strike"
takerBlockVolume = "rubik/stat/option/taker-block-volume"
// Convert Currencies end points
assetConvertCurrencies = "asset/convert/currencies"
convertCurrencyPairsPath = "asset/convert/currency-pair"
assetEstimateQuote = "asset/convert/estimate-quote"
assetConvertTrade = "asset/convert/trade"
assetConvertHistory = "asset/convert/history"
// Account Endpoints
accountBalance = "account/balance"
accountPosition = "account/positions"
accountPositionHistory = "account/positions-history"
accountAndPositionRisk = "account/account-position-risk"
accountBillsDetail = "account/bills"
accountBillsDetailArchive = "account/bills-archive"
accountConfiguration = "account/config"
accountSetPositionMode = "account/set-position-mode"
accountSetLeverage = "account/set-leverage"
accountMaxSize = "account/max-size"
accountMaxAvailSize = "account/max-avail-size"
accountPositionMarginBalance = "account/position/margin-balance"
accountLeverageInfo = "account/leverage-info"
accountMaxLoan = "account/max-loan"
accountTradeFee = "account/trade-fee"
accountInterestAccrued = "account/interest-accrued"
accountInterestRate = "account/interest-rate"
accountSetGreeks = "account/set-greeks"
accountSetIsolatedMode = "account/set-isolated-mode"
accountMaxWithdrawal = "account/max-withdrawal"
accountRiskState = "account/risk-state"
accountBorrowReply = "account/borrow-repay"
accountBorrowRepayHistory = "account/borrow-repay-history"
accountInterestLimits = "account/interest-limits"
accountSimulatedMargin = "account/simulated_margin"
accountGreeks = "account/greeks"
accountPortfolioMarginLimitation = "account/position-tiers"
// Block Trading
rfqCounterparties = "rfq/counterparties"
rfqCreateRfq = "rfq/create-rfq"
rfqCancelRfq = "rfq/cancel-rfq"
rfqCancelRfqs = "rfq/cancel-batch-rfqs"
rfqCancelAllRfqs = "rfq/cancel-all-rfqs"
rfqExecuteQuote = "rfq/execute-quote"
makerInstrumentSettings = "rfq/maker-instrument-settings"
mmpReset = "rfq/mmp-reset"
rfqCreateQuote = "rfq/create-quote"
rfqCancelQuote = "rfq/cancel-quote"
rfqCancelBatchQuotes = "rfq/cancel-batch-quotes"
rfqCancelAllQuotes = "rfq/cancel-all-quotes"
rfqRfqs = "rfq/rfqs"
rfqQuotes = "rfq/quotes"
rfqTrades = "rfq/trades"
rfqPublicTrades = "rfq/public-trades"
// Subaccount endpoints
usersSubaccountList = "users/subaccount/list"
subAccountModifyAPIKey = "users/subaccount/modify-apikey"
accountSubaccountBalances = "account/subaccount/balances"
assetSubaccountBalances = "asset/subaccount/balances"
assetSubaccountBills = "asset/subaccount/bills"
assetSubaccountTransfer = "asset/subaccount/transfer"
userSubaccountSetTransferOut = "users/subaccount/set-transfer-out"
usersEntrustSubaccountList = "users/entrust-subaccount-list"
// Grid Trading Endpoints
gridOrderAlgo = "tradingBot/grid/order-algo"
gridAmendOrderAlgo = "tradingBot/grid/amend-order-algo"
gridAlgoOrderStop = "tradingBot/grid/stop-order-algo"
gridAlgoOrders = "tradingBot/grid/orders-algo-pending"
gridAlgoOrdersHistory = "tradingBot/grid/orders-algo-history"
gridOrdersAlgoDetails = "tradingBot/grid/orders-algo-details"
gridSuborders = "tradingBot/grid/sub-orders"
gridPositions = "tradingBot/grid/positions"
gridWithdrawalIncome = "tradingBot/grid/withdraw-income"
gridComputeMarginBalance = "tradingBot/grid/compute-margin-balance"
gridMarginBalance = "tradingBot/grid/margin-balance"
gridAIParams = "tradingBot/grid/ai-param"
// Earn
financeOffers = "finance/staking-defi/offers"
financePurchase = "finance/staking-defi/purchase"
financeRedeem = "finance/staking-defi/redeem"
financeCancelPurchase = "finance/staking-defi/cancel"
financeActiveOrders = "finance/staking-defi/orders-active"
financeOrdersHistory = "finance/staking-defi/orders-history"
// Savings
financeSavingBalance = "finance/savings/balance"
financePurchaseRedempt = "finance/savings/purchase-redempt"
financeSetLendingRate = "finance/savings/set-lending-rate"
financeLendingHistory = "finance/savings/lending-history"
financePublicBorrowInfo = "finance/savings/lending-rate-summary"
financePublicBorrowHistory = "finance/savings/lending-rate-history"
// Status Endpoints
systemStatus = "system/status"
)
var (
errNo24HrTradeVolumeFound = errors.New("no trade record found in the 24 trade volume ")
errOracleInformationNotFound = errors.New("oracle information not found")
errExchangeInfoNotFound = errors.New("exchange information not found")
errIndexComponentNotFound = errors.New("unable to fetch index components")
errMissingRequiredArgInstType = errors.New("invalid required argument instrument type")
errLimitValueExceedsMaxOf100 = errors.New("limit value exceeds the maximum value 100")
errMissingInstrumentID = errors.New("missing instrument id")
errFundingRateHistoryNotFound = errors.New("funding rate history not found")
errMissingRequiredUnderlying = errors.New("error missing required parameter underlying")
errMissingRequiredParamInstID = errors.New("missing required parameter instrument id")
errLiquidationOrderResponseNotFound = errors.New("liquidation order not found")
errEitherInstIDOrCcyIsRequired = errors.New("either parameter instId or ccy is required")
errIncorrectRequiredParameterTradeMode = errors.New("unacceptable required argument, trade mode")
errInterestRateAndLoanQuotaNotFound = errors.New("interest rate and loan quota not found")
errUnderlyingsForSpecifiedInstTypeNofFound = errors.New("underlyings for the specified instrument id is not found")
errInsuranceFundInformationNotFound = errors.New("insurance fund information not found")
errMissingExpiryTimeParameter = errors.New("missing expiry date parameter")
errInvalidTradeModeValue = errors.New("invalid trade mode value")
errInvalidOrderType = errors.New("invalid order type")
errInvalidAmount = errors.New("unacceptable quantity to buy or sell")
errMissingClientOrderIDOrOrderID = errors.New("client order id or order id is missing")
errInvalidNewSizeOrPriceInformation = errors.New("invalid the new size or price information")
errMissingNewSize = errors.New("missing the order size information")
errMissingMarginMode = errors.New("missing required param margin mode \"mgnMode\"")
errInvalidTriggerPrice = errors.New("invalid trigger price value")
errInvalidPriceLimit = errors.New("invalid price limit value")
errMissingIntervalValue = errors.New("missing interval value")
errMissingTakeProfitTriggerPrice = errors.New("missing take profit trigger price")
errMissingTakeProfitOrderPrice = errors.New("missing take profit order price")
errMissingSizeLimit = errors.New("missing required parameter \"szLimit\"")
errMissingEitherAlgoIDOrState = errors.New("either algo id or order state is required")
errUnacceptableAmount = errors.New("amount must be greater than 0")
errInvalidCurrencyValue = errors.New("invalid currency value")
errInvalidDepositAmount = errors.New("invalid deposit amount")
errMissingResponseBody = errors.New("error missing response body")
errMissingValidWithdrawalID = errors.New("missing valid withdrawal id")
errNoValidResponseFromServer = errors.New("no valid response from server")
errInstrumentTypeRequired = errors.New("instrument type required")
errInvalidInstrumentType = errors.New("invalid instrument type")
errMissingValidGreeksType = errors.New("missing valid greeks type")
errMissingIsolatedMarginTradingSetting = errors.New("missing isolated margin trading setting, isolated margin trading settings automatic:Auto transfers autonomy:Manual transfers")
errInvalidOrderSide = errors.New("invalid order side")
errOrderSideRequired = errors.New("order side required")
errInvalidCounterParties = errors.New("missing counter parties")
errInvalidLegs = errors.New("no legs are provided")
errMissingRfqIDAndClientRfqID = errors.New("missing rfq id or client rfq id")
errMissingRfqIDOrQuoteID = errors.New("either Rfq ID or Quote ID is missing")
errMissingRfqID = errors.New("error missing rfq id")
errMissingLegs = errors.New("missing legs")
errMissingSizeOfQuote = errors.New("missing size of quote leg")
errMossingLegsQuotePrice = errors.New("error missing quote price")
errMissingQuoteIDOrClientQuoteID = errors.New("missing quote id or client quote id")
errMissingEitherQuoteIDAOrClientQuoteIDs = errors.New("missing either quote ids or client quote ids")
errMissingRequiredParameterSubaccountName = errors.New("missing required parameter subaccount name")
errInvalidTransferAmount = errors.New("unacceptable transfer amount")
errInvalidSubaccount = errors.New("invalid account type")
errMissingDestinationSubaccountName = errors.New("missing destination subaccount name")
errMissingInitialSubaccountName = errors.New("missing initial subaccount name")
errMissingAlgoOrderType = errors.New("missing algo order type \"grid\": Spot grid, \"contract_grid\": Contract grid")
errInvalidMaximumPrice = errors.New("invalid maximum price")
errInvalidMinimumPrice = errors.New("invalid minimum price")
errInvalidGridQuantity = errors.New("invalid grid quantity (grid number)")
errMissingSize = errors.New("missing required argument, size")
errMissingRequiredArgumentDirection = errors.New("missing required argument, direction")
errRequiredParameterMissingLeverage = errors.New("missing required parameter, leverage")
errMissingAlgoOrderID = errors.New("missing algo orders id")
errMissingValidStopType = errors.New("invalid grid order stop type, only values are \"1\" and \"2\" ")
errMissingSubOrderType = errors.New("missing sub order type")
errMissingQuantity = errors.New("invalid quantity to buy or sell")
errDepositAddressNotFound = errors.New("deposit address with the specified currency code and chain not found")
errMissingAtLeast1CurrencyPair = errors.New("at least one currency is required to fetch order history")
errNoCandlestickDataFound = errors.New("no candlesticks data found")
errInvalidWebsocketEvent = errors.New("invalid websocket event")
errMissingValidChannelInformation = errors.New("missing channel information")
errNilArgument = errors.New("nil argument is not acceptable")
errNoOrderParameterPassed = errors.New("no order parameter was passed")
errMaxRfqOrdersToCancel = errors.New("no more than 100 Rfq cancel order parameter is allowed")
errMalformedData = errors.New("malformed data")
errInvalidUnderlying = errors.New("invalid underlying")
errMissingRequiredParameter = errors.New("missing required parameter")
errMissingMakerInstrumentSettings = errors.New("missing maker instrument settings")
errInvalidSubAccountName = errors.New("invalid sub-account name")
errInvalidAPIKey = errors.New("invalid api key")
errInvalidAlgoID = errors.New("invalid algo id")
errInvalidMarginTypeAdjust = errors.New("invalid margin type adjust, only 'add' and 'reduce' are allowed")
errInvalidAlgoOrderType = errors.New("invalid algo order type")
errEmptyArgument = errors.New("empty argument")
errInvalidIPAddress = errors.New("invalid ip address")
errInvalidAPIKeyPermission = errors.New("invalid API Key permission")
errInvalidResponseParam = errors.New("invalid response parameter, response must be non-nil pointer")
errEmptyPlaceOrderResponse = errors.New("empty place order response")
errTooManyArgument = errors.New("too many cancel request params")
errIncompleteCurrencyPair = errors.New("incomplete currency pair")
errInvalidDuration = errors.New("invalid grid contract duration, only '7D', '30D', and '180D' are allowed")
errInvalidProtocolType = errors.New("invalid protocol type, only 'staking' and 'defi' allowed")
errExceedLimit = errors.New("limit exceeded")
errOnlyThreeMonthsSupported = errors.New("only three months of trade data retrieval supported")
errOnlyOneResponseExpected = errors.New("one response item expected")
errNoInstrumentFound = errors.New("no instrument found")
)
/************************************ MarketData Endpoints *************************************************/
// OrderTypeFromString returns order.Type instance from string
func (ok *Okx) OrderTypeFromString(orderType string) (order.Type, error) {
switch strings.ToLower(orderType) {
case OkxOrderMarket:
return order.Market, nil
case OkxOrderLimit:
return order.Limit, nil
case OkxOrderPostOnly:
return order.PostOnly, nil
case OkxOrderFOK:
return order.FillOrKill, nil
case OkxOrderIOC:
return order.ImmediateOrCancel, nil
case OkxOrderOptimalLimitIOC:
return order.OptimalLimitIOC, nil
default:
return order.UnknownType, fmt.Errorf("%w %v", errInvalidOrderType, orderType)
}
}
// OrderTypeString returns a string representation of order.Type instance
func (ok *Okx) OrderTypeString(orderType order.Type) (string, error) {
switch orderType {
case order.Market:
return OkxOrderMarket, nil
case order.Limit:
return OkxOrderLimit, nil
case order.PostOnly:
return OkxOrderPostOnly, nil
case order.FillOrKill:
return OkxOrderFOK, nil
case order.IOS:
return OkxOrderIOC, nil
case order.OptimalLimitIOC:
return OkxOrderOptimalLimitIOC, nil
default:
return "", fmt.Errorf("%w %v", errInvalidOrderType, orderType)
}
}
// PlaceOrder place an order only if you have sufficient funds.
func (ok *Okx) PlaceOrder(ctx context.Context, arg *PlaceOrderRequestParam, a asset.Item) (*OrderData, error) {
if arg == nil {
return nil, errNilArgument
}
arg.AssetType = a
err := ok.validatePlaceOrderParams(arg)
if err != nil {
return nil, err
}
var resp []OrderData
err = ok.SendHTTPRequest(ctx, exchange.RestSpot, placeOrderEPL, http.MethodPost, tradeOrder, &arg, &resp, true)
if err != nil {
if len(resp) != 1 {
return nil, err
}
return nil, fmt.Errorf("error code:%s message: %v", resp[0].SCode, resp[0].SMessage)
}
if len(resp) == 1 {
return &resp[0], nil
}
return nil, errNoValidResponseFromServer
}
func (ok *Okx) validatePlaceOrderParams(arg *PlaceOrderRequestParam) error {
if arg.InstrumentID == "" {
return errMissingInstrumentID
}
arg.Side = strings.ToLower(arg.Side)
if arg.Side != order.Buy.Lower() && arg.Side != order.Sell.Lower() {
return fmt.Errorf("%w %s", errInvalidOrderSide, arg.Side)
}
if arg.TradeMode != "" &&
arg.TradeMode != TradeModeCross &&
arg.TradeMode != TradeModeIsolated &&
arg.TradeMode != TradeModeCash {
return fmt.Errorf("%w %s", errInvalidTradeModeValue, arg.TradeMode)
}
if arg.PositionSide != "" {
if (arg.PositionSide == positionSideLong || arg.PositionSide == positionSideShort) &&
(arg.AssetType != asset.Futures && arg.AssetType != asset.PerpetualSwap) {
return errors.New("invalid position mode, 'long' or 'short' for Futures/SWAP, otherwise 'net'(default) are allowed")
}
}
arg.OrderType = strings.ToLower(arg.OrderType)
if arg.OrderType == order.OptimalLimitIOC.Lower() &&
(arg.AssetType != asset.Futures && arg.AssetType != asset.PerpetualSwap) {
return errors.New("\"optimal_limit_ioc\": market order with immediate-or-cancel order (applicable only to Futures and Perpetual swap)")
}
if arg.OrderType != OkxOrderMarket &&
arg.OrderType != OkxOrderLimit &&
arg.OrderType != OkxOrderPostOnly &&
arg.OrderType != OkxOrderFOK &&
arg.OrderType != OkxOrderIOC &&
arg.OrderType != OkxOrderOptimalLimitIOC {
return fmt.Errorf("%w %v", errInvalidOrderType, arg.OrderType)
}
if arg.Amount <= 0 {
return errInvalidAmount
}
if arg.QuantityType != "" && arg.QuantityType != "base_ccy" && arg.QuantityType != "quote_ccy" {
return errors.New("only base_ccy and quote_ccy quantity types are supported")
}
return nil
}
// PlaceMultipleOrders to place orders in batches. Maximum 20 orders can be placed at a time. Request parameters should be passed in the form of an array.
func (ok *Okx) PlaceMultipleOrders(ctx context.Context, args []PlaceOrderRequestParam) ([]OrderData, error) {
if len(args) == 0 {
return nil, errNoOrderParameterPassed
}
var err error
for x := range args {
err = ok.validatePlaceOrderParams(&args[x])
if err != nil {
return nil, err
}
}
var resp []OrderData
err = ok.SendHTTPRequest(ctx, exchange.RestSpot, placeMultipleOrdersEPL, http.MethodPost, placeMultipleOrderURL, &args, &resp, true)
if err != nil {
if len(resp) == 0 {
return nil, err
}
var errs error
for x := range resp {
errs = common.AppendError(errs, fmt.Errorf("error code:%s message: %v", resp[x].SCode, resp[x].SMessage))
}
return nil, errs
}
return resp, nil
}
// CancelSingleOrder cancel an incomplete order.
func (ok *Okx) CancelSingleOrder(ctx context.Context, arg CancelOrderRequestParam) (*OrderData, error) {
if arg.InstrumentID == "" {
return nil, errMissingInstrumentID
}
if arg.OrderID == "" && arg.ClientOrderID == "" {
return nil, errors.New("either order id or client id is required")
}
var resp []OrderData
err := ok.SendHTTPRequest(ctx, exchange.RestSpot, cancelOrderEPL, http.MethodPost, cancelTradeOrder, &arg, &resp, true)
if err != nil {
if len(resp) != 1 {
return nil, err
}
return nil, fmt.Errorf("error code:%s message: %v", resp[0].SCode, resp[0].SMessage)
}
if len(resp) == 1 {
return &resp[0], nil
}
return nil, errNoValidResponseFromServer
}
// CancelMultipleOrders cancel incomplete orders in batches. Maximum 20 orders can be canceled at a time.
// Request parameters should be passed in the form of an array.
func (ok *Okx) CancelMultipleOrders(ctx context.Context, args []CancelOrderRequestParam) ([]OrderData, error) {
for x := range args {
arg := args[x]
if arg.InstrumentID == "" {
return nil, errMissingInstrumentID
}
if arg.OrderID == "" && arg.ClientOrderID == "" {
return nil, errors.New("either order id or client id is required")
}
}
var resp []OrderData
err := ok.SendHTTPRequest(ctx, exchange.RestSpot, cancelMultipleOrdersEPL,
http.MethodPost, cancelBatchTradeOrders, args, &resp, true)
if err != nil {
if len(resp) == 0 {
return nil, err
}
var errs error
for x := range resp {
if resp[x].SCode != "0" {
errs = common.AppendError(errs, fmt.Errorf("error code:%s message: %v", resp[x].SCode, resp[x].SMessage))
}
}
return nil, errs
}
return resp, nil
}
// AmendOrder an incomplete order.
func (ok *Okx) AmendOrder(ctx context.Context, arg *AmendOrderRequestParams) (*OrderData, error) {
if arg.InstrumentID == "" {
return nil, errMissingInstrumentID
}
if arg.ClientOrderID == "" && arg.OrderID == "" {
return nil, errMissingClientOrderIDOrOrderID
}
if arg.NewQuantity < 0 && arg.NewPrice < 0 {
return nil, errInvalidNewSizeOrPriceInformation
}
var resp []OrderData
err := ok.SendHTTPRequest(ctx, exchange.RestSpot, amendOrderEPL, http.MethodPost, amendOrder, arg, &resp, true)
if err != nil {
return nil, err
}
if len(resp) == 1 {
return &resp[0], nil
}
return nil, errNoValidResponseFromServer
}
// AmendMultipleOrders amend incomplete orders in batches. Maximum 20 orders can be amended at a time. Request parameters should be passed in the form of an array.
func (ok *Okx) AmendMultipleOrders(ctx context.Context, args []AmendOrderRequestParams) ([]OrderData, error) {
for x := range args {
if args[x].InstrumentID == "" {
return nil, errMissingInstrumentID
}
if args[x].ClientOrderID == "" && args[x].OrderID == "" {
return nil, errMissingClientOrderIDOrOrderID
}
if args[x].NewQuantity < 0 && args[x].NewPrice < 0 {
return nil, errInvalidNewSizeOrPriceInformation
}
}
var resp []OrderData
return resp, ok.SendHTTPRequest(ctx, exchange.RestSpot, amendMultipleOrdersEPL, http.MethodPost, amendBatchOrders, &args, &resp, true)
}
// ClosePositions Close all positions of an instrument via a market order.
func (ok *Okx) ClosePositions(ctx context.Context, arg *ClosePositionsRequestParams) (*ClosePositionResponse, error) {
if arg.InstrumentID == "" {
return nil, errMissingInstrumentID
}
if arg.MarginMode != "" &&
arg.MarginMode != TradeModeCross &&
arg.MarginMode != TradeModeIsolated {
return nil, errMissingMarginMode
}
var resp []ClosePositionResponse
err := ok.SendHTTPRequest(ctx, exchange.RestSpot, closePositionEPL, http.MethodPost, closePositionPath, arg, &resp, true)
if err != nil {
return nil, err
}
if len(resp) == 1 {
return &resp[0], nil
}
return nil, errNoValidResponseFromServer
}
// GetOrderDetail retrieves order details given instrument id and order identification
func (ok *Okx) GetOrderDetail(ctx context.Context, arg *OrderDetailRequestParam) (*OrderDetail, error) {
if arg == nil {
return nil, errNilArgument
}
params := url.Values{}
if arg.InstrumentID == "" {
return nil, errMissingInstrumentID
}
params.Set("instId", arg.InstrumentID)
switch {
case arg.OrderID == "" && arg.ClientOrderID == "":
return nil, errMissingClientOrderIDOrOrderID
case arg.ClientOrderID == "":
params.Set("ordId", arg.OrderID)
default:
params.Set("clOrdId", arg.ClientOrderID)
}
var resp []OrderDetail
err := ok.SendHTTPRequest(ctx, exchange.RestSpot, getOrderDetEPL, http.MethodGet, common.EncodeURLValues(tradeOrder, params), nil, &resp, true)
if err != nil {
return nil, err
}
if len(resp) == 1 {
return &resp[0], nil
}
return nil, errNoValidResponseFromServer
}
// GetOrderList retrieves all incomplete orders under the current account.
func (ok *Okx) GetOrderList(ctx context.Context, arg *OrderListRequestParams) ([]OrderDetail, error) {
if arg == nil {
return nil, errNilArgument
}
params := url.Values{}
if arg.InstrumentType != "" {
params.Set("instType", arg.InstrumentType)
}
if arg.InstrumentID != "" {
params.Set("instId", arg.InstrumentID)
}
if arg.Underlying != "" {
params.Set("uly", arg.Underlying)
}
if arg.OrderType != "" {
params.Set("orderType", strings.ToLower(arg.OrderType))
}
if arg.State != "" {
params.Set("state", arg.State)
}
if arg.Before != "" {
params.Set("before", arg.Before)
}
if arg.After != "" {
params.Set("after", arg.After)
}
if arg.Limit > 0 {
params.Set("limit", strconv.FormatInt(arg.Limit, 10))
}
var resp []OrderDetail
return resp, ok.SendHTTPRequest(ctx, exchange.RestSpot, getOrderListEPL, http.MethodGet, common.EncodeURLValues(pendingTradeOrders, params), nil, &resp, true)
}
// Get7DayOrderHistory retrieves the completed order data for the last 7 days, and the incomplete orders that have been cancelled are only reserved for 2 hours.
func (ok *Okx) Get7DayOrderHistory(ctx context.Context, arg *OrderHistoryRequestParams) ([]OrderDetail, error) {
return ok.getOrderHistory(ctx, arg, tradeHistory, getOrderHistory7DaysEPL)
}
// Get3MonthOrderHistory retrieves the completed order data for the last 7 days, and the incomplete orders that have been cancelled are only reserved for 2 hours.
func (ok *Okx) Get3MonthOrderHistory(ctx context.Context, arg *OrderHistoryRequestParams) ([]OrderDetail, error) {
return ok.getOrderHistory(ctx, arg, orderHistoryArchive, getOrderHistory3MonthsEPL)
}
// getOrderHistory retrieves the order history of the past limited times
func (ok *Okx) getOrderHistory(ctx context.Context, arg *OrderHistoryRequestParams, route string, rateLimit request.EndpointLimit) ([]OrderDetail, error) {
params := url.Values{}
if arg.InstrumentType != "" {
params.Set("instType", strings.ToUpper(arg.InstrumentType))
} else {
return nil, errMissingRequiredArgInstType
}
if arg.InstrumentID != "" {
params.Set("instId", arg.InstrumentID)
}
if arg.Underlying != "" {
params.Set("uly", arg.Underlying)
}
if arg.OrderType != "" {
params.Set("orderType", strings.ToLower(arg.OrderType))
}
if arg.State != "" {
params.Set("state", arg.State)
}
if arg.Before != "" {
params.Set("before", arg.Before)
}
if arg.After != "" {
params.Set("after", arg.After)
}
if !arg.Start.IsZero() {
params.Set("begin", strconv.FormatInt(arg.Start.UnixMilli(), 10))
}
if !arg.End.IsZero() {
params.Set("end", strconv.FormatInt(arg.End.UnixMilli(), 10))
}
if arg.Limit > 0 {
params.Set("limit", strconv.FormatInt(arg.Limit, 10))
}
if arg.Category != "" {
params.Set("category", strings.ToLower(arg.Category))
}
var resp []OrderDetail
return resp, ok.SendHTTPRequest(ctx, exchange.RestSpot, rateLimit, http.MethodGet, common.EncodeURLValues(route, params), nil, &resp, true)
}
// GetTransactionDetailsLast3Days retrieves recently-filled transaction details in the last 3 day.
func (ok *Okx) GetTransactionDetailsLast3Days(ctx context.Context, arg *TransactionDetailRequestParams) ([]TransactionDetail, error) {
return ok.getTransactionDetails(ctx, arg, tradeFills, getTransactionDetail3DaysEPL)
}
// GetTransactionDetailsLast3Months Retrieve recently-filled transaction details in the last 3 months.
func (ok *Okx) GetTransactionDetailsLast3Months(ctx context.Context, arg *TransactionDetailRequestParams) ([]TransactionDetail, error) {
return ok.getTransactionDetails(ctx, arg, tradeFillsHistory, getTransactionDetail3MonthsEPL)
}
// GetTransactionDetails retrieves recently-filled transaction details.
func (ok *Okx) getTransactionDetails(ctx context.Context, arg *TransactionDetailRequestParams, route string, rateLimit request.EndpointLimit) ([]TransactionDetail, error) {
params := url.Values{}
arg.InstrumentType = strings.ToUpper(arg.InstrumentType)
if arg.InstrumentType != "" {
params.Set("instType", arg.InstrumentType)
} else {
return nil, errMissingRequiredArgInstType
}
if arg.InstrumentID != "" {
params.Set("instId", arg.InstrumentID)
}
if arg.Underlying != "" {
params.Set("uly", arg.Underlying)
}
if !arg.Begin.IsZero() {
params.Set("begin", strconv.FormatInt(arg.Begin.UnixMilli(), 10))
}
if !arg.End.IsZero() {
params.Set("end", strconv.FormatInt(arg.End.UnixMilli(), 10))
}
if arg.Limit > 0 {
params.Set("limit", strconv.FormatInt(arg.Limit, 10))
}
if arg.InstrumentID != "" {
params.Set("instId", arg.InstrumentID)
}
if arg.After != "" {
params.Set("after", arg.After)
}
if arg.Before != "" {
params.Set("before", arg.Before)
}
var resp []TransactionDetail
return resp, ok.SendHTTPRequest(ctx, exchange.RestSpot, rateLimit, http.MethodGet, common.EncodeURLValues(route, params), nil, &resp, true)
}
// PlaceAlgoOrder order includes trigger order, oco order, conditional order,iceberg order, twap order and trailing order.
func (ok *Okx) PlaceAlgoOrder(ctx context.Context, arg *AlgoOrderParams) (*AlgoOrder, error) {
if arg.InstrumentID == "" {
return nil, errMissingInstrumentID
}
arg.TradeMode = strings.ToLower(arg.TradeMode)
if arg.TradeMode != TradeModeCross &&
arg.TradeMode != TradeModeIsolated {
return nil, errInvalidTradeModeValue
}
if arg.Side != order.Buy &&
arg.Side != order.Sell {
return nil, errInvalidOrderSide
}
if arg.OrderType == "" {
return nil, errInvalidOrderType
}
if arg.Size <= 0 {
return nil, errMissingNewSize
}
var resp []AlgoOrder
err := ok.SendHTTPRequest(ctx, exchange.RestSpot, placeAlgoOrderEPL, http.MethodGet, algoTradeOrder, arg, &resp, true)
if err != nil {
return nil, err
}
if len(resp) == 1 {
return &resp[0], nil
}
return nil, errNoValidResponseFromServer
}
// PlaceStopOrder to place stop order
func (ok *Okx) PlaceStopOrder(ctx context.Context, arg *AlgoOrderParams) (*AlgoOrder, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.OrderType != "conditional" {
return nil, errInvalidOrderType
}
if arg.TakeProfitTriggerPrice == 0 {
return nil, errMissingTakeProfitTriggerPrice
}
if arg.TakeProfitTriggerPriceType == "" {
return nil, errMissingTakeProfitOrderPrice
}
return ok.PlaceAlgoOrder(ctx, arg)
}
// PlaceTrailingStopOrder to place trailing stop order
func (ok *Okx) PlaceTrailingStopOrder(ctx context.Context, arg *AlgoOrderParams) (*AlgoOrder, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.OrderType != "move_order_stop" {
return nil, errInvalidOrderType
}
if arg.CallbackRatio == 0 && arg.CallbackSpreadVariance == "" {
return nil, errors.New("either \"callbackRatio\" or \"callbackSpread\" is allowed to be passed")
}
return ok.PlaceAlgoOrder(ctx, arg)
}
// PlaceIcebergOrder to place iceburg algo order
func (ok *Okx) PlaceIcebergOrder(ctx context.Context, arg *AlgoOrderParams) (*AlgoOrder, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.OrderType != "iceberg" {
return nil, errInvalidOrderType
}
if arg.SizeLimit <= 0 {
return nil, errMissingSizeLimit
}
if arg.PriceLimit <= 0 {
return nil, errInvalidPriceLimit
}
return ok.PlaceAlgoOrder(ctx, arg)
}
// PlaceTWAPOrder to place TWAP algo orders
func (ok *Okx) PlaceTWAPOrder(ctx context.Context, arg *AlgoOrderParams) (*AlgoOrder, error) {
if arg.OrderType != "twap" {
return nil, errInvalidOrderType
}
if arg.SizeLimit <= 0 {
return nil, errMissingSizeLimit
}
if arg.PriceLimit <= 0 {
return nil, errInvalidPriceLimit
}
if ok.GetIntervalEnum(arg.TimeInterval, true) == "" {
return nil, errMissingIntervalValue
}
return ok.PlaceAlgoOrder(ctx, arg)
}
// TriggerAlgoOrder fetches algo trigger orders for SWAP market types.
func (ok *Okx) TriggerAlgoOrder(ctx context.Context, arg *AlgoOrderParams) (*AlgoOrder, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.OrderType != "trigger" {
return nil, errInvalidOrderType
}
if arg.TriggerPrice <= 0 {
return nil, errInvalidTriggerPrice
}
if arg.TriggerPriceType != "" &&
arg.TriggerPriceType != "last" &&
arg.TriggerPriceType != "index" &&
arg.TriggerPriceType != "mark" {
return nil, errors.New("only last, index and mark trigger price types are allowed")
}
return ok.PlaceAlgoOrder(ctx, arg)
}
// CancelAdvanceAlgoOrder Cancel unfilled algo orders
// A maximum of 10 orders can be canceled at a time.
// Request parameters should be passed in the form of an array.
func (ok *Okx) CancelAdvanceAlgoOrder(ctx context.Context, args []AlgoOrderCancelParams) ([]AlgoOrder, error) {
if args == nil {
return nil, errNilArgument
}
return ok.cancelAlgoOrder(ctx, args, cancelAdvancedAlgoOrder, cancelAdvanceAlgoOrderEPL)
}
// CancelAlgoOrder to cancel unfilled algo orders (not including Iceberg order, TWAP order, Trailing Stop order).
// A maximum of 10 orders can be canceled at a time.
// Request parameters should be passed in the form of an array.
func (ok *Okx) CancelAlgoOrder(ctx context.Context, args []AlgoOrderCancelParams) ([]AlgoOrder, error) {
if args == nil {
return nil, errNilArgument
}
return ok.cancelAlgoOrder(ctx, args, cancelAlgoOrder, cancelAlgoOrderEPL)
}
// cancelAlgoOrder to cancel unfilled algo orders.
func (ok *Okx) cancelAlgoOrder(ctx context.Context, args []AlgoOrderCancelParams, route string, rateLimit request.EndpointLimit) ([]AlgoOrder, error) {
for x := range args {
arg := args[x]
if arg.AlgoOrderID == "" {
return nil, errMissingAlgoOrderID
} else if arg.InstrumentID == "" {
return nil, errMissingInstrumentID
}
}
if len(args) == 0 {
return nil, errors.New("no parameter")
}
resp := []AlgoOrder{}
return resp, ok.SendHTTPRequest(ctx, exchange.RestSpot, rateLimit, http.MethodPost, route, &args, &resp, true)
}
// GetAlgoOrderList retrieves a list of untriggered Algo orders under the current account.
func (ok *Okx) GetAlgoOrderList(ctx context.Context, orderType, algoOrderID, clientOrderID, instrumentType, instrumentID string, after, before time.Time, limit int64) ([]AlgoOrderResponse, error) {
params := url.Values{}
orderType = strings.ToLower(orderType)
if orderType == "" {
return nil, errors.New("order type is required")
}
params.Set("ordType", orderType)
var resp []AlgoOrderResponse
if algoOrderID != "" {
params.Set("algoId", algoOrderID)
}
if clientOrderID != "" {
params.Set("clOrdId", clientOrderID)
}
instrumentType = strings.ToUpper(instrumentType)
if instrumentType != "" {
params.Set("instType", instrumentType)
}
if instrumentID != "" {
params.Set("instId", instrumentID)
}
if !before.IsZero() && before.Before(time.Now()) {
params.Set("before", strconv.FormatInt(before.UnixMilli(), 10))
}
if !after.IsZero() && after.Before(time.Now()) {
params.Set("after", strconv.FormatInt(after.UnixMilli(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
return resp, ok.SendHTTPRequest(ctx, exchange.RestSpot, getAlgoOrderListEPL, http.MethodGet, common.EncodeURLValues(getAlgoOrders, params), nil, &resp, true)
}
// GetAlgoOrderHistory load a list of all algo orders under the current account in the last 3 months.
func (ok *Okx) GetAlgoOrderHistory(ctx context.Context, orderType, state, algoOrderID, instrumentType, instrumentID string, after, before time.Time, limit int64) ([]AlgoOrderResponse, error) {
params := url.Values{}
if orderType == "" {
return nil, errors.New("order type is required")
}
params.Set("ordType", strings.ToLower(orderType))
var resp []AlgoOrderResponse
if algoOrderID == "" &&
state != "effective" &&
state != "order_failed" &&
state != "canceled" {
return nil, errMissingEitherAlgoIDOrState
}
if algoOrderID != "" {
params.Set("algoId", algoOrderID)
} else {
params.Set("state", state)
}
instrumentType = strings.ToUpper(instrumentType)
if instrumentType != "" {
params.Set("instType", instrumentType)
}
if instrumentID != "" {
params.Set("instId", instrumentID)
}
if !before.IsZero() && before.Before(time.Now()) {
params.Set("before", strconv.FormatInt(before.UnixMilli(), 10))
}
if !after.IsZero() && after.Before(time.Now()) {
params.Set("after", strconv.FormatInt(after.UnixMilli(), 10))
}
if limit > 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
return resp, ok.SendHTTPRequest(ctx, exchange.RestSpot, getAlgoOrderHistoryEPL, http.MethodGet, common.EncodeURLValues(algoOrderHistory, params), nil, &resp, true)
}
// GetEasyConvertCurrencyList retrieve list of small convertibles and mainstream currencies. Only applicable to the crypto balance less than $10.
func (ok *Okx) GetEasyConvertCurrencyList(ctx context.Context) (*EasyConvertDetail, error) {
var resp []EasyConvertDetail
if err := ok.SendHTTPRequest(ctx, exchange.RestSpot, getEasyConvertCurrencyListEPL, http.MethodGet,
easyConvertCurrencyList, nil, &resp, true); err != nil {
return nil, err
}
if len(resp) == 1 {
return &resp[0], nil
}
return nil, errNoValidResponseFromServer
}
// PlaceEasyConvert converts small currencies to mainstream currencies. Only applicable to the crypto balance less than $10.
func (ok *Okx) PlaceEasyConvert(ctx context.Context, arg PlaceEasyConvertParam) ([]EasyConvertItem, error) {