exchanges: Okx Update (#1420)

* update acccount ratelimits and added missing endpoints

* completed mapping missing trade accoung REST endpoints and Rate Limit

* added orderbook trading missing REST endpoints

* Added few missing endpoints and unit tests

* Completed grid trading and signal bot trading with unit tests

* Added Recurring Buy endpoints and corresponding unit tests

* Added copy trading endpoints and unit tests

* added newly added block trading and spread endpoints

* completed mapping spread endpoints

* Added new endpoints and unit tests

* Added round 1: Okx types and converts update.

* Update endpoints handling and types update

* Removed constants, updated unit tests, and updated endpoint methods

* Slight endpoint and unit test update

* Added spread and other websocket endpoints and update

* completed Spread WS Orderbook handler

* Added missing spread channels and handlers

* Adding Bussinss websocket and missing subscriptions, update unit tests, and endpoints

* Added spread endpoints to wrapper and unit tests update

* Added missing websocket subscriptions and copy trading endpoints

* Added missing endpoints and re-organize business websocket handlers

* Docs update

* Endpoints code updates

* types, unit test and endpoints update

* Minor unit tests update

* spelling fix

* fix unit test issues

* Updating unit tests error handling

* Updating unit tests error handling

* Unit tests assertion handling update

* Unit tests update

* Resolve linter issues

* linter issues fix

* Orderbook unit test error fix

* Minor fixes

* Change on test handling and types

* Updating unit tests and cleanups

* Fix unit test issues

* Add ratelimit test and update unit tests and methods

* Update method parameters and error declarations

* Added lending endpoints, unit tests, and update endpoint methods and error declarations

* Update ratelimiters, add missing lending and trading endpoints and unit tests

* Update websocket authentication and subscription handling

* Minor update to unit test and types

* Types, error handling, and other minor updates

* Update unit tests and endpoint functions

* error declarations update and unit tests

* Overall update on unit endpoint, unit tests, and types

* Adding review fixes

* Update on endpoints, order types, and unit tests

* Update unit tests and endpoint functions

* Update on endpoint and update missing parameters

* Implemented and tested newly added trading endpoints

* endpoints update and unit tests

* Update missing endpoints and update overall code

* added and testing funding and fiat related endpoints

* Update on convert and fiat related endpoints

* linter fix, types, endpoints, and unit tests update

* linter issues fix

* revert changes on tempos

* Fix Panic and update websocket auth calls handling

* config linter issue fix

* Fix panic issues and update unit tests

* Fix race condition, TestAllExchangeWrappers unit test issues

* Fix withdrawal manager test issue

* Rename ClosePositionForContractrID --> ClosePositionForContractID

* Rename ClosePositionForContractrID --> ClosePositionForContractID

* Fix error

* endpoints update and fix unit test issues

* added unit tests, updated comments, and code sections

* revert change in defaultSubscriptions

* few types comments update

* Minor changes

* remove lending endpoints

* rm mistakenly added code

* fix unit test

* minor unit test fix

* Adding offline error tests, update endpoints function, config update

* Update unit test coverage for offline error handliing

* Updating wrapper algo order coverage, endpoint calls, and unit tests

* Updating wrapper trade functions to accomodate algo orders

* update wrapper unit tests

* Fix wrapper order functions offline errors handling

* Tested and updated wrapper order functions

* Address review comments

* update order unit tests, and okx endpoint functions

* finalize affected order, endpoint, and margin endpoints

* Slight change on margin unit test

* fix margin unit test issues

* Minor change on unit test

* updates on contract settlement and future contract wrapper function

* add test coverage for contract functions and minor fix on wrapper

* Overall update and unit testing

* codespell, unit tests, type declaration and naming, and code-structure updates

* margin types value and validation function fix

* Update tests and helper funcs

* Improve test coverage

* helper functions and unit tests update

* Fix margin unit test

* Minor review updates

* minor fix on if statement

* Update helper functions

* error handling and functions naming update

* update comment

* minor error return fixes

* minor unit test fix

* Minor fix on spread websocket orders handling

* codespell fix

* skip orderbook depth with incomplete price

* skip orderbook depth with incomplete price
This commit is contained in:
Samuael A.
2025-02-10 02:44:48 +03:00
committed by GitHub
parent e6d456162a
commit 5c892307c7
29 changed files with 16407 additions and 7627 deletions

View File

@@ -68,6 +68,7 @@ var (
ErrCannotCalculateOffline = errors.New("cannot calculate offline, unsupported")
ErrNoResponse = errors.New("no response")
ErrTypeAssertFailure = errors.New("type assert failure")
ErrNoResults = errors.New("no results found")
ErrUnknownError = errors.New("unknown error")
ErrGettingField = errors.New("error getting field")
ErrSettingField = errors.New("error setting field")

File diff suppressed because one or more lines are too long

View File

@@ -3,10 +3,10 @@ package withdraw
import (
"context"
"database/sql"
"errors"
"time"
"github.com/gofrs/uuid"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/database"
modelPSQL "github.com/thrasher-corp/gocryptotrader/database/models/postgres"
@@ -19,11 +19,6 @@ import (
"github.com/thrasher-corp/sqlboiler/queries/qm"
)
var (
// ErrNoResults is the error returned if no results are found
ErrNoResults = errors.New("no results found")
)
// Event stores Withdrawal Response details in database
func Event(res *withdraw.Response) {
if database.DB.SQL == nil {
@@ -424,7 +419,7 @@ func getByColumns(q []qm.QueryMod) ([]*withdraw.Response, error) {
}
}
if len(resp) == 0 {
return nil, ErrNoResults
return nil, common.ErrNoResults
}
return resp, nil
}

View File

@@ -8,6 +8,7 @@ import (
"testing"
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/database"
"github.com/thrasher-corp/gocryptotrader/database/drivers"
@@ -159,7 +160,7 @@ func withdrawHelper(t *testing.T) {
_, err := GetEventByUUID(withdraw.DryRunID.String())
if err != nil {
if !errors.Is(err, ErrNoResults) {
if !errors.Is(err, common.ErrNoResults) {
t.Fatal(err)
}
}
@@ -181,7 +182,7 @@ func withdrawHelper(t *testing.T) {
if len(v) > 0 {
_, err = GetEventByUUID(v[0].ID.String())
if err != nil {
if !errors.Is(err, ErrNoResults) {
if !errors.Is(err, common.ErrNoResults) {
t.Error(err)
}
}

View File

@@ -41,6 +41,7 @@ const (
USDCMarginedFutures
FutureCombo
LinearContract
Spread
// Options asset consts must come below this comment for method `IsOptions`
Options
OptionCombo
@@ -58,6 +59,7 @@ const (
perpetualContract = "perpetualcontract"
perpetualSwap = "perpetualswap"
swap = "swap"
spread = "spread"
futures = "futures"
deliveryFutures = "delivery"
upsideProfitContract = "upsideprofitcontract"
@@ -73,7 +75,7 @@ const (
)
var (
supportedList = Items{Spot, Margin, CrossMargin, MarginFunding, Index, Binary, PerpetualContract, PerpetualSwap, Futures, DeliveryFutures, UpsideProfitContract, DownsideProfitContract, CoinMarginedFutures, USDTMarginedFutures, USDCMarginedFutures, Options, LinearContract, OptionCombo, FutureCombo}
supportedList = Items{Spot, Margin, CrossMargin, MarginFunding, Index, Binary, PerpetualContract, PerpetualSwap, Futures, DeliveryFutures, UpsideProfitContract, DownsideProfitContract, CoinMarginedFutures, USDTMarginedFutures, USDCMarginedFutures, Options, LinearContract, OptionCombo, FutureCombo, Spread}
)
// Supported returns a list of supported asset types
@@ -100,6 +102,8 @@ func (a Item) String() string {
return perpetualContract
case PerpetualSwap:
return perpetualSwap
case Spread:
return spread
case Futures:
return futures
case DeliveryFutures:
@@ -220,6 +224,8 @@ func New(input string) (Item, error) {
return PerpetualContract, nil
case perpetualSwap, swap:
return PerpetualSwap, nil
case spread:
return Spread, nil
case futures:
return Futures, nil
case upsideProfitContract:

View File

@@ -70,7 +70,7 @@ func TestIsValid(t *testing.T) {
func TestIsFutures(t *testing.T) {
t.Parallel()
valid := []Item{PerpetualContract, PerpetualSwap, Futures, DeliveryFutures, UpsideProfitContract, DownsideProfitContract, CoinMarginedFutures, USDTMarginedFutures, USDCMarginedFutures, FutureCombo, LinearContract}
valid := []Item{PerpetualContract, PerpetualSwap, Futures, DeliveryFutures, UpsideProfitContract, DownsideProfitContract, CoinMarginedFutures, USDTMarginedFutures, USDCMarginedFutures, FutureCombo, LinearContract, Spread}
for a := range All {
if slices.Contains(valid, a) {
require.Truef(t, a.IsFutures(), "IsFutures must return true for %s", a)
@@ -117,6 +117,7 @@ func TestNew(t *testing.T) {
{Input: "Future", Error: ErrNotSupported},
{Input: "option_combo", Expected: OptionCombo},
{Input: "future_combo", Expected: FutureCombo},
{Input: "spread", Expected: Spread},
{Input: "linearContract", Expected: LinearContract},
}

View File

@@ -34,6 +34,8 @@ func (t Mode) String() string {
return multiCollateralStr
case PortfolioMode:
return portfolioCollateralStr
case SpotFuturesMode:
return spotFuturesCollateralStr
case UnknownMode:
return unknownCollateralStr
}

View File

@@ -18,6 +18,9 @@ func TestValidCollateralType(t *testing.T) {
if !PortfolioMode.Valid() {
t.Fatal("expected 'true', received 'false'")
}
if !SpotFuturesMode.Valid() {
t.Fatal("expected 'true', received 'false'")
}
if UnsetMode.Valid() {
t.Fatal("expected 'false', received 'true'")
}

View File

@@ -24,20 +24,23 @@ const (
PortfolioMode
// UnknownMode has collateral allocated in an unknown manner at present, but is not unset
UnknownMode
// SpotFuturesMode has collateral allocated across spot and futures accounts
SpotFuturesMode
)
const (
unsetCollateralStr = "unset"
singleCollateralStr = "single"
multiCollateralStr = "multi"
portfolioCollateralStr = "portfolio"
unknownCollateralStr = "unknown"
unsetCollateralStr = "unset"
singleCollateralStr = "single"
multiCollateralStr = "multi"
portfolioCollateralStr = "portfolio"
spotFuturesCollateralStr = "spot_futures"
unknownCollateralStr = "unknown"
)
// ErrInvalidCollateralMode is returned when converting invalid string to collateral mode
var ErrInvalidCollateralMode = errors.New("invalid collateral mode")
var supportedCollateralModes = SingleMode | MultiMode | PortfolioMode
var supportedCollateralModes = SingleMode | MultiMode | PortfolioMode | SpotFuturesMode
// ByPosition shows how much collateral is used
// from positions

View File

@@ -1,6 +1,8 @@
package futures
import (
"errors"
"strings"
"time"
"github.com/shopspring/decimal"
@@ -9,6 +11,11 @@ import (
"github.com/thrasher-corp/gocryptotrader/exchanges/fundingrate"
)
// var error definitions
var (
ErrInvalidContractSettlementType = errors.New("invalid contract settlement type")
)
// Contract holds details on futures contracts
type Contract struct {
Exchange string
@@ -41,6 +48,7 @@ const (
Inverse
Quanto
LinearOrInverse
Hybrid
)
// String returns the string representation of a contract settlement type
@@ -56,11 +64,34 @@ func (d ContractSettlementType) String() string {
return "quanto"
case LinearOrInverse:
return "linearOrInverse"
case Hybrid:
return "hybrid"
default:
return "unknown"
}
}
// StringToContractSettlementType for converting case insensitive contract settlement type
func StringToContractSettlementType(cstype string) (ContractSettlementType, error) {
cstype = strings.ToLower(cstype)
switch cstype {
case UnsetSettlementType.String(), "":
return UnsetSettlementType, nil
case Linear.String():
return Linear, nil
case Inverse.String():
return Inverse, nil
case Quanto.String():
return Quanto, nil
case "linearorinverse":
return LinearOrInverse, nil
case Hybrid.String():
return Hybrid, nil
default:
return UnsetSettlementType, ErrInvalidContractSettlementType
}
}
// ContractType holds the various style of contracts offered by futures exchanges
type ContractType uint8

View File

@@ -0,0 +1,71 @@
package futures
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestStringToContractSettlementType(t *testing.T) {
t.Parallel()
contractSettlementTypesMap := map[string]struct {
CT ContractSettlementType
Error error
}{
"lInear": {Linear, nil},
"LINEAR": {Linear, nil},
"Inverse": {Inverse, nil},
"unset": {UnsetSettlementType, nil},
"hybRiD": {Hybrid, nil},
"LinearOrInverse": {LinearOrInverse, nil},
"": {UnsetSettlementType, nil},
"Quanto": {Quanto, nil},
"QUANTO": {Quanto, nil},
"Unknown": {UnsetSettlementType, ErrInvalidContractSettlementType},
}
for x, v := range contractSettlementTypesMap {
val, err := StringToContractSettlementType(x)
assert.Equal(t, v.CT, val)
assert.ErrorIs(t, err, v.Error)
}
}
func TestContractSettlementTypeString(t *testing.T) {
t.Parallel()
contractSettlementTypeToStringMap := map[ContractSettlementType]string{
UnsetSettlementType: "unset",
Linear: "linear",
Inverse: "inverse",
Quanto: "quanto",
LinearOrInverse: "linearOrInverse",
Hybrid: "hybrid",
ContractSettlementType(200): "unknown",
}
for k, v := range contractSettlementTypeToStringMap {
assert.Equal(t, v, k.String())
}
}
func TestContractTypeToString(t *testing.T) {
t.Parallel()
contractTypeToStringMap := map[ContractType]string{
Daily: "day",
Perpetual: "perpetual",
LongDated: "long_dated",
Weekly: "weekly",
Fortnightly: "fortnightly",
ThreeWeekly: "three-weekly",
Monthly: "monthly",
Quarterly: "quarterly",
SemiAnnually: "semi-annually",
HalfYearly: "half-yearly",
NineMonthly: "nine-monthly",
Yearly: "yearly",
Unknown: "unknown",
UnsetContractType: "unset",
ContractType(200): "unset",
}
for k, v := range contractTypeToStringMap {
assert.Equal(t, v, k.String())
}
}

View File

@@ -32,6 +32,10 @@ func (t Type) String() string {
return isolatedStr
case Multi:
return multiStr
case SpotIsolated:
return spotIsolatedStr
case NoMargin:
return cashStr
case Unknown:
return unknownStr
}
@@ -46,7 +50,7 @@ func (t Type) Upper() string {
// IsValidString checks to see if the supplied string is a valid margin type
func IsValidString(m string) bool {
switch strings.ToLower(m) {
case isolatedStr, multiStr, unsetStr, crossedStr, crossStr:
case isolatedStr, multiStr, unsetStr, crossedStr, crossStr, spotIsolatedStr, cashStr:
return true
}
return false
@@ -60,6 +64,10 @@ func StringToMarginType(m string) (Type, error) {
return Isolated, nil
case multiStr, crossedStr, crossStr:
return Multi, nil
case spotIsolatedStr:
return SpotIsolated, nil
case cashStr:
return NoMargin, nil
case "":
return Unset, nil
}

View File

@@ -2,161 +2,99 @@ package margin
import (
"encoding/json"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValid(t *testing.T) {
t.Parallel()
if !Isolated.Valid() {
t.Fatal("expected 'true', received 'false'")
}
if !Multi.Valid() {
t.Fatal("expected 'true', received 'false'")
}
if Unset.Valid() {
t.Fatal("expected 'false', received 'true'")
}
if Unknown.Valid() {
t.Fatal("expected 'false', received 'true'")
}
if Type(137).Valid() {
t.Fatal("expected 'false', received 'true'")
}
require.True(t, Isolated.Valid())
require.True(t, Multi.Valid())
require.True(t, NoMargin.Valid())
require.True(t, SpotIsolated.Valid())
require.False(t, Unset.Valid())
require.False(t, Unknown.Valid())
require.False(t, Type(137).Valid())
}
func TestUnmarshalJSON(t *testing.T) {
t.Parallel()
type martian struct {
M Type `json:"margin"`
}
var alien martian
jason := []byte(`{"margin":"isolated"}`)
err := json.Unmarshal(jason, &alien)
if err != nil {
t.Error(err)
}
if alien.M != Isolated {
t.Errorf("received '%v' expected 'isolated'", alien.M)
}
jason = []byte(`{"margin":"cross"}`)
err = json.Unmarshal(jason, &alien)
if err != nil {
t.Error(err)
}
if alien.M != Multi {
t.Errorf("received '%v' expected 'Multi'", alien.M)
}
jason = []byte(`{"margin":"hello moto"}`)
err = json.Unmarshal(jason, &alien)
if !errors.Is(err, ErrInvalidMarginType) {
t.Error(err)
}
if alien.M != Unknown {
t.Errorf("received '%v' expected 'isolated'", alien.M)
for name, tc := range map[string]struct {
in string
want Type
err error
}{
"isolated": {`{"margin":"isolated"}`, Isolated, nil},
"cross": {`{"margin":"cross"}`, Multi, nil},
"cash": {`{"margin":"cash"}`, NoMargin, nil},
"spotIsolated": {`{"margin":"spot_isolated"}`, SpotIsolated, nil},
"invalid": {`{"margin":"hello moto"}`, Unknown, ErrInvalidMarginType},
"unset": {`{"margin":""}`, Unset, nil},
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
var alien struct {
M Type `json:"margin"`
}
err := json.Unmarshal([]byte(tc.in), &alien)
assert.ErrorIs(t, err, tc.err)
assert.Equal(t, tc.want, alien.M)
})
}
}
func TestString(t *testing.T) {
t.Parallel()
if Unknown.String() != unknownStr {
t.Errorf("received '%v' expected '%v'", Unknown.String(), unknownStr)
}
if Isolated.String() != isolatedStr {
t.Errorf("received '%v' expected '%v'", Isolated.String(), isolatedStr)
}
if Multi.String() != multiStr {
t.Errorf("received '%v' expected '%v'", Multi.String(), multiStr)
}
if Unset.String() != unsetStr {
t.Errorf("received '%v' expected '%v'", Unset.String(), unsetStr)
}
assert.Equal(t, unknownStr, Unknown.String())
assert.Equal(t, isolatedStr, Isolated.String())
assert.Equal(t, multiStr, Multi.String())
assert.Equal(t, unsetStr, Unset.String())
assert.Equal(t, spotIsolatedStr, SpotIsolated.String())
assert.Equal(t, cashStr, NoMargin.String())
assert.Equal(t, "", Type(30).String())
}
func TestUpper(t *testing.T) {
t.Parallel()
if Unknown.Upper() != strings.ToUpper(unknownStr) {
t.Errorf("received '%v' expected '%v'", Unknown.String(), strings.ToUpper(unknownStr))
}
if Isolated.Upper() != strings.ToUpper(isolatedStr) {
t.Errorf("received '%v' expected '%v'", Isolated.String(), strings.ToUpper(isolatedStr))
}
if Multi.Upper() != strings.ToUpper(multiStr) {
t.Errorf("received '%v' expected '%v'", Multi.String(), strings.ToUpper(multiStr))
}
if Unset.Upper() != strings.ToUpper(unsetStr) {
t.Errorf("received '%v' expected '%v'", Unset.String(), strings.ToUpper(unsetStr))
}
assert.Equal(t, strings.ToUpper(unknownStr), Unknown.Upper())
assert.Equal(t, strings.ToUpper(isolatedStr), Isolated.Upper())
assert.Equal(t, strings.ToUpper(multiStr), Multi.Upper())
assert.Equal(t, strings.ToUpper(spotIsolatedStr), SpotIsolated.Upper())
assert.Equal(t, strings.ToUpper(cashStr), NoMargin.Upper())
assert.Equal(t, strings.ToUpper(unsetStr), Unset.Upper())
}
func TestIsValidString(t *testing.T) {
t.Parallel()
if IsValidString("lol") {
t.Fatal("expected 'false', received 'true'")
}
if !IsValidString("isolated") {
t.Fatal("expected 'true', received 'false'")
}
if !IsValidString("cross") {
t.Fatal("expected 'true', received 'false'")
}
if !IsValidString("multi") {
t.Fatal("expected 'true', received 'false'")
}
if !IsValidString("unset") {
t.Fatal("expected 'true', received 'false'")
}
if IsValidString("") {
t.Fatal("expected 'false', received 'true'")
}
if IsValidString("unknown") {
t.Fatal("expected 'false', received 'true'")
}
assert.False(t, IsValidString("lol"))
assert.True(t, IsValidString("spot_isolated"))
assert.True(t, IsValidString("cash"))
assert.True(t, IsValidString("isolated"))
assert.True(t, IsValidString("cross"))
assert.True(t, IsValidString("multi"))
assert.True(t, IsValidString(""))
assert.False(t, IsValidString("unknown"))
}
func TestStringToMarginType(t *testing.T) {
t.Parallel()
resp, err := StringToMarginType("lol")
if !errors.Is(err, ErrInvalidMarginType) {
t.Error(err)
}
if resp != Unknown {
t.Errorf("received '%v' expected '%v'", resp, Unknown)
}
resp, err = StringToMarginType("")
if err != nil {
t.Error(err)
}
if resp != Unset {
t.Errorf("received '%v' expected '%v'", resp, Unset)
}
resp, err = StringToMarginType("cross")
if err != nil {
t.Error(err)
}
if resp != Multi {
t.Errorf("received '%v' expected '%v'", resp, Multi)
}
resp, err = StringToMarginType("multi")
if err != nil {
t.Error(err)
}
if resp != Multi {
t.Errorf("received '%v' expected '%v'", resp, Multi)
}
resp, err = StringToMarginType("isolated")
if err != nil {
t.Error(err)
}
if resp != Isolated {
t.Errorf("received '%v' expected '%v'", resp, Isolated)
for label, v := range map[string]struct {
MarginType Type
Error error
}{
"lol": {Unknown, ErrInvalidMarginType},
"": {Unset, nil},
"cross": {Multi, nil},
"multi": {Multi, nil},
"isolated": {Isolated, nil},
"cash": {NoMargin, nil},
"spot_isolated": {SpotIsolated, nil},
} {
resp, err := StringToMarginType(label)
assert.ErrorIs(t, err, v.Error)
assert.Equal(t, v.MarginType.String(), resp.String())
}
}

View File

@@ -78,19 +78,25 @@ const (
// Multi means a margin trade is not isolated from other margin trades
// it can sometimes be referred to as "cross"
Multi
// Unknown is an unknown margin type but is not unset
// NoMargin indicates a trade that is conducted in non-margin mode, i.e., no borrowing of funds is involved.
NoMargin
// SpotIsolated indicates a margin shared amongst all spot trades but isolated from other assets
SpotIsolated
// Unknown indicates the margin type is set, but unknown
Unknown
)
var supported = Isolated | Multi
var supported = Isolated | Multi | NoMargin | SpotIsolated
const (
unsetStr = "unset"
isolatedStr = "isolated"
multiStr = "multi"
crossedStr = "crossed"
crossStr = "cross"
unknownStr = "unknown"
unsetStr = ""
isolatedStr = "isolated"
multiStr = "multi"
cashStr = "cash"
spotIsolatedStr = "spot_isolated"
crossedStr = "crossed"
crossStr = "cross"
unknownStr = "unknown"
)
// RateHistoryResponse has the funding rate details

193
exchanges/okx/helpers.go Normal file
View File

@@ -0,0 +1,193 @@
package okx
import (
"fmt"
"slices"
"strings"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
)
// orderTypeFromString returns order.Type instance from string
func orderTypeFromString(orderType string) (order.Type, error) {
orderType = strings.ToLower(orderType)
switch orderType {
case orderMarket:
return order.Market, nil
case orderLimit:
return order.Limit, nil
case orderPostOnly:
return order.PostOnly, nil
case orderFOK:
return order.FillOrKill, nil
case orderIOC:
return order.ImmediateOrCancel, nil
case orderOptimalLimitIOC:
return order.OptimalLimitIOC, nil
case "mmp":
return order.MarketMakerProtection, nil
case "mmp_and_post_only":
return order.MarketMakerProtectionAndPostOnly, nil
case "twap":
return order.TWAP, nil
case "move_order_stop":
return order.TrailingStop, nil
case "chase":
return order.Chase, nil
default:
return order.UnknownType, fmt.Errorf("%w %v", order.ErrTypeIsInvalid, orderType)
}
}
// orderTypeString returns a string representation of order.Type instance
func orderTypeString(orderType order.Type) (string, error) {
switch orderType {
case order.ImmediateOrCancel:
return "ioc", nil
case order.Market, order.Limit, order.Trigger,
order.PostOnly, order.FillOrKill, order.OptimalLimitIOC,
order.MarketMakerProtection, order.MarketMakerProtectionAndPostOnly,
order.Chase, order.TWAP, order.OCO:
return orderType.Lower(), nil
case order.ConditionalStop:
return "conditional", nil
case order.TrailingStop:
return "move_order_stop", nil
default:
return "", fmt.Errorf("%w: `%v`", order.ErrUnsupportedOrderType, orderType)
}
}
// getAssetsFromInstrumentID parses an instrument ID and returns a list of assets types
// that the instrument is associated with
func (ok *Okx) getAssetsFromInstrumentID(instrumentID string) ([]asset.Item, error) {
if instrumentID == "" {
return nil, errMissingInstrumentID
}
pf, err := ok.CurrencyPairs.GetFormat(asset.Spot, true)
if err != nil {
return nil, err
}
splitSymbol := strings.Split(instrumentID, pf.Delimiter)
if len(splitSymbol) <= 1 {
return nil, fmt.Errorf("%w %v", currency.ErrCurrencyNotSupported, instrumentID)
}
pair, err := currency.NewPairDelimiter(instrumentID, pf.Delimiter)
if err != nil {
return nil, fmt.Errorf("%w: `%s`", err, instrumentID)
}
switch {
case len(splitSymbol) == 2:
resp := make([]asset.Item, 0, 2)
enabled, err := ok.IsPairEnabled(pair, asset.Spot)
if err != nil {
return nil, err
}
if enabled {
resp = append(resp, asset.Spot)
}
enabled, err = ok.IsPairEnabled(pair, asset.Margin)
if err != nil {
return nil, err
}
if enabled {
resp = append(resp, asset.Margin)
}
if len(resp) > 0 {
return resp, nil
}
case len(splitSymbol) > 2:
var aType asset.Item
switch strings.ToLower(splitSymbol[len(splitSymbol)-1]) {
case "swap":
aType = asset.PerpetualSwap
case "c", "p":
aType = asset.Options
default:
aType = asset.Futures
}
enabled, err := ok.IsPairEnabled(pair, aType)
if err != nil {
return nil, err
} else if enabled {
return []asset.Item{aType}, nil
}
}
return nil, fmt.Errorf("%w: no asset enabled with instrument ID `%v`", asset.ErrNotEnabled, instrumentID)
}
// assetTypeFromInstrumentType returns an asset Item instance given and Instrument Type string
func assetTypeFromInstrumentType(instrumentType string) (asset.Item, error) {
switch strings.ToUpper(instrumentType) {
case instTypeSwap, instTypeContract:
return asset.PerpetualSwap, nil
case instTypeSpot:
return asset.Spot, nil
case instTypeMargin:
return asset.Margin, nil
case instTypeFutures:
return asset.Futures, nil
case instTypeOption:
return asset.Options, nil
case "":
return asset.Empty, nil
default:
return asset.Empty, asset.ErrNotSupported
}
}
func (ok *Okx) validatePlaceOrderParams(arg *PlaceOrderRequestParam) error {
if arg == nil {
return common.ErrNilPointer
}
if arg.InstrumentID == "" {
return errMissingInstrumentID
}
if arg.AssetType == asset.Spot || arg.AssetType == asset.Margin || arg.AssetType == asset.Empty {
arg.Side = strings.ToLower(arg.Side)
if arg.Side != order.Buy.Lower() && arg.Side != order.Sell.Lower() {
return fmt.Errorf("%w %s", order.ErrSideIsInvalid, arg.Side)
}
}
if !slices.Contains([]string{"", TradeModeCross, TradeModeIsolated, TradeModeCash}, arg.TradeMode) {
return fmt.Errorf("%w %s", errInvalidTradeModeValue, arg.TradeMode)
}
if arg.AssetType == asset.Futures || arg.AssetType == asset.PerpetualSwap {
arg.PositionSide = strings.ToLower(arg.PositionSide)
if !slices.Contains([]string{"long", "short"}, arg.PositionSide) {
return fmt.Errorf("%w: `%s`, 'long' or 'short' supported", order.ErrSideIsInvalid, arg.PositionSide)
}
}
arg.OrderType = strings.ToLower(arg.OrderType)
if !slices.Contains([]string{orderMarket, orderLimit, orderPostOnly, orderFOK, orderIOC, orderOptimalLimitIOC, "mmp", "mmp_and_post_only"}, arg.OrderType) {
return fmt.Errorf("%w: '%v'", order.ErrTypeIsInvalid, arg.OrderType)
}
if arg.Amount <= 0 {
return order.ErrAmountBelowMin
}
if !slices.Contains([]string{"", "base_ccy", "quote_ccy"}, arg.QuantityType) {
return errCurrencyQuantityTypeRequired
}
return nil
}
// assetTypeString returns a string representation of asset type
func assetTypeString(assetType asset.Item) (string, error) {
switch assetType {
case asset.Spot:
return "SPOT", nil
case asset.Margin:
return "MARGIN", nil
case asset.Futures:
return "FUTURES", nil
case asset.Options:
return "OPTION", nil
case asset.PerpetualSwap:
return "SWAP", nil
default:
return "", asset.ErrNotSupported
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,286 @@
package okx
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/gorilla/websocket"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/crypto"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
"github.com/thrasher-corp/gocryptotrader/exchanges/stream"
"github.com/thrasher-corp/gocryptotrader/exchanges/subscription"
"github.com/thrasher-corp/gocryptotrader/log"
)
const (
// okxBusinessWebsocketURL
okxBusinessWebsocketURL = "wss://ws.okx.com:8443/ws/v5/business"
)
var (
// defaultBusinessSubscribedChannels list of channels which are subscribed by default
defaultBusinessSubscribedChannels = []string{
okxSpreadPublicTrades,
okxSpreadOrderbook,
okxSpreadPublicTicker,
channelPublicStrucBlockTrades,
channelPublicBlockTrades,
channelBlockTickers,
}
// defaultBusinessAuthChannels list of authenticated channels
defaultBusinessAuthChannels = []string{
okxSpreadOrders,
okxSpreadTrades,
}
)
// WsConnectBusiness connects to a business websocket channel.
func (ok *Okx) WsConnectBusiness() error {
if !ok.Websocket.IsEnabled() || !ok.IsEnabled() {
return stream.ErrWebsocketNotEnabled
}
var dialer websocket.Dialer
dialer.ReadBufferSize = 8192
dialer.WriteBufferSize = 8192
ok.Websocket.Conn.SetURL(okxBusinessWebsocketURL)
err := ok.Websocket.Conn.Dial(&dialer, http.Header{})
if err != nil {
return err
}
ok.Websocket.Wg.Add(1)
go ok.wsReadData(ok.Websocket.Conn)
if ok.Verbose {
log.Debugf(log.ExchangeSys, "Successful connection to %v\n",
ok.Websocket.GetWebsocketURL())
}
ok.Websocket.Conn.SetupPingHandler(request.UnAuth, stream.PingHandler{
MessageType: websocket.TextMessage,
Message: pingMsg,
Delay: time.Second * 20,
})
if ok.Websocket.CanUseAuthenticatedEndpoints() {
err = ok.WsSpreadAuth(context.TODO())
if err != nil {
log.Errorf(log.ExchangeSys, "Error connecting auth socket: %s\n", err.Error())
ok.Websocket.SetCanUseAuthenticatedEndpoints(false)
}
}
return nil
}
// WsSpreadAuth will connect to Okx's Private websocket connection and Authenticate with a login payload.
func (ok *Okx) WsSpreadAuth(ctx context.Context) error {
if !ok.Websocket.CanUseAuthenticatedEndpoints() {
return fmt.Errorf("%v AuthenticatedWebsocketAPISupport not enabled", ok.Name)
}
creds, err := ok.GetCredentials(ctx)
if err != nil {
return err
}
ok.Websocket.SetCanUseAuthenticatedEndpoints(true)
timeUnix := time.Now()
signPath := "/users/self/verify"
hmac, err := crypto.GetHMAC(crypto.HashSHA256,
[]byte(strconv.FormatInt(timeUnix.Unix(), 10)+http.MethodGet+signPath),
[]byte(creds.Secret),
)
if err != nil {
return err
}
base64Sign := crypto.Base64Encode(hmac)
wsReq := WebsocketEventRequest{
Operation: operationLogin,
Arguments: []WebsocketLoginData{
{
APIKey: creds.Key,
Passphrase: creds.ClientID,
Timestamp: timeUnix.Unix(),
Sign: base64Sign,
},
},
}
err = ok.Websocket.AuthConn.SendJSONMessage(ctx, request.UnAuth, wsReq)
if err != nil {
return err
}
timer := time.NewTimer(ok.WebsocketResponseCheckTimeout)
randomID, err := common.GenerateRandomString(16)
if err != nil {
return fmt.Errorf("%w, generating random string for incoming websocket response failed", err)
}
wsResponse := make(chan *wsIncomingData)
ok.WsResponseMultiplexer.Register <- &wsRequestInfo{
ID: randomID,
Chan: wsResponse,
Event: operationLogin,
}
ok.WsRequestSemaphore <- 1
defer func() {
<-ok.WsRequestSemaphore
}()
defer func() { ok.WsResponseMultiplexer.Unregister <- randomID }()
for {
select {
case data := <-wsResponse:
if data.Event == operationLogin && data.StatusCode == "0" {
ok.Websocket.SetCanUseAuthenticatedEndpoints(true)
return nil
} else if data.Event == "error" &&
(data.StatusCode == "60022" || data.StatusCode == "60009") {
ok.Websocket.SetCanUseAuthenticatedEndpoints(false)
return fmt.Errorf("authentication failed with error: %v", ErrorCodes[data.StatusCode])
}
continue
case <-timer.C:
timer.Stop()
return fmt.Errorf("%s websocket connection: timeout waiting for response with an operation: %v",
ok.Name,
wsReq.Operation)
}
}
}
// GenerateDefaultBusinessSubscriptions returns a list of default subscriptions to business stream.
func (ok *Okx) GenerateDefaultBusinessSubscriptions() ([]subscription.Subscription, error) {
var subs []string
var subscriptions []subscription.Subscription
subs = append(subs, defaultBusinessSubscribedChannels...)
if ok.Websocket.CanUseAuthenticatedEndpoints() {
subs = append(subs, defaultBusinessAuthChannels...)
}
for c := range subs {
switch subs[c] {
case okxSpreadOrders,
okxSpreadTrades,
okxSpreadOrderbookLevel1,
okxSpreadOrderbook,
okxSpreadPublicTrades,
okxSpreadPublicTicker:
pairs, err := ok.GetEnabledPairs(asset.Spread)
if err != nil {
return nil, err
}
for p := range pairs {
subscriptions = append(subscriptions, subscription.Subscription{
Channel: subs[c],
Asset: asset.Spread,
Pairs: []currency.Pair{pairs[p]},
})
}
case channelPublicBlockTrades,
channelBlockTickers:
pairs, err := ok.GetEnabledPairs(asset.PerpetualSwap)
if err != nil {
return nil, err
}
for p := range pairs {
subscriptions = append(subscriptions, subscription.Subscription{
Channel: subs[c],
Asset: asset.PerpetualSwap,
Pairs: []currency.Pair{pairs[p]},
})
}
default:
subscriptions = append(subscriptions, subscription.Subscription{
Channel: subs[c],
})
}
}
return subscriptions, nil
}
// BusinessSubscribe sends a websocket subscription request to several channels to receive data.
func (ok *Okx) BusinessSubscribe(channelsToSubscribe subscription.List) error {
return ok.handleBusinessSubscription(operationSubscribe, channelsToSubscribe)
}
// BusinessUnsubscribe sends a websocket unsubscription request to several channels to receive data.
func (ok *Okx) BusinessUnsubscribe(channelsToUnsubscribe subscription.List) error {
return ok.handleBusinessSubscription(operationUnsubscribe, channelsToUnsubscribe)
}
// handleBusinessSubscription sends a subscription and unsubscription information thought the business websocket endpoint.
// as of the okx, exchange this endpoint sends subscription and unsubscription messages but with a list of json objects.
func (ok *Okx) handleBusinessSubscription(operation string, subscriptions subscription.List) error {
wsSubscriptionReq := WSSubscriptionInformationList{Operation: operation}
ok.WsRequestSemaphore <- 1
defer func() { <-ok.WsRequestSemaphore }()
var channels subscription.List
var authChannels subscription.List
var err error
for i := 0; i < len(subscriptions); i++ {
arg := SubscriptionInfo{
Channel: subscriptions[i].Channel,
}
var instrumentID, instrumentFamily, spreadID string
switch arg.Channel {
case okxSpreadOrders,
okxSpreadTrades,
okxSpreadOrderbookLevel1,
okxSpreadOrderbook,
okxSpreadPublicTrades,
okxSpreadPublicTicker:
spreadID = subscriptions[i].Pairs[0].String()
case channelPublicBlockTrades,
channelBlockTickers:
instrumentID = subscriptions[i].Pairs[0].String()
}
instrumentFamilyInterface, okay := subscriptions[i].Params["instFamily"]
if okay {
instrumentFamily, _ = instrumentFamilyInterface.(string)
}
arg.InstrumentFamily = instrumentFamily
arg.SpreadID = spreadID
arg.InstrumentID = instrumentID
var chunk []byte
channels = append(channels, subscriptions[i])
wsSubscriptionReq.Arguments = append(wsSubscriptionReq.Arguments, arg)
chunk, err = json.Marshal(wsSubscriptionReq)
if err != nil {
return err
}
if len(chunk) > maxConnByteLen {
i--
err = ok.Websocket.Conn.SendJSONMessage(context.Background(), request.UnAuth, wsSubscriptionReq)
if err != nil {
return err
}
if operation == operationUnsubscribe {
err = ok.Websocket.RemoveSubscriptions(ok.Websocket.Conn, channels...)
} else {
err = ok.Websocket.AddSuccessfulSubscriptions(ok.Websocket.Conn, channels...)
}
if err != nil {
return err
}
channels = subscription.List{}
wsSubscriptionReq.Arguments = []SubscriptionInfo{}
continue
}
}
err = ok.Websocket.Conn.SendJSONMessage(context.Background(), request.UnAuth, wsSubscriptionReq)
if err != nil {
return err
}
if operation == operationUnsubscribe {
channels = append(channels, authChannels...)
err = ok.Websocket.RemoveSubscriptions(ok.Websocket.Conn, channels...)
} else {
channels = append(channels, authChannels...)
err = ok.Websocket.AddSuccessfulSubscriptions(ok.Websocket.Conn, channels...)
}
return err
}

View File

@@ -130,7 +130,7 @@ var (
"59508": errors.New("the sub account of {0} is suspended"),
"59509": errors.New("account does not have permission to reset MMP status"),
"59510": errors.New("sub-account does not exist"),
"59512": errors.New("unable to set up this permission for ND brokers sub accounts. by default, all ND sub accounts can transfer funds out"),
"59512": errors.New("unable to set up this permission for 'ND' brokers sub accounts"),
"59601": errors.New("this sub-account name already exists, try another name"),
"59602": errors.New("number of API keys exceeds the limit"),
"59603": errors.New("number of sub accounts exceeds the limit"),

File diff suppressed because one or more lines are too long

View File

@@ -2,60 +2,11 @@ package okx
import (
"encoding/json"
"strconv"
"strings"
"time"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
)
type okxUnixMilliTime int64
// UnmarshalJSON deserializes byte data to okxunixMilliTime instance.
func (a *okxUnixMilliTime) UnmarshalJSON(data []byte) error {
var num string
err := json.Unmarshal(data, &num)
if err != nil {
return err
}
if num == "" {
return nil
}
value, err := strconv.ParseInt(num, 10, 64)
if err != nil {
return err
}
*a = okxUnixMilliTime(value)
return nil
}
// Time returns the time instance from unix value of integer.
func (a *okxUnixMilliTime) Time() time.Time {
return time.UnixMilli(int64(*a))
}
type okxTime struct {
time.Time
}
// UnmarshalJSON deserializes byte data to okxTime instance.
func (t *okxTime) UnmarshalJSON(data []byte) error {
var num string
err := json.Unmarshal(data, &num)
if err != nil {
return err
}
if num == "" {
return nil
}
value, err := strconv.ParseInt(num, 10, 64)
if err != nil {
return err
}
t.Time = time.UnixMilli(value)
return nil
}
// UnmarshalJSON decoder for OpenInterestResponse instance.
func (a *OpenInterest) UnmarshalJSON(data []byte) error {
type Alias OpenInterest
@@ -68,110 +19,8 @@ func (a *OpenInterest) UnmarshalJSON(data []byte) error {
return err
}
chil.InstrumentType = strings.ToUpper(chil.InstrumentType)
a.InstrumentType = GetAssetTypeFromInstrumentType(chil.InstrumentType)
return nil
}
// UnmarshalJSON deserializes JSON, and timestamp information.
func (a *LimitPriceResponse) UnmarshalJSON(data []byte) error {
type Alias LimitPriceResponse
chil := &struct {
*Alias
Timestamp int64 `json:"ts,string"`
}{
Alias: (*Alias)(a),
}
err := json.Unmarshal(data, chil)
if err != nil {
return err
}
return nil
}
// UnmarshalJSON deserializes JSON, and timestamp information.
func (a *OrderDetail) UnmarshalJSON(data []byte) error {
type Alias OrderDetail
chil := &struct {
*Alias
UpdateTime int64 `json:"uTime,string"`
CreationTime int64 `json:"cTime,string"`
FillTime string `json:"fillTime"`
}{
Alias: (*Alias)(a),
}
if err := json.Unmarshal(data, chil); err != nil {
return err
}
var err error
a.UpdateTime = time.UnixMilli(chil.UpdateTime)
a.CreationTime = time.UnixMilli(chil.CreationTime)
if chil.FillTime == "" {
a.FillTime = time.Time{}
} else {
var value int64
value, err = strconv.ParseInt(chil.FillTime, 10, 64)
if err != nil {
return err
}
a.FillTime = time.UnixMilli(value)
}
if err != nil {
return err
}
return nil
}
// UnmarshalJSON deserializes JSON, and timestamp information.
func (a *RfqTradeResponse) UnmarshalJSON(data []byte) error {
type Alias RfqTradeResponse
chil := &struct {
*Alias
CreationTime int64 `json:"cTime,string"`
}{
Alias: (*Alias)(a),
}
if err := json.Unmarshal(data, chil); err != nil {
return err
}
a.CreationTime = time.UnixMilli(chil.CreationTime)
return nil
}
// UnmarshalJSON deserializes JSON, and timestamp information.
func (a *BlockTicker) UnmarshalJSON(data []byte) error {
type Alias BlockTicker
chil := &struct {
*Alias
Timestamp int64 `json:"ts,string"`
}{
Alias: (*Alias)(a),
}
err := json.Unmarshal(data, chil)
if err != nil {
return err
}
return nil
}
// UnmarshalJSON deserializes JSON, and timestamp information.
func (a *UnitConvertResponse) UnmarshalJSON(data []byte) error {
type Alias UnitConvertResponse
chil := &struct {
*Alias
ConvertType int `json:"type,string"`
}{
Alias: (*Alias)(a),
}
if err := json.Unmarshal(data, chil); err != nil {
return err
}
switch chil.ConvertType {
case 1:
a.ConvertType = 1
case 2:
a.ConvertType = 2
}
return nil
a.InstrumentType, err = assetTypeFromInstrumentType(chil.InstrumentType)
return err
}
// MarshalJSON serialized QuoteLeg instance into bytes
@@ -190,67 +39,3 @@ func (a *QuoteLeg) MarshalJSON() ([]byte, error) {
}
return json.Marshal(chil)
}
// MarshalJSON serialized CreateQuoteParams instance into bytes
func (a *CreateQuoteParams) MarshalJSON() ([]byte, error) {
type Alias CreateQuoteParams
chil := &struct {
*Alias
QuoteSide string `json:"quoteSide"`
}{
Alias: (*Alias)(a),
}
if a.QuoteSide == order.Buy {
chil.QuoteSide = "buy"
} else {
chil.QuoteSide = "sell"
}
return json.Marshal(chil)
}
// MarshalJSON serializes the WebsocketLoginData object
func (a *WebsocketLoginData) MarshalJSON() ([]byte, error) {
type Alias WebsocketLoginData
return json.Marshal(struct {
Timestamp int64 `json:"timestamp"`
*Alias
}{
Timestamp: a.Timestamp.UTC().Unix(),
Alias: (*Alias)(a),
})
}
// UnmarshalJSON deserializes JSON, and timestamp information.
func (a *WebsocketLoginData) UnmarshalJSON(data []byte) error {
type Alias WebsocketLoginData
chil := &struct {
*Alias
Timestamp int64 `json:"timestamp"`
}{
Alias: (*Alias)(a),
}
if err := json.Unmarshal(data, chil); err != nil {
return err
}
a.Timestamp = time.UnixMilli(chil.Timestamp)
return nil
}
// UnmarshalJSON deserializes JSON, and timestamp information.
func (a *CurrencyOneClickRepay) UnmarshalJSON(data []byte) error {
type Alias CurrencyOneClickRepay
chil := &struct {
*Alias
UpdateTime int64 `json:"uTime,string"`
FillToSize string `json:"fillToSz"`
FillFromSize string `json:"fillFromSz"`
}{
Alias: (*Alias)(a),
}
err := json.Unmarshal(data, chil)
if err != nil {
return err
}
a.UpdateTime = time.Unix(chil.UpdateTime, 0)
return nil
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -16,198 +16,12 @@ const (
)
const (
// Trade Endpoints
placeOrderRate = 60
placeMultipleOrdersRate = 300
cancelOrderRate = 60
cancelMultipleOrdersRate = 300
amendOrderRate = 60
amendMultipleOrdersRate = 300
closePositionsRate = 20
getOrderDetails = 60
getOrderListRate = 60
getOrderHistory7DaysRate = 40
getOrderHistory3MonthsRate = 20
getTransactionDetail3DaysRate = 60
getTransactionDetail3MonthsRate = 10
placeAlgoOrderRate = 20
cancelAlgoOrderRate = 20
cancelAdvanceAlgoOrderRate = 20
getAlgoOrderListRate = 20
getAlgoOrderHistoryRate = 20
getEasyConvertCurrencyListRate = 1
placeEasyConvert = 1
getEasyConvertHistory = 1
oneClickRepayCurrencyList = 1
tradeOneClickRepay = 1
getOneClickRepayHistory = 1
// Block Trading endpoints
getCounterpartiesRate = 5
createRfqRate = 5
cancelRfqRate = 5
cancelMultipleRfqRate = 2
cancelAllRfqsRate = 2
executeQuoteRate = 2
setQuoteProducts = 5
restMMPStatus = 5
createQuoteRate = 50
cancelQuoteRate = 50
cancelMultipleQuotesRate = 2
cancelAllQuotes = 2
getRfqsRate = 2
getQuotesRate = 2
getTradesRate = 5
getTradesHistoryRate = 10
getPublicTradesRate = 5
// Funding
getCurrenciesRate = 6
getBalanceRate = 6
getAccountAssetValuationRate = 1
fundsTransferRate = 1
getFundsTransferStateRate = 1
assetBillsDetailsRate = 6
lightningDepositsRate = 2
getDepositAddressRate = 6
getDepositHistoryRate = 6
withdrawalRate = 6
lightningWithdrawalsRate = 2
cancelWithdrawalRate = 6
getWithdrawalHistoryRate = 6
smallAssetsConvertRate = 1
// Savings
getSavingBalanceRate = 6
savingsPurchaseRedemptionRate = 6
setLendingRateRate = 6
getLendingHistoryRate = 6
getPublicBorrowInfoRate = 6
getPublicBorrowHistoryRate = 6
// Convert
getConvertCurrenciesRate = 6
getConvertCurrencyPairRate = 6
estimateQuoteRate = 10
convertTradeRate = 10
getConvertHistoryRate = 6
// Account
getAccountBalanceRate = 10
getPositionsRate = 10
getPositionsHistoryRate = 1
getAccountAndPositionRiskRate = 10
getBillsDetailsRate = 6
getAccountConfigurationRate = 5
setPositionModeRate = 5
setLeverageRate = 20
getMaximumBuyOrSellAmountRate = 20
getMaximumAvailableTradableAmountRate = 20
increaseOrDecreaseMarginRate = 20
getLeverageRate = 20
getTheMaximumLoanOfInstrumentRate = 20
getFeeRatesRate = 5
getInterestAccruedDataRate = 5
getInterestRateRate = 5
setGreeksRate = 5
isolatedMarginTradingSettingsRate = 5
getMaximumWithdrawalsRate = 20
getAccountRiskStateRate = 10
vipLoansBorrowAndRepayRate = 6
getBorrowAnsRepayHistoryHistoryRate = 5
getBorrowInterestAndLimitRate = 5
positionBuilderRate = 2
getGreeksRate = 10
getPMLimitation = 10
// Sub Account Endpoints
viewSubaccountListRate = 2
resetSubAccountAPIKey = 1
getSubaccountTradingBalanceRate = 2
getSubaccountFundingBalanceRate = 2
historyOfSubaccountTransferRate = 6
masterAccountsManageTransfersBetweenSubaccountRate = 1
setPermissionOfTransferOutRate = 1
getCustodyTradingSubaccountListRate = 1
gridTradingRate = 20
amendGridAlgoOrderRate = 20
stopGridAlgoOrderRate = 20
getGridAlgoOrderListRate = 20
getGridAlgoOrderHistoryRate = 20
getGridAlgoOrderDetailsRate = 20
getGridAlgoSubOrdersRate = 20
getGridAlgoOrderPositionsRate = 20
spotGridWithdrawIncomeRate = 20
computeMarginBalance = 20
adjustMarginBalance = 20
getGridAIParameter = 20
// Earn
getOffer = 3
purchase = 2
redeem = 2
cancelPurchaseOrRedemption = 2
getEarnActiveOrders = 3
getFundingOrderHistory = 3
// Market Data
getTickersRate = 20
getIndexTickersRate = 20
getOrderBookRate = 20
getCandlesticksRate = 40
getCandlesticksHistoryRate = 20
getIndexCandlesticksRate = 20
getMarkPriceCandlesticksRate = 20
getTradesRequestRate = 100
get24HTotalVolumeRate = 2
getOracleRate = 1
getExchangeRateRequestRate = 1
getIndexComponentsRate = 20
getBlockTickersRate = 20
getBlockTradesRate = 20
// Public Data Endpoints
getInstrumentsRate = 20
getDeliveryExerciseHistoryRate = 40
getOpenInterestRate = 20
getFundingRate = 20
getFundingRateHistoryRate = 20
getLimitPriceRate = 20
getOptionMarketDateRate = 20
getEstimatedDeliveryExercisePriceRate = 10
getDiscountRateAndInterestFreeQuotaRate = 2
getSystemTimeRate = 10
getLiquidationOrdersRate = 40
getMarkPriceRate = 10
getPositionTiersRate = 10
getInterestRateAndLoanQuotaRate = 2
getInterestRateAndLoanQuoteForVIPLoansRate = 2
getUnderlyingRate = 20
getInsuranceFundRate = 10
unitConvertRate = 10
// Trading Data Endpoints
getSupportCoinRate = 5
getTakerVolumeRate = 5
getMarginLendingRatioRate = 5
getLongShortRatioRate = 5
getContractsOpenInterestAndVolumeRate = 5
getOptionsOpenInterestAndVolumeRate = 5
getPutCallRatioRate = 5
getOpenInterestAndVolumeRate = 5
getTakerFlowRate = 5
// Status Endpoints
getEventStatusRate = 1
)
const (
placeOrderEPL request.EndpointLimit = iota + 1 // This endpoint limit is shared with `Place order` Websocket API endpoints
placeMultipleOrdersEPL // This endpoint limit is shared with `Place multiple orders` Websocket API endpoints
cancelOrderEPL // This endpoint limit is shared with `Cancel order` Websocket API endpoints
cancelMultipleOrdersEPL // This endpoint limit is shared with `Cancel multiple orders` Websocket API endpoints
amendOrderEPL // This endpoint limit is shared with `Amend order` Websocket API endpoints
amendMultipleOrdersEPL // This endpoint limit is shared with `Amend multiple orders` Websocket API endpoints
placeOrderEPL request.EndpointLimit = iota
placeMultipleOrdersEPL
cancelOrderEPL
cancelMultipleOrdersEPL
amendOrderEPL
amendMultipleOrdersEPL
closePositionEPL
getOrderDetEPL
getOrderListEPL
@@ -215,9 +29,16 @@ const (
getOrderHistory3MonthsEPL
getTransactionDetail3DaysEPL
getTransactionDetail3MonthsEPL
setTransactionDetail2YearIntervalEPL
getTransactionDetailLast2YearsEPL
cancelAllAfterCountdownEPL
getTradeAccountRateLimitEPL
orderPreCheckEPL
placeAlgoOrderEPL
cancelAlgoOrderEPL
amendAlgoOrderEPL
cancelAdvanceAlgoOrderEPL
getAlgoOrderDetailEPL
getAlgoOrderListEPL
getAlgoOrderHistoryEPL
getEasyConvertCurrencyListEPL
@@ -226,25 +47,32 @@ const (
getOneClickRepayHistoryEPL
oneClickRepayCurrencyListEPL
tradeOneClickRepayEPL
massCancemMMPOrderEPL
getCounterpartiesEPL
createRfqEPL
cancelRfqEPL
cancelMultipleRfqEPL
cancelAllRfqsEPL
createRFQEPL
cancelRFQEPL
cancelMultipleRFQEPL
cancelAllRFQsEPL
executeQuoteEPL
getQuoteProductsEPL
setQuoteProductsEPL
restMMPStatusEPL
resetRFQMMPEPL
setMMPEPL
getMMPConfigEPL
createQuoteEPL
cancelQuoteEPL
cancelMultipleQuotesEPL
cancelAllQuotesEPL
getRfqsEPL
getRFQsEPL
getQuotesEPL
getTradesEPL
getTradesHistoryEPL
optionInstrumentTradeFamilyEPL
optionTradesEPL
getPublicTradesEPL
getCurrenciesEPL
getBalanceEPL
getNonTradableAssetsEPL
getAccountAssetValuationEPL
fundsTransferEPL
getFundsTransferStateEPL
@@ -256,7 +84,9 @@ const (
lightningWithdrawalsEPL
cancelWithdrawalEPL
getWithdrawalHistoryEPL
getDepositWithdrawalStatusEPL
smallAssetsConvertEPL
getPublicExchangeListEPL
getSavingBalanceEPL
savingsPurchaseRedemptionEPL
setLendingRateEPL
@@ -264,6 +94,8 @@ const (
getPublicBorrowInfoEPL
getPublicBorrowHistoryEPL
getConvertCurrenciesEPL
getMonthlyStatementEPL
applyForMonthlyStatementEPL
getConvertCurrencyPairEPL
estimateQuoteEPL
convertTradeEPL
@@ -273,6 +105,9 @@ const (
getPositionsHistoryEPL
getAccountAndPositionRiskEPL
getBillsDetailsEPL
getBillsDetailArchiveEPL
billHistoryArchiveEPL
getBillHistoryArchiveEPL
getAccountConfigurationEPL
setPositionModeEPL
setLeverageEPL
@@ -280,6 +115,7 @@ const (
getMaximumAvailableTradableAmountEPL
increaseOrDecreaseMarginEPL
getLeverageEPL
getLeverateEstimatedInfoEPL
getTheMaximumLoanOfInstrumentEPL
getFeeRatesEPL
getInterestAccruedDataEPL
@@ -288,23 +124,55 @@ const (
isolatedMarginTradingSettingsEPL
getMaximumWithdrawalsEPL
getAccountRiskStateEPL
manualBorrowAndRepayEPL
getBorrowAndRepayHistoryEPL
vipLoansBorrowAnsRepayEPL
getBorrowAnsRepayHistoryHistoryEPL
getVIPInterestAccruedDataEPL
getVIPInterestDeductedDataEPL
getVIPLoanOrderListEPL
getVIPLoanOrderDetailEPL
getBorrowInterestAndLimitEPL
getFixedLoanBorrowLimitEPL
getFixedLoanBorrowQuoteEPL
placeFixedLoanBorrowingOrderEPL
amendFixedLaonBorrowingOrderEPL
manualRenewFixedLoanBorrowingOrderEPL
repayFixedLoanBorrowingOrderEPL
convertFixedLoanToMarketLoanEPL
reduceLiabilitiesForFixedLoanEPL
getFixedLoanBorrowOrderListEPL
manualBorrowOrRepayEPL
setAutoRepayEPL
getBorrowRepayHistoryEPL
newPositionBuilderEPL
setRiskOffsetAmountEPL
positionBuilderEPL
getGreeksEPL
getPMLimitationEPL
setRiskOffsetLimiterEPL
activateOptionEPL
setAutoLoanEPL
setAccountLevelEPL
resetMMPStatusEPL
viewSubaccountListEPL
resetSubAccountAPIKeyEPL
getSubaccountTradingBalanceEPL
getSubaccountFundingBalanceEPL
getSubAccountMaxWithdrawalEPL
historyOfSubaccountTransferEPL
managedSubAccountTransferEPL
masterAccountsManageTransfersBetweenSubaccountEPL
setPermissionOfTransferOutEPL
getCustodyTradingSubaccountListEPL
setSubAccountVIPLoanAllocationEPL
getSubAccountBorrowInterestAndLimitEPL
gridTradingEPL
amendGridAlgoOrderEPL
stopGridAlgoOrderEPL
closePositionForForContractGridEPL
cancelClosePositionOrderForContractGridEPL
instantTriggerGridAlgoOrderEPL
getGridAlgoOrderListEPL
getGridAlgoOrderHistoryEPL
getGridAlgoOrderDetailsEPL
@@ -314,16 +182,61 @@ const (
computeMarginBalanceEPL
adjustMarginBalanceEPL
getGridAIParameterEPL
computeMinInvestmentEPL
rsiBackTestingEPL
signalBotOrderDetailsEPL
signalBotOrderPositionsEPL
signalBotSubOrdersEPL
signalBotEventHistoryEPL
placeRecurringBuyOrderEPL
amendRecurringBuyOrderEPL
stopRecurringBuyOrderEPL
getRecurringBuyOrderListEPL
getRecurringBuyOrderHistoryEPL
getRecurringBuyOrderDetailEPL
getRecurringBuySubOrdersEPL
getExistingLeadingPositionsEPL
getLeadingPositionHistoryEPL
placeLeadingStopOrderEPL
closeLeadingPositionEPL
getLeadingInstrumentsEPL
getProfitSharingLimitEPL
getTotalProfitSharingEPL
setFirstCopySettingsEPL
amendFirstCopySettingsEPL
stopCopyingEPL
getCopySettingsEPL
getMultipleLeveragesEPL
setBatchLeverageEPL
getMyLeadTradersEPL
getLeadTraderRanksEPL
getLeadTraderWeeklyPNLEPL
getLeadTraderDailyPNLEPL
getLeadTraderStatsEPL
getLeadTraderCurrencyPreferencesEPL
getTraderCurrentLeadPositionsEPL
getLeadTraderLeadPositionHistoryEPL
getOfferEPL
purchaseEPL
redeemEPL
cancelPurchaseOrRedemptionEPL
getEarnActiveOrdersEPL
getFundingOrderHistoryEPL
getProductInfoEPL
purchaseETHStakingEPL
redeemETHStakingEPL
getBETHBalanceEPL
getPurchaseRedeemHistoryEPL
getAPYHistoryEPL
getTickersEPL
getTickerEPL
getPremiumHistoryEPL
getIndexTickersEPL
getOrderBookEPL
getCandlestickEPL
getOrderBookLiteEPL
getCandlesticksEPL
getTradesRequestEPL
get24HTotalVolumeEPL
getOracleEPL
@@ -331,6 +244,19 @@ const (
getIndexComponentsEPL
getBlockTickersEPL
getBlockTradesEPL
placeSpreadOrderEPL
cancelSpreadOrderEPL
cancelAllSpreadOrderEPL
amendSpreadOrderEPL
getSpreadOrderDetailsEPL
getSpreadOrderTradesEPL
getSpreadsEPL
getSpreadOrderbookEPL
getSpreadTickerEPL
getSpreadPublicTradesEPL
cancelAllSpreadOrdersAfterEPL
getActiveSpreadOrdersEPL
getSpreadOrders7DaysEPL
getInstrumentsEPL
getDeliveryExerciseHistoryEPL
getOpenInterestEPL
@@ -349,6 +275,8 @@ const (
getUnderlyingEPL
getInsuranceFundEPL
unitConvertEPL
optionTickBandsEPL
getIndexTickerEPL
getSupportCoinEPL
getTakerVolumeEPL
getMarginLendingRatioEPL
@@ -360,192 +288,377 @@ const (
getTakerFlowEPL
getEventStatusEPL
getCandlestickHistoryEPL
getIndexCandlestickEPL
getIndexCandlesticksEPL
getIndexCandlesticksHistoryEPL
getMarkPriceCandlesticksHistoryEPL
getEconomicCalendarEPL
getEstimatedDeliveryPriceEPL
getAffilateInviteesDetailEPL
getUserAffiliateRebateInformationEPL
placeLendingOrderEPL
amendLendingOrderEPL
lendingOrderListEPL
lendingSubOrderListEPL
lendingPublicOfferEPL
lendingAPYHistoryEPL
lendingVolumeEPL
rubikGetContractOpenInterestHistoryEPL
rubikContractTakerVolumeEPL
rubikTopTradersContractLongShortRatioEPL
getAccountInstrumentsEPL
getAnnouncementsEPL
getAnnouncementTypeEPL
getDepositOrderDetailEPL
getDepositOrderHistoryEPL
getWithdrawalOrderDetailEPL
getFiatWithdrawalOrderHistoryEPL
cancelWithdrawalOrderEPL
createWithdrawalOrderEPL
getWithdrawalPaymentMethodsEPL
getFiatDepositPaymentMethodsEPL
)
// GetRateLimit returns a RateLimit instance, which implements the request.Limiter interface.
func GetRateLimit() request.RateLimitDefinitions {
return request.RateLimitDefinitions{
// Trade Endpoints
placeOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, placeOrderRate, 1),
placeMultipleOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, placeMultipleOrdersRate, 1),
cancelOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, cancelOrderRate, 1),
cancelMultipleOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, cancelMultipleOrdersRate, 1),
amendOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, amendOrderRate, 1),
amendMultipleOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, amendMultipleOrdersRate, 1),
closePositionEPL: request.NewRateLimitWithWeight(twoSecondsInterval, closePositionsRate, 1),
getOrderDetEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getOrderDetails, 1),
getOrderListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getOrderListRate, 1),
getOrderHistory7DaysEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getOrderHistory7DaysRate, 1),
getOrderHistory3MonthsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getOrderHistory3MonthsRate, 1),
getTransactionDetail3DaysEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getTransactionDetail3DaysRate, 1),
getTransactionDetail3MonthsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getTransactionDetail3MonthsRate, 1),
placeAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, placeAlgoOrderRate, 1),
cancelAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, cancelAlgoOrderRate, 1),
cancelAdvanceAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, cancelAdvanceAlgoOrderRate, 1),
getAlgoOrderListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getAlgoOrderListRate, 1),
getAlgoOrderHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getAlgoOrderHistoryRate, 1),
getEasyConvertCurrencyListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getEasyConvertCurrencyListRate, 1),
placeEasyConvertEPL: request.NewRateLimitWithWeight(twoSecondsInterval, placeEasyConvert, 1),
getEasyConvertHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getEasyConvertHistory, 1),
getOneClickRepayHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getOneClickRepayHistory, 1),
oneClickRepayCurrencyListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, oneClickRepayCurrencyList, 1),
tradeOneClickRepayEPL: request.NewRateLimitWithWeight(twoSecondsInterval, tradeOneClickRepay, 1),
placeOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 60, 1),
placeMultipleOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 4, 1),
cancelOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 60, 1),
cancelMultipleOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 300, 1),
amendOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 60, 1),
amendMultipleOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 4, 1),
closePositionEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getOrderDetEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 60, 1),
getOrderListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 60, 1),
getOrderHistory7DaysEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 40, 1),
getOrderHistory3MonthsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getTransactionDetail3DaysEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 60, 1),
getTransactionDetail3MonthsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
setTransactionDetail2YearIntervalEPL: request.NewRateLimitWithWeight(time.Hour*24, 5, 1),
getTransactionDetailLast2YearsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
cancelAllAfterCountdownEPL: request.NewRateLimitWithWeight(oneSecondInterval, 1, 1),
getTradeAccountRateLimitEPL: request.NewRateLimitWithWeight(oneSecondInterval, 1, 1),
orderPreCheckEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
placeAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
cancelAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
amendAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
cancelAdvanceAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getAlgoOrderDetailEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getAlgoOrderListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getAlgoOrderHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getEasyConvertCurrencyListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 1, 1),
placeEasyConvertEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 1, 1),
getEasyConvertHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 1, 1),
getOneClickRepayHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 1, 1),
oneClickRepayCurrencyListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 1, 1),
tradeOneClickRepayEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 1, 1),
massCancemMMPOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
// Block Trading endpoints
getCounterpartiesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getCounterpartiesRate, 1),
createRfqEPL: request.NewRateLimitWithWeight(twoSecondsInterval, createRfqRate, 1),
cancelRfqEPL: request.NewRateLimitWithWeight(twoSecondsInterval, cancelRfqRate, 1),
cancelMultipleRfqEPL: request.NewRateLimitWithWeight(twoSecondsInterval, cancelMultipleRfqRate, 1),
cancelAllRfqsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, cancelAllRfqsRate, 1),
executeQuoteEPL: request.NewRateLimitWithWeight(threeSecondsInterval, executeQuoteRate, 1),
setQuoteProductsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, setQuoteProducts, 1),
restMMPStatusEPL: request.NewRateLimitWithWeight(twoSecondsInterval, restMMPStatus, 1),
createQuoteEPL: request.NewRateLimitWithWeight(twoSecondsInterval, createQuoteRate, 1),
cancelQuoteEPL: request.NewRateLimitWithWeight(twoSecondsInterval, cancelQuoteRate, 1),
cancelMultipleQuotesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, cancelMultipleQuotesRate, 1),
cancelAllQuotesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, cancelAllQuotes, 1),
getRfqsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getRfqsRate, 1),
getQuotesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getQuotesRate, 1),
getTradesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getTradesRate, 1),
getTradesHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getTradesHistoryRate, 1),
getPublicTradesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getPublicTradesRate, 1),
getCounterpartiesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
createRFQEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
cancelRFQEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
cancelMultipleRFQEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
cancelAllRFQsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
executeQuoteEPL: request.NewRateLimitWithWeight(threeSecondsInterval, 2, 1),
getQuoteProductsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
setQuoteProductsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
resetMMPStatusEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
resetRFQMMPEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
setMMPEPL: request.NewRateLimitWithWeight(tenSecondsInterval, 2, 1),
getMMPConfigEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
createQuoteEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 50, 1),
cancelQuoteEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 50, 1),
cancelMultipleQuotesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
cancelAllQuotesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
getRFQsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
getQuotesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
getTradesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getTradesHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
optionInstrumentTradeFamilyEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
optionTradesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getPublicTradesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
// Funding
getCurrenciesEPL: request.NewRateLimitWithWeight(oneSecondInterval, getCurrenciesRate, 1),
getBalanceEPL: request.NewRateLimitWithWeight(oneSecondInterval, getBalanceRate, 1),
getAccountAssetValuationEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getAccountAssetValuationRate, 1),
fundsTransferEPL: request.NewRateLimitWithWeight(oneSecondInterval, fundsTransferRate, 1),
getFundsTransferStateEPL: request.NewRateLimitWithWeight(oneSecondInterval, getFundsTransferStateRate, 1),
assetBillsDetailsEPL: request.NewRateLimitWithWeight(oneSecondInterval, assetBillsDetailsRate, 1),
lightningDepositsEPL: request.NewRateLimitWithWeight(oneSecondInterval, lightningDepositsRate, 1),
getDepositAddressEPL: request.NewRateLimitWithWeight(oneSecondInterval, getDepositAddressRate, 1),
getDepositHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, getDepositHistoryRate, 1),
withdrawalEPL: request.NewRateLimitWithWeight(oneSecondInterval, withdrawalRate, 1),
lightningWithdrawalsEPL: request.NewRateLimitWithWeight(oneSecondInterval, lightningWithdrawalsRate, 1),
cancelWithdrawalEPL: request.NewRateLimitWithWeight(oneSecondInterval, cancelWithdrawalRate, 1),
getWithdrawalHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, getWithdrawalHistoryRate, 1),
smallAssetsConvertEPL: request.NewRateLimitWithWeight(oneSecondInterval, smallAssetsConvertRate, 1),
getSavingBalanceEPL: request.NewRateLimitWithWeight(oneSecondInterval, getSavingBalanceRate, 1),
savingsPurchaseRedemptionEPL: request.NewRateLimitWithWeight(oneSecondInterval, savingsPurchaseRedemptionRate, 1),
setLendingRateEPL: request.NewRateLimitWithWeight(oneSecondInterval, setLendingRateRate, 1),
getLendingHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, getLendingHistoryRate, 1),
getPublicBorrowInfoEPL: request.NewRateLimitWithWeight(oneSecondInterval, getPublicBorrowInfoRate, 1),
getPublicBorrowHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, getPublicBorrowHistoryRate, 1),
getCurrenciesEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getBalanceEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getNonTradableAssetsEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getAccountAssetValuationEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 1, 1),
fundsTransferEPL: request.NewRateLimitWithWeight(oneSecondInterval, 1, 1),
getFundsTransferStateEPL: request.NewRateLimitWithWeight(oneSecondInterval, 1, 1),
assetBillsDetailsEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
lightningDepositsEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
getDepositAddressEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getDepositHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
withdrawalEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
lightningWithdrawalsEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
cancelWithdrawalEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getWithdrawalHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getDepositWithdrawalStatusEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 1, 1),
smallAssetsConvertEPL: request.NewRateLimitWithWeight(oneSecondInterval, 1, 1),
getPublicExchangeListEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getSavingBalanceEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
savingsPurchaseRedemptionEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
setLendingRateEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getLendingHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getPublicBorrowInfoEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getPublicBorrowHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
// Convert
getConvertCurrenciesEPL: request.NewRateLimitWithWeight(oneSecondInterval, getConvertCurrenciesRate, 1),
getConvertCurrencyPairEPL: request.NewRateLimitWithWeight(oneSecondInterval, getConvertCurrencyPairRate, 1),
estimateQuoteEPL: request.NewRateLimitWithWeight(oneSecondInterval, estimateQuoteRate, 1),
convertTradeEPL: request.NewRateLimitWithWeight(oneSecondInterval, convertTradeRate, 1),
getConvertHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, getConvertHistoryRate, 1),
getMonthlyStatementEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
applyForMonthlyStatementEPL: request.NewRateLimitWithWeight(time.Hour*24*30, 20, 1),
getConvertCurrenciesEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getConvertCurrencyPairEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
estimateQuoteEPL: request.NewRateLimitWithWeight(oneSecondInterval, 10, 1),
convertTradeEPL: request.NewRateLimitWithWeight(oneSecondInterval, 10, 1),
getConvertHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
// Account
getAccountBalanceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getAccountBalanceRate, 1),
getPositionsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getPositionsRate, 1),
getPositionsHistoryEPL: request.NewRateLimitWithWeight(tenSecondsInterval, getPositionsHistoryRate, 1),
getAccountAndPositionRiskEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getAccountAndPositionRiskRate, 1),
getBillsDetailsEPL: request.NewRateLimitWithWeight(oneSecondInterval, getBillsDetailsRate, 1),
getAccountConfigurationEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getAccountConfigurationRate, 1),
setPositionModeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, setPositionModeRate, 1),
setLeverageEPL: request.NewRateLimitWithWeight(twoSecondsInterval, setLeverageRate, 1),
getMaximumBuyOrSellAmountEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getMaximumBuyOrSellAmountRate, 1),
getMaximumAvailableTradableAmountEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getMaximumAvailableTradableAmountRate, 1),
increaseOrDecreaseMarginEPL: request.NewRateLimitWithWeight(twoSecondsInterval, increaseOrDecreaseMarginRate, 1),
getLeverageEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getLeverageRate, 1),
getTheMaximumLoanOfInstrumentEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getTheMaximumLoanOfInstrumentRate, 1),
getFeeRatesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getFeeRatesRate, 1),
getInterestAccruedDataEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getInterestAccruedDataRate, 1),
getInterestRateEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getInterestRateRate, 1),
setGreeksEPL: request.NewRateLimitWithWeight(twoSecondsInterval, setGreeksRate, 1),
isolatedMarginTradingSettingsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, isolatedMarginTradingSettingsRate, 1),
getMaximumWithdrawalsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getMaximumWithdrawalsRate, 1),
getAccountRiskStateEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getAccountRiskStateRate, 1),
vipLoansBorrowAnsRepayEPL: request.NewRateLimitWithWeight(oneSecondInterval, vipLoansBorrowAndRepayRate, 1),
getBorrowAnsRepayHistoryHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getBorrowAnsRepayHistoryHistoryRate, 1),
getBorrowInterestAndLimitEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getBorrowInterestAndLimitRate, 1),
positionBuilderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, positionBuilderRate, 1),
getGreeksEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getGreeksRate, 1),
getPMLimitationEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getPMLimitation, 1),
getAccountBalanceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getPositionsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getPositionsHistoryEPL: request.NewRateLimitWithWeight(tenSecondsInterval, 1, 1),
getAccountAndPositionRiskEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getBillsDetailsEPL: request.NewRateLimitWithWeight(oneSecondInterval, 5, 1),
getBillsDetailArchiveEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
billHistoryArchiveEPL: request.NewRateLimitWithWeight(time.Hour*24, 12, 1),
getBillHistoryArchiveEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getAccountConfigurationEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
setPositionModeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
setLeverageEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getMaximumBuyOrSellAmountEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getMaximumAvailableTradableAmountEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
increaseOrDecreaseMarginEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getLeverageEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getLeverateEstimatedInfoEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getTheMaximumLoanOfInstrumentEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getFeeRatesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getInterestAccruedDataEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getInterestRateEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
setGreeksEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
isolatedMarginTradingSettingsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getMaximumWithdrawalsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getAccountRiskStateEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
manualBorrowAndRepayEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getBorrowAndRepayHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
vipLoansBorrowAnsRepayEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getBorrowAnsRepayHistoryHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getVIPInterestAccruedDataEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getVIPInterestDeductedDataEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getVIPLoanOrderListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getVIPLoanOrderDetailEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getBorrowInterestAndLimitEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getFixedLoanBorrowLimitEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getFixedLoanBorrowQuoteEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
placeFixedLoanBorrowingOrderEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
amendFixedLaonBorrowingOrderEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
manualRenewFixedLoanBorrowingOrderEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
repayFixedLoanBorrowingOrderEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
convertFixedLoanToMarketLoanEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
reduceLiabilitiesForFixedLoanEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
getFixedLoanBorrowOrderListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
manualBorrowOrRepayEPL: request.NewRateLimitWithWeight(oneSecondInterval, 1, 1),
setAutoRepayEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getBorrowRepayHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
newPositionBuilderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
setRiskOffsetAmountEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
positionBuilderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
getGreeksEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getPMLimitationEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
setRiskOffsetLimiterEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
activateOptionEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
setAutoLoanEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
setAccountLevelEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
// Sub Account Endpoints
viewSubaccountListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, viewSubaccountListRate, 1),
resetSubAccountAPIKeyEPL: request.NewRateLimitWithWeight(oneSecondInterval, resetSubAccountAPIKey, 1),
getSubaccountTradingBalanceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getSubaccountTradingBalanceRate, 1),
getSubaccountFundingBalanceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getSubaccountFundingBalanceRate, 1),
historyOfSubaccountTransferEPL: request.NewRateLimitWithWeight(oneSecondInterval, historyOfSubaccountTransferRate, 1),
masterAccountsManageTransfersBetweenSubaccountEPL: request.NewRateLimitWithWeight(oneSecondInterval, masterAccountsManageTransfersBetweenSubaccountRate, 1),
setPermissionOfTransferOutEPL: request.NewRateLimitWithWeight(oneSecondInterval, setPermissionOfTransferOutRate, 1),
getCustodyTradingSubaccountListEPL: request.NewRateLimitWithWeight(oneSecondInterval, getCustodyTradingSubaccountListRate, 1),
viewSubaccountListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
resetSubAccountAPIKeyEPL: request.NewRateLimitWithWeight(oneSecondInterval, 1, 1),
getSubaccountTradingBalanceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
getSubaccountFundingBalanceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
getSubAccountMaxWithdrawalEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
historyOfSubaccountTransferEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
managedSubAccountTransferEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
masterAccountsManageTransfersBetweenSubaccountEPL: request.NewRateLimitWithWeight(oneSecondInterval, 1, 1),
setPermissionOfTransferOutEPL: request.NewRateLimitWithWeight(oneSecondInterval, 1, 1),
getCustodyTradingSubaccountListEPL: request.NewRateLimitWithWeight(oneSecondInterval, 1, 1),
setSubAccountVIPLoanAllocationEPL: request.NewRateLimitWithWeight(oneSecondInterval, 5, 1),
getSubAccountBorrowInterestAndLimitEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
// Grid Trading Endpoints
gridTradingEPL: request.NewRateLimitWithWeight(twoSecondsInterval, gridTradingRate, 1),
amendGridAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, amendGridAlgoOrderRate, 1),
stopGridAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, stopGridAlgoOrderRate, 1),
getGridAlgoOrderListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getGridAlgoOrderListRate, 1),
getGridAlgoOrderHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getGridAlgoOrderHistoryRate, 1),
getGridAlgoOrderDetailsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getGridAlgoOrderDetailsRate, 1),
getGridAlgoSubOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getGridAlgoSubOrdersRate, 1),
getGridAlgoOrderPositionsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getGridAlgoOrderPositionsRate, 1),
spotGridWithdrawIncomeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, spotGridWithdrawIncomeRate, 1),
computeMarginBalanceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, computeMarginBalance, 1),
adjustMarginBalanceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, adjustMarginBalance, 1),
getGridAIParameterEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getGridAIParameter, 1),
gridTradingEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
amendGridAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
stopGridAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
closePositionForForContractGridEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
cancelClosePositionOrderForContractGridEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
instantTriggerGridAlgoOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getGridAlgoOrderListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getGridAlgoOrderHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getGridAlgoOrderDetailsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getGridAlgoSubOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getGridAlgoOrderPositionsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
spotGridWithdrawIncomeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
computeMarginBalanceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
adjustMarginBalanceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getGridAIParameterEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
computeMinInvestmentEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
rsiBackTestingEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
// Signal Bot Trading
signalBotOrderDetailsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
signalBotOrderPositionsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
signalBotSubOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
signalBotEventHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
// Recurring Buy Order
placeRecurringBuyOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
amendRecurringBuyOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
stopRecurringBuyOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getRecurringBuyOrderListEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getRecurringBuyOrderHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getRecurringBuyOrderDetailEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getRecurringBuySubOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getExistingLeadingPositionsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getLeadingPositionHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
placeLeadingStopOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
closeLeadingPositionEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getLeadingInstrumentsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getProfitSharingLimitEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getTotalProfitSharingEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
setFirstCopySettingsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
amendFirstCopySettingsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
stopCopyingEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getCopySettingsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getMultipleLeveragesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
setBatchLeverageEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getMyLeadTradersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getLeadTraderRanksEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getLeadTraderWeeklyPNLEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getLeadTraderDailyPNLEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getLeadTraderStatsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getLeadTraderCurrencyPreferencesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getTraderCurrentLeadPositionsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getLeadTraderLeadPositionHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
// Earn
getOfferEPL: request.NewRateLimitWithWeight(oneSecondInterval, getOffer, 1),
purchaseEPL: request.NewRateLimitWithWeight(oneSecondInterval, purchase, 1),
redeemEPL: request.NewRateLimitWithWeight(oneSecondInterval, redeem, 1),
cancelPurchaseOrRedemptionEPL: request.NewRateLimitWithWeight(oneSecondInterval, cancelPurchaseOrRedemption, 1),
getEarnActiveOrdersEPL: request.NewRateLimitWithWeight(oneSecondInterval, getEarnActiveOrders, 1),
getFundingOrderHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, getFundingOrderHistory, 1),
getOfferEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
purchaseEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
redeemEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
cancelPurchaseOrRedemptionEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
getEarnActiveOrdersEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
getFundingOrderHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
getProductInfoEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
// ETH Staking
purchaseETHStakingEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
redeemETHStakingEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
getBETHBalanceEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getPurchaseRedeemHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
getAPYHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, 6, 1),
// Market Data
getTickersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getTickersRate, 1),
getIndexTickersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getIndexTickersRate, 1),
getOrderBookEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getOrderBookRate, 1),
getCandlestickEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getCandlesticksRate, 1),
getCandlestickHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getCandlesticksHistoryRate, 1),
getIndexCandlestickEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getIndexCandlesticksRate, 1),
getTradesRequestEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getTradesRequestRate, 1),
get24HTotalVolumeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, get24HTotalVolumeRate, 1),
getOracleEPL: request.NewRateLimitWithWeight(fiveSecondsInterval, getOracleRate, 1),
getExchangeRateRequestEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getExchangeRateRequestRate, 1),
getIndexComponentsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getIndexComponentsRate, 1),
getBlockTickersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getBlockTickersRate, 1),
getBlockTradesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getBlockTradesRate, 1),
getTickersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getTickerEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getPremiumHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getIndexTickersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getOrderBookEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 40, 1),
getOrderBookLiteEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 6, 1),
getCandlesticksEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 40, 1),
getCandlestickHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getIndexCandlesticksEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getIndexCandlesticksHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getMarkPriceCandlesticksHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getEconomicCalendarEPL: request.NewRateLimitWithWeight(oneSecondInterval, 5, 1),
// getIndexCandlesticksEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getEstimatedDeliveryPriceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getTradesRequestEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 100, 1),
get24HTotalVolumeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
getOracleEPL: request.NewRateLimitWithWeight(fiveSecondsInterval, 1, 1),
getExchangeRateRequestEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 1, 1),
getIndexComponentsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getBlockTickersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getBlockTradesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
// Spread Orders rate limiters
placeSpreadOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
cancelSpreadOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
cancelAllSpreadOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
amendSpreadOrderEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getSpreadOrderDetailsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getActiveSpreadOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getSpreadOrders7DaysEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getSpreadOrderTradesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getSpreadsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getSpreadOrderbookEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getSpreadTickerEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getSpreadPublicTradesEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
cancelAllSpreadOrdersAfterEPL: request.NewRateLimitWithWeight(oneSecondInterval, 1, 1),
// Public Data Endpoints
getInstrumentsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getInstrumentsRate, 1),
getDeliveryExerciseHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getDeliveryExerciseHistoryRate, 1),
getOpenInterestEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getOpenInterestRate, 1),
getFundingEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getFundingRate, 1),
getFundingRateHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getFundingRateHistoryRate, 1),
getLimitPriceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getLimitPriceRate, 1),
getOptionMarketDateEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getOptionMarketDateRate, 1),
getEstimatedDeliveryExercisePriceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getEstimatedDeliveryExercisePriceRate, 1),
getDiscountRateAndInterestFreeQuotaEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getDiscountRateAndInterestFreeQuotaRate, 1),
getSystemTimeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getSystemTimeRate, 1),
getLiquidationOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getLiquidationOrdersRate, 1),
getMarkPriceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getMarkPriceRate, 1),
getPositionTiersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getPositionTiersRate, 1),
getInterestRateAndLoanQuotaEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getInterestRateAndLoanQuotaRate, 1),
getInterestRateAndLoanQuoteForVIPLoansEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getInterestRateAndLoanQuoteForVIPLoansRate, 1),
getUnderlyingEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getUnderlyingRate, 1),
getInsuranceFundEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getInsuranceFundRate, 1),
unitConvertEPL: request.NewRateLimitWithWeight(twoSecondsInterval, unitConvertRate, 1),
getInstrumentsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getDeliveryExerciseHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 40, 1),
getOpenInterestEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getFundingEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getFundingRateHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getLimitPriceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getOptionMarketDateEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getEstimatedDeliveryExercisePriceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getDiscountRateAndInterestFreeQuotaEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
getSystemTimeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getLiquidationOrdersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 40, 1), // Missing from documentation
getMarkPriceEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getPositionTiersEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
getInterestRateAndLoanQuotaEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
getInterestRateAndLoanQuoteForVIPLoansEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 2, 1),
getUnderlyingEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getInsuranceFundEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
unitConvertEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
optionTickBandsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getIndexTickerEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
// Trading Data Endpoints
getSupportCoinEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getSupportCoinRate, 1),
getTakerVolumeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getTakerVolumeRate, 1),
getMarginLendingRatioEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getMarginLendingRatioRate, 1),
getLongShortRatioEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getLongShortRatioRate, 1),
getContractsOpenInterestAndVolumeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getContractsOpenInterestAndVolumeRate, 1),
getOptionsOpenInterestAndVolumeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getOptionsOpenInterestAndVolumeRate, 1),
getPutCallRatioEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getPutCallRatioRate, 1),
getOpenInterestAndVolumeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getOpenInterestAndVolumeRate, 1),
getTakerFlowEPL: request.NewRateLimitWithWeight(twoSecondsInterval, getTakerFlowRate, 1),
getSupportCoinEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getTakerVolumeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getMarginLendingRatioEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getLongShortRatioEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getContractsOpenInterestAndVolumeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getOptionsOpenInterestAndVolumeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getPutCallRatioEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getOpenInterestAndVolumeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getTakerFlowEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
// Status Endpoints
getEventStatusEPL: request.NewRateLimitWithWeight(fiveSecondsInterval, getEventStatusRate, 1),
getEventStatusEPL: request.NewRateLimitWithWeight(fiveSecondsInterval, 1, 1),
getAffilateInviteesDetailEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getUserAffiliateRebateInformationEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
placeLendingOrderEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
amendLendingOrderEPL: request.NewRateLimitWithWeight(oneSecondInterval, 2, 1),
lendingOrderListEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
lendingSubOrderListEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
lendingPublicOfferEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
lendingAPYHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
lendingVolumeEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
rubikGetContractOpenInterestHistoryEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 10, 1),
rubikContractTakerVolumeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
rubikTopTradersContractLongShortRatioEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getAccountInstrumentsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 20, 1),
getAnnouncementsEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 5, 1),
getAnnouncementTypeEPL: request.NewRateLimitWithWeight(twoSecondsInterval, 1, 1),
getDepositOrderDetailEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
getDepositOrderHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
getWithdrawalOrderDetailEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
getFiatWithdrawalOrderHistoryEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
cancelWithdrawalOrderEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
createWithdrawalOrderEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
getWithdrawalPaymentMethodsEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
getFiatDepositPaymentMethodsEPL: request.NewRateLimitWithWeight(oneSecondInterval, 3, 1),
}
}

View File

@@ -0,0 +1,283 @@
package okx
import (
"context"
"net/http"
"testing"
"github.com/stretchr/testify/require"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
func TestRateLimit_LimitStatic(t *testing.T) {
t.Parallel()
testTable := map[string]request.EndpointLimit{
"placeOrder": placeOrderEPL,
"placeMultipleOrders": placeMultipleOrdersEPL,
"cancelOrder": cancelOrderEPL,
"cancelMultipleOrders": cancelMultipleOrdersEPL,
"amendOrder": amendOrderEPL,
"amendMultipleOrders": amendMultipleOrdersEPL,
"closePosition": closePositionEPL,
"getOrderDet": getOrderDetEPL,
"getOrderList": getOrderListEPL,
"getOrderHistory7Days": getOrderHistory7DaysEPL,
"getOrderHistory3Months": getOrderHistory3MonthsEPL,
"getTransactionDetail3Days": getTransactionDetail3DaysEPL,
"getTransactionDetail3Months": getTransactionDetail3MonthsEPL,
"setTransactionDetail2YearInterval": setTransactionDetail2YearIntervalEPL,
"getTransactionDetailLast2Years": getTransactionDetailLast2YearsEPL,
"cancelAllAfterCountdown": cancelAllAfterCountdownEPL,
"placeAlgoOrder": placeAlgoOrderEPL,
"cancelAlgoOrder": cancelAlgoOrderEPL,
"amendAlgoOrder": amendAlgoOrderEPL,
"cancelAdvanceAlgoOrder": cancelAdvanceAlgoOrderEPL,
"getAlgoOrderDetail": getAlgoOrderDetailEPL,
"getAlgoOrderList": getAlgoOrderListEPL,
"getAlgoOrderHistory": getAlgoOrderHistoryEPL,
"getEasyConvertCurrencyList": getEasyConvertCurrencyListEPL,
"placeEasyConvert": placeEasyConvertEPL,
"getEasyConvertHistory": getEasyConvertHistoryEPL,
"getOneClickRepayHistory": getOneClickRepayHistoryEPL,
"oneClickRepayCurrencyList": oneClickRepayCurrencyListEPL,
"tradeOneClickRepay": tradeOneClickRepayEPL,
"massCancemMMPOrder": massCancemMMPOrderEPL,
"getCounterparties": getCounterpartiesEPL,
"createRFQ": createRFQEPL,
"cancelRFQ": cancelRFQEPL,
"cancelMultipleRFQ": cancelMultipleRFQEPL,
"cancelAllRFQs": cancelAllRFQsEPL,
"executeQuote": executeQuoteEPL,
"getQuoteProducts": getQuoteProductsEPL,
"setQuoteProducts": setQuoteProductsEPL,
"resetRFQMMP": resetRFQMMPEPL,
"setMMP": setMMPEPL,
"getMMPConfig": getMMPConfigEPL,
"createQuote": createQuoteEPL,
"cancelQuote": cancelQuoteEPL,
"cancelMultipleQuotes": cancelMultipleQuotesEPL,
"cancelAllQuotes": cancelAllQuotesEPL,
"getRFQs": getRFQsEPL,
"getQuotes": getQuotesEPL,
"getTrades": getTradesEPL,
"getTradesHistory": getTradesHistoryEPL,
"optionInstrumentTradeFamily": optionInstrumentTradeFamilyEPL,
"optionTrades": optionTradesEPL,
"getPublicTrades": getPublicTradesEPL,
"getCurrencies": getCurrenciesEPL,
"getBalance": getBalanceEPL,
"getNonTradableAssets": getNonTradableAssetsEPL,
"getAccountAssetValuation": getAccountAssetValuationEPL,
"fundsTransfer": fundsTransferEPL,
"getFundsTransferState": getFundsTransferStateEPL,
"assetBillsDetails": assetBillsDetailsEPL,
"lightningDeposits": lightningDepositsEPL,
"getDepositAddress": getDepositAddressEPL,
"getDepositHistory": getDepositHistoryEPL,
"withdrawal": withdrawalEPL,
"lightningWithdrawals": lightningWithdrawalsEPL,
"cancelWithdrawal": cancelWithdrawalEPL,
"getWithdrawalHistory": getWithdrawalHistoryEPL,
"getDepositWithdrawalStatus": getDepositWithdrawalStatusEPL,
"smallAssetsConvert": smallAssetsConvertEPL,
"getPublicExchangeList": getPublicExchangeListEPL,
"getSavingBalance": getSavingBalanceEPL,
"savingsPurchaseRedemption": savingsPurchaseRedemptionEPL,
"setLendingRate": setLendingRateEPL,
"getLendingHistory": getLendingHistoryEPL,
"getPublicBorrowInfo": getPublicBorrowInfoEPL,
"getPublicBorrowHistory": getPublicBorrowHistoryEPL,
"getConvertCurrencies": getConvertCurrenciesEPL,
"getConvertCurrencyPair": getConvertCurrencyPairEPL,
"estimateQuote": estimateQuoteEPL,
"convertTrade": convertTradeEPL,
"getConvertHistory": getConvertHistoryEPL,
"getAccountBalance": getAccountBalanceEPL,
"getPositions": getPositionsEPL,
"getPositionsHistory": getPositionsHistoryEPL,
"getAccountAndPositionRisk": getAccountAndPositionRiskEPL,
"getBillsDetails": getBillsDetailsEPL,
"getBillsDetailArchive": getBillsDetailArchiveEPL,
"getAccountConfiguration": getAccountConfigurationEPL,
"setPositionMode": setPositionModeEPL,
"setLeverage": setLeverageEPL,
"getMaximumBuyOrSellAmount": getMaximumBuyOrSellAmountEPL,
"getMaximumAvailableTradableAmount": getMaximumAvailableTradableAmountEPL,
"increaseOrDecreaseMargin": increaseOrDecreaseMarginEPL,
"getLeverage": getLeverageEPL,
"getLeverateEstimatedInfo": getLeverateEstimatedInfoEPL,
"getTheMaximumLoanOfInstrument": getTheMaximumLoanOfInstrumentEPL,
"getFeeRates": getFeeRatesEPL,
"getInterestAccruedData": getInterestAccruedDataEPL,
"getInterestRate": getInterestRateEPL,
"setGreeks": setGreeksEPL,
"isolatedMarginTradingSettings": isolatedMarginTradingSettingsEPL,
"getMaximumWithdrawals": getMaximumWithdrawalsEPL,
"getAccountRiskState": getAccountRiskStateEPL,
"manualBorrowAndRepay": manualBorrowAndRepayEPL,
"getBorrowAndRepayHistory": getBorrowAndRepayHistoryEPL,
"vipLoansBorrowAnsRepay": vipLoansBorrowAnsRepayEPL,
"getBorrowAnsRepayHistoryHistory": getBorrowAnsRepayHistoryHistoryEPL,
"getVIPInterestAccruedData": getVIPInterestAccruedDataEPL,
"getVIPInterestDeductedData": getVIPInterestDeductedDataEPL,
"getVIPLoanOrderList": getVIPLoanOrderListEPL,
"getVIPLoanOrderDetail": getVIPLoanOrderDetailEPL,
"getBorrowInterestAndLimit": getBorrowInterestAndLimitEPL,
"positionBuilder": positionBuilderEPL,
"getGreeks": getGreeksEPL,
"getPMLimitation": getPMLimitationEPL,
"setRiskOffsetLimiter": setRiskOffsetLimiterEPL,
"activateOption": activateOptionEPL,
"setAutoLoan": setAutoLoanEPL,
"setAccountLevel": setAccountLevelEPL,
"resetMMPStatus": resetMMPStatusEPL,
"viewSubaccountList": viewSubaccountListEPL,
"resetSubAccountAPIKey": resetSubAccountAPIKeyEPL,
"getSubaccountTradingBalance": getSubaccountTradingBalanceEPL,
"getSubaccountFundingBalance": getSubaccountFundingBalanceEPL,
"getSubAccountMaxWithdrawal": getSubAccountMaxWithdrawalEPL,
"historyOfSubaccountTransfer": historyOfSubaccountTransferEPL,
"managedSubAccountTransfer": managedSubAccountTransferEPL,
"masterAccountsManageTransfersBetweenSubaccount": masterAccountsManageTransfersBetweenSubaccountEPL,
"setPermissionOfTransferOut": setPermissionOfTransferOutEPL,
"getCustodyTradingSubaccountList": getCustodyTradingSubaccountListEPL,
"setSubAccountVIPLoanAllocation": setSubAccountVIPLoanAllocationEPL,
"getSubAccountBorrowInterestAndLimit": getSubAccountBorrowInterestAndLimitEPL,
"gridTrading": gridTradingEPL,
"amendGridAlgoOrder": amendGridAlgoOrderEPL,
"stopGridAlgoOrder": stopGridAlgoOrderEPL,
"closePositionForForContractGrid": closePositionForForContractGridEPL,
"cancelClosePositionOrderForContractGrid": cancelClosePositionOrderForContractGridEPL,
"instantTriggerGridAlgoOrder": instantTriggerGridAlgoOrderEPL,
"getGridAlgoOrderList": getGridAlgoOrderListEPL,
"getGridAlgoOrderHistory": getGridAlgoOrderHistoryEPL,
"getGridAlgoOrderDetails": getGridAlgoOrderDetailsEPL,
"getGridAlgoSubOrders": getGridAlgoSubOrdersEPL,
"getGridAlgoOrderPositions": getGridAlgoOrderPositionsEPL,
"spotGridWithdrawIncome": spotGridWithdrawIncomeEPL,
"computeMarginBalance": computeMarginBalanceEPL,
"adjustMarginBalance": adjustMarginBalanceEPL,
"getGridAIParameter": getGridAIParameterEPL,
"computeMinInvestment": computeMinInvestmentEPL,
"rsiBackTesting": rsiBackTestingEPL,
"signalBotOrderDetails": signalBotOrderDetailsEPL,
"signalBotOrderPositions": signalBotOrderPositionsEPL,
"signalBotSubOrders": signalBotSubOrdersEPL,
"signalBotEventHistory": signalBotEventHistoryEPL,
"placeRecurringBuyOrder": placeRecurringBuyOrderEPL,
"amendRecurringBuyOrder": amendRecurringBuyOrderEPL,
"stopRecurringBuyOrder": stopRecurringBuyOrderEPL,
"getRecurringBuyOrderList": getRecurringBuyOrderListEPL,
"getRecurringBuyOrderHistory": getRecurringBuyOrderHistoryEPL,
"getRecurringBuyOrderDetail": getRecurringBuyOrderDetailEPL,
"getRecurringBuySubOrders": getRecurringBuySubOrdersEPL,
"getExistingLeadingPositions": getExistingLeadingPositionsEPL,
"getLeadingPositionHistory": getLeadingPositionHistoryEPL,
"placeLeadingStopOrder": placeLeadingStopOrderEPL,
"closeLeadingPosition": closeLeadingPositionEPL,
"getLeadingInstruments": getLeadingInstrumentsEPL,
"getProfitSharingLimit": getProfitSharingLimitEPL,
"getTotalProfitSharing": getTotalProfitSharingEPL,
"setFirstCopySettings": setFirstCopySettingsEPL,
"amendFirstCopySettings": amendFirstCopySettingsEPL,
"stopCopying": stopCopyingEPL,
"getCopySettings": getCopySettingsEPL,
"getMultipleLeverages": getMultipleLeveragesEPL,
"setBatchLeverage": setBatchLeverageEPL,
"getMyLeadTraders": getMyLeadTradersEPL,
"getLeadTraderRanks": getLeadTraderRanksEPL,
"getLeadTraderWeeklyPNL": getLeadTraderWeeklyPNLEPL,
"getLeadTraderDailyPNL": getLeadTraderDailyPNLEPL,
"getLeadTraderStats": getLeadTraderStatsEPL,
"getLeadTraderCurrencyPreferences": getLeadTraderCurrencyPreferencesEPL,
"getTraderCurrentLeadPositions": getTraderCurrentLeadPositionsEPL,
"getLeadTraderLeadPositionHistory": getLeadTraderLeadPositionHistoryEPL,
"getOffer": getOfferEPL,
"purchase": purchaseEPL,
"redeem": redeemEPL,
"cancelPurchaseOrRedemption": cancelPurchaseOrRedemptionEPL,
"getEarnActiveOrders": getEarnActiveOrdersEPL,
"getFundingOrderHistory": getFundingOrderHistoryEPL,
"purchaseETHStaking": purchaseETHStakingEPL,
"redeemETHStaking": redeemETHStakingEPL,
"getBETHBalance": getBETHBalanceEPL,
"getPurchaseRedeemHistory": getPurchaseRedeemHistoryEPL,
"getAPYHistory": getAPYHistoryEPL,
"getTickers": getTickersEPL,
"getTicker": getTickerEPL,
"getIndexTickers": getIndexTickersEPL,
"getOrderBook": getOrderBookEPL,
"getOrderBookLite": getOrderBookLiteEPL,
"getCandlesticks": getCandlesticksEPL,
"getTradesRequest": getTradesRequestEPL,
"get24HTotalVolume": get24HTotalVolumeEPL,
"getOracle": getOracleEPL,
"getExchangeRateRequest": getExchangeRateRequestEPL,
"getIndexComponents": getIndexComponentsEPL,
"getBlockTickers": getBlockTickersEPL,
"getBlockTrades": getBlockTradesEPL,
"placeSpreadOrder": placeSpreadOrderEPL,
"cancelSpreadOrder": cancelSpreadOrderEPL,
"cancelAllSpreadOrder": cancelAllSpreadOrderEPL,
"amendSpreadOrder": amendSpreadOrderEPL,
"getSpreadOrderDetails": getSpreadOrderDetailsEPL,
"getSpreadOrderTrades": getSpreadOrderTradesEPL,
"getSpreads": getSpreadsEPL,
"getSpreadOrderbook": getSpreadOrderbookEPL,
"getSpreadTicker": getSpreadTickerEPL,
"getSpreadPublicTrades": getSpreadPublicTradesEPL,
"getActiveSpreadOrders": getActiveSpreadOrdersEPL,
"getSpreadOrders7Days": getSpreadOrders7DaysEPL,
"getInstruments": getInstrumentsEPL,
"getDeliveryExerciseHistory": getDeliveryExerciseHistoryEPL,
"getOpenInterest": getOpenInterestEPL,
"getFunding": getFundingEPL,
"getFundingRateHistory": getFundingRateHistoryEPL,
"getLimitPrice": getLimitPriceEPL,
"getOptionMarketDate": getOptionMarketDateEPL,
"getEstimatedDeliveryExercisePrice": getEstimatedDeliveryExercisePriceEPL,
"getDiscountRateAndInterestFreeQuota": getDiscountRateAndInterestFreeQuotaEPL,
"getSystemTime": getSystemTimeEPL,
"getLiquidationOrders": getLiquidationOrdersEPL,
"getMarkPrice": getMarkPriceEPL,
"getPositionTiers": getPositionTiersEPL,
"getInterestRateAndLoanQuota": getInterestRateAndLoanQuotaEPL,
"getInterestRateAndLoanQuoteForVIPLoans": getInterestRateAndLoanQuoteForVIPLoansEPL,
"getUnderlying": getUnderlyingEPL,
"getInsuranceFund": getInsuranceFundEPL,
"unitConvert": unitConvertEPL,
"optionTickBands": optionTickBandsEPL,
"getIndexTicker": getIndexTickerEPL,
"getSupportCoin": getSupportCoinEPL,
"getTakerVolume": getTakerVolumeEPL,
"getMarginLendingRatio": getMarginLendingRatioEPL,
"getLongShortRatio": getLongShortRatioEPL,
"getContractsOpenInterestAndVolume": getContractsOpenInterestAndVolumeEPL,
"getOptionsOpenInterestAndVolume": getOptionsOpenInterestAndVolumeEPL,
"getPutCallRatio": getPutCallRatioEPL,
"getOpenInterestAndVolume": getOpenInterestAndVolumeEPL,
"getTakerFlow": getTakerFlowEPL,
"getEventStatus": getEventStatusEPL,
"getCandlestickHistory": getCandlestickHistoryEPL,
"getIndexCandlesticks": getIndexCandlesticksEPL,
"getIndexCandlesticksHistory": getIndexCandlesticksHistoryEPL,
"getMarkPriceCandlesticksHistory": getMarkPriceCandlesticksHistoryEPL,
"getEconomicCalendar": getEconomicCalendarEPL,
"getEstimatedDeliveryPrice": getEstimatedDeliveryPriceEPL,
"getAffilateInviteesDetail": getAffilateInviteesDetailEPL,
"getUserAffilateRebateInformation": getUserAffiliateRebateInformationEPL,
}
rl, err := request.New("RateLimit_Static", http.DefaultClient, request.WithLimiter(GetRateLimit()))
require.NoError(t, err)
for name, tt := range testTable {
t.Run(name, func(t *testing.T) {
t.Parallel()
if err := rl.InitiateRateLimit(context.Background(), tt); err != nil {
t.Fatalf("error applying rate limit: %v", err)
}
})
}
}

View File

@@ -949,7 +949,22 @@ func TestStringToOrderType(t *testing.T) {
{"tRiGgEr", Trigger, nil},
{"conDitiOnal", ConditionalStop, nil},
{"oCo", OCO, nil},
{"mMp", MarketMakerProtection, nil},
{"Mmp_And_Post_oNly", MarketMakerProtectionAndPostOnly, nil},
{"tWaP", TWAP, nil},
{"TWAP", TWAP, nil},
{"woahMan", UnknownType, errUnrecognisedOrderType},
{"chase", Chase, nil},
{"MOVE_ORDER_STOP", TrailingStop, nil},
{"mOVe_OrdeR_StoP", TrailingStop, nil},
{"optimal_limit_IoC", OptimalLimitIOC, nil},
{"Stop_market", StopMarket, nil},
{"liquidation", Liquidation, nil},
{"LiQuidation", Liquidation, nil},
{"take_profit", TakeProfit, nil},
{"Take ProfIt", TakeProfit, nil},
{"TAKE PROFIT MARkEt", TakeProfitMarket, nil},
{"TAKE_PROFIT_MARkEt", TakeProfitMarket, nil},
}
for i := range cases {
testData := &cases[i]
@@ -2151,3 +2166,29 @@ func TestGetTradeAmount(t *testing.T) {
s.Side = Sell
require.Equal(t, baseAmount, s.GetTradeAmount(protocol.TradingRequirements{SpotMarketOrderAmountSellBaseOnly: true}))
}
func TestStringToTrackingMode(t *testing.T) {
t.Parallel()
inputs := map[string]TrackingMode{
"diStance": Distance,
"distance": Distance,
"Percentage": Percentage,
"percentage": Percentage,
"": UnknownTrackingMode,
}
for k, v := range inputs {
assert.Equal(t, v, StringToTrackingMode(k))
}
}
func TestTrackingModeString(t *testing.T) {
t.Parallel()
inputs := map[TrackingMode]string{
Distance: "distance",
Percentage: "percentage",
UnknownTrackingMode: "",
}
for k, v := range inputs {
require.Equal(t, v, k.String())
}
}

View File

@@ -31,6 +31,8 @@ var (
// ErrNoRates is returned when no margin rates are returned when they are expected
ErrNoRates = errors.New("no rates")
ErrCannotLiquidate = errors.New("cannot liquidate position")
ErrUnknownTrackingMode = errors.New("unknown tracking mode")
)
// Submit contains all properties of an order that may be required
@@ -92,6 +94,11 @@ type Submit struct {
// Iceberg specifies whether or not only visible portions of orders are shown in iceberg orders
Iceberg bool
// TrackingMode specifies the way trailing stop and chase orders follow the market price or ask/bid prices.
// See: https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-place-algo-order
TrackingMode TrackingMode
TrackingValue float64
}
// SubmitResponse is what is returned after submitting an order to an exchange
@@ -129,6 +136,16 @@ type SubmitResponse struct {
MarginType margin.Type
}
// TrackingMode defines how the stop price follows the market price.
type TrackingMode uint8
// Defined package tracking modes
const (
UnknownTrackingMode TrackingMode = iota
Distance // Distance fixed amount away from the market price
Percentage // Percentage fixed percentage away from the market price
)
// Modify contains all properties of an order
// that may be updated after it has been created
// Each exchange has their own requirements, so not all fields
@@ -359,8 +376,12 @@ const (
Liquidation
Trigger
OptimalLimitIOC
OCO // One-cancels-the-other order
ConditionalStop // One-way stop order
OCO // One-cancels-the-other order
ConditionalStop // One-way stop order
MarketMakerProtection // market-maker-protection used with portfolio margin mode. See https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-order
MarketMakerProtectionAndPostOnly // market-maker-protection and post-only mode. Used in Okx exchange orders.
TWAP // time-weighted average price.
Chase // chase order. See https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-place-algo-order
)
// Side enforces a standard for order sides across the code base

View File

@@ -705,6 +705,14 @@ func (t Type) String() string {
return "STOP"
case ConditionalStop:
return "CONDITIONAL"
case MarketMakerProtection:
return "MMP"
case MarketMakerProtectionAndPostOnly:
return "MMP_AND_POST_ONLY"
case TWAP:
return "TWAP"
case Chase:
return "CHASE"
case StopLimit:
return "STOP LIMIT"
case StopMarket:
@@ -1137,7 +1145,7 @@ func StringToOrderType(oType string) (Type, error) {
return StopLimit, nil
case StopMarket.String(), "STOP_MARKET":
return StopMarket, nil
case TrailingStop.String(), "TRAILING STOP", "EXCHANGE TRAILING STOP":
case TrailingStop.String(), "TRAILING STOP", "EXCHANGE TRAILING STOP", "MOVE_ORDER_STOP":
return TrailingStop, nil
case FillOrKill.String(), "EXCHANGE FOK":
return FillOrKill, nil
@@ -1155,6 +1163,20 @@ func StringToOrderType(oType string) (Type, error) {
return OCO, nil
case ConditionalStop.String():
return ConditionalStop, nil
case MarketMakerProtection.String():
return MarketMakerProtection, nil
case MarketMakerProtectionAndPostOnly.String():
return MarketMakerProtectionAndPostOnly, nil
case TWAP.String():
return TWAP, nil
case Chase.String():
return Chase, nil
case TakeProfitMarket.String(), "TAKE_PROFIT_MARKET":
return TakeProfitMarket, nil
case TakeProfit.String(), "TAKE_PROFIT":
return TakeProfit, nil
case Liquidation.String():
return Liquidation, nil
default:
return UnknownType, fmt.Errorf("'%v' %w", oType, errUnrecognisedOrderType)
}
@@ -1368,3 +1390,28 @@ func (t PriceType) StringToPriceType(priceType string) (PriceType, error) {
return UnknownPriceType, ErrUnknownPriceType
}
}
// String implements the stringer interface
func (t TrackingMode) String() string {
switch t {
case Distance:
return "distance"
case Percentage:
return "percentage"
default:
return ""
}
}
// StringToTrackingMode converts TrackingMode instance from string
func StringToTrackingMode(mode string) TrackingMode {
mode = strings.ToLower(mode)
switch mode {
case "distance":
return Distance
case "percentage":
return Percentage
default:
return UnknownTrackingMode
}
}

File diff suppressed because one or more lines are too long