mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-17 15:09:59 +00:00
* initial update of currency system * WIP progress * Finish initial currency string error returns * fix whoopsie testing for non https insecureinos * Current WIP for getEnabledPairs check and error return * WIP continued * When getting enabled pairs throw error when item is not contained in available pairs list * More updates -WIP * Wip continued including potential interface * Current WIP * pairs manager pass * drop asset string and just use the map key, plus return some errors and create more work for myself. * clean and fixed a bug in currency.json, will not populate correctly without coinmarketcap api keys set. * purge logger references after merge * go mod tidy after merge * Pointer change WIP * fix some issues and added error returns to a few items (WIP) * WIP * Clean * Fix some linter issues * Fix more linter issues * even more linters * xtda nits * revert pointer change and rm field * Addr madcozbadd nits * fix linter issues: shadow declarations * Fix linter issues: gocritic huge things * linter issue fix * Addr nits * flush go mod files * after merge woops * fix shadow dec * Addr thrasher nits * addr nits * fix some issues * more fixes * RM println * Addr glorious nits * Add helper method for setting assets * add missing format directive * Addr nits * Actually process new futures contracts -_- derp * WIP for GRPC upgrade for pair management * update config pairs * finished disabling and enabling asset * linked update of tradable pairs to cli * fix oopsies * defer writing to file on program termination for currency storage system * update template * don't add disabled asset items to initial sync * Fix enable disabling a list of pairs and added in a slice error type so we can add whats allowable without throwing an error and return a report, also addressed some other nits * WIP on getting a channel to unsub * Wip track down unsubscribe bug and start creating streaming interface * purge websocket orderbook object and centralised updating routine for orderbook * general clean before interface implementation * stage one connection interface WIP * WIP * repackage wshandler WIP * find difference of subs and change signature of subscriber functions so we can batch subscriptions and unsubscription in exchanges that support it * design change on mange subscription routine WIP * integrated ZB with the new webosocket updates * WIP - okex conversion * integrate websocket upgrades for lakebtc, kraken, huobi, hitbtc, gateio, and WIP for coinbene * integrate another range of exchanges for websocket update * Added subscriber and unsubscriber methods to websocket functionality * fixed tests WIP * amalgamate cache setup with main websocket setup * reinstate exported fields traffic alert and shutdownC to accommodate gemini and lakebtc implementations * added in colon * Updated websocket auth handling as they werent getting passed through. Added a setter method for websocket URL due to the Binance generated auth key/listenKey. Fixed bug which stopped reconnection. * Fix subscribe candle bug Fix time conversion in candle Fix inititial candle history to datahandler Include funding to orderbook handling Include funding to trades Reduce code duplication in sub and unsub functions Added the ability to include funding currency websocket subscriptions validated all channels and added more items todo list (Auth items) * RM line * bitstamp pass * btcmarkets pass - still needs to implement unsubscriber functionality and pairs change test. * Batch outgoing subscriptions and fix unsubscribe bug * BTSE - bumped time to minute to reduce pinger calling by 75 calls per day. Fix authentication bug and add authentication pass into to-do. Batch outgoing subscription calls * fix type field and batch outgoing subs and unsubs for coinbasepro * Batch outgoing subs and unsubs * Fixes bug when matching return from authentication * Fix bug where params where being sent out of order due to map ,where depth items werent being subscribed too, where trying to subscribe to too many kline items caused error, where trying to get a nano secocond ID conflicted due to speed of generation. * Add websocket capability for currency pair change by utilizing full channel subscription list in subscribe function. * Add error handling * Fix public: time conversions, subscription list, stopped pushing heartbeat to data handler, aggregated list of connections. * hitBTC pass * returned nil instead of error due to period null bids and asks updates coming through. * Fix auth ping capture and reply. Added in interval handling for kline data. Added correct full trade data handling. Fix subscribe and unsubscribe. * Fix when websocket auth conn and token generation fail we don't try and auth sub. Fix bug between auth and normal connection id generation and matching. Batch outgoing payloads to increase efficiency. Updated matching functions to utilise channels instead of waitgroups and go routines. * RM debug output * rm func to get shutdown channel * Add unsubscriber functionality, added wsTicker type, removed return as this will impede data flow and cause reconnection when handling and processing data * okgroup WIP * *Added missing fields for websocket trades *Fix bug processing kline interval *Added fields for websocket ticker struct *Fix auth bug -Updated request and response matching param to interface so we can custom signature match. Stops auth subscribing before a reply is issued. -Updated channel inclusion of pair fo auth subs as this was missing. *Assortment of perfomance improvements * poloniex pass * send all trades to data handler, validated enabled and disable pairs * initial clean * centralised request matching mechanism * websocket main improvements WIP * WIP * Websocket management via gctcli WIP * GRPC expansion * Updated GCTCLI with websocket url and proxy setting functionality which flushes connection * Fix continuous spawning of routines bug on error with reconnection * Addr linter issues * fix subscription bug that I caused when I changed to a switch case * fix linter issue * fix woopsie * End of day WIP * Fix order submission REST, time conversion, order type conversion, orderID bugs * fix gateio test and unsubscribe bug * revert comment out code * websocketAPI changed to to true in configtest.json * fix race in gateio test * End of day WIP for websocket tests. * BugFix for binance when book isn't seeded. Updated websocket tests. Deprecated subscription manager. RM wrapper funcs. * Added string title to exchange name as they are saved as lower case in type, reinstated verbose check in websocket.go * Added verbosity check for setting websocket URL * fix bug where the asset had a mind of its own * purge dodgy coding * Fix tests, drop blocking chan in websocket Dial function * few more changes * race condition fix for websocket tests. * fix intermittent test failure due to underlying hash table storage * Address madcuzbad nit * RM superfluous printlines * Add quick top example with paramater fields * First pass Glorious nits * As per madcozbad suggestion return error when enabled pair not found in full return map. Add test. * addr madcozbadd nits * as per glorious suggestion rm'd loadedJSON field * adjusted ticker, added test and RM'd code that can never be executed * Addr nits and add in crypto rand genration for ID's * remove global channel declaration and rescoped as this was causing a lock * as per glorious suggestion restructured return error for websocket * addr glorious suggestions * fix linter issues * purge non-existent pair from testdata * add side field to struct and parse * addr glorious nits * Add verbosity to error returns and logs and fix string parsing in GCTRPC * fix speeling mistwake * Adds websocket functionality check before flushing websocket connection * Addr kraken panic and setting/flush websocket url stage one. * added websocket url check before setting with tests * Added in edge case test if by the time we call contains on available pairs it has been changed * remove error return for func * Continuation of tests * continuation of tests * Stop potential panic within pair creation function * Implement changes to upstream * rm sup comment * fix bug when subscribing and unsubscribing. Also add in boolean to determine there are currencies that need to be flushed via set pairs via gctcli * fix test * Fix linter issues * Fix tests * turn websocket off in config example * Fix issue where you cannot enable websocket when config is set to false, also added config websocket enable state saving * Introduced err var for same error returns * Add err var exchange base not found * restructure function * drop gctscript from generic response name * drop managesub delay const as its not being used * correctly implement websocket rate limiting for coinut * remove quotations * drop pair management check * fix spelling * return error in function to not update currency with unset role * amalagamted enable/disable into set function and added in pairstore fetch function * update error description * rm function * moved test function to sharedtestvals and move type to types.go * append delimiter onto currency delimiter strings * add test coverage * rm functions as they are set as methods in base * remove superfluous methods * Fix issue that would occur when a subscription errored and not appending successful subs * fix after rebase woopsie * fix linter issues * fix bug streamline code * fix linter issues * fix linter issues * fix case where it should not change ID if set but append new * fix whoopsie * fix websocket tests * fix readme, fix wrapper issues reporting template, go mod tidy * add test coverage * add test coverage and verified futures pariing * add in futures bypass as its not currently supported on BTSE until API update and implementation * removed downside/upside profit contract type as its no longer supported. Added in check in set config pairs to warn user of potential conflict and to manually remove or update. * If asset enabled add pair and increase code coverage * remove strings.title, set and fetch with strings.Lower but keep struct field exchangename unchanged. Streamline ticker and orderbook code. * Add code coverage * log error if setting default currency fails, add code coverage * address glorious nits * Addr xtda nits * fix linter issues * addr glorious nits * xtda nits * Addr glorious nits * add subscription protection and removed a superfluous wait call * fix test * fix whoopsie * addr xtda nits * addr glorious nits * Added asset types to subscriptions structs, also added in error handling for resubscription errors * consolidated rpc returned type and added in sucessful strings * dropped stream timing down to 100ms * DOC changes * proxy and url usage string additions * WIP * go mod tidy rides again * Addr nits * Addr nits, fix tests * fix wording * add in test case for currency matching * Add byte length check on outbound websocket payload subscriptions * addr thrasher nits * Addr madcozbadd nits * addr linter issues * Addr glorious nits by amalgamating function into one mega amazing function. * fix futures account subscription bug * addr glorious nits and reinstated wg.Wait() checks * changed string to currency delimiter string and setconnected by function
1064 lines
33 KiB
Go
1064 lines
33 KiB
Go
package exchange
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/thrasher-corp/gocryptotrader/common"
|
|
"github.com/thrasher-corp/gocryptotrader/common/crypto"
|
|
"github.com/thrasher-corp/gocryptotrader/config"
|
|
"github.com/thrasher-corp/gocryptotrader/currency"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/kline"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/protocol"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/stream"
|
|
"github.com/thrasher-corp/gocryptotrader/log"
|
|
"github.com/thrasher-corp/gocryptotrader/portfolio/banking"
|
|
)
|
|
|
|
const (
|
|
warningBase64DecryptSecretKeyFailed = "exchange %s unable to base64 decode secret key.. Disabling Authenticated API support" // nolint // False positive (G101: Potential hardcoded credentials)
|
|
// WarningAuthenticatedRequestWithoutCredentialsSet error message for authenticated request without credentials set
|
|
WarningAuthenticatedRequestWithoutCredentialsSet = "exchange %s authenticated HTTP request called but not supported due to unset/default API keys"
|
|
// DefaultHTTPTimeout is the default HTTP/HTTPS Timeout for exchange requests
|
|
DefaultHTTPTimeout = time.Second * 15
|
|
// DefaultWebsocketResponseCheckTimeout is the default delay in checking for an expected websocket response
|
|
DefaultWebsocketResponseCheckTimeout = time.Millisecond * 50
|
|
// DefaultWebsocketResponseMaxLimit is the default max wait for an expected websocket response before a timeout
|
|
DefaultWebsocketResponseMaxLimit = time.Second * 7
|
|
// DefaultWebsocketOrderbookBufferLimit is the maximum number of orderbook updates that get stored before being applied
|
|
DefaultWebsocketOrderbookBufferLimit = 5
|
|
)
|
|
|
|
func (e *Base) checkAndInitRequester() {
|
|
if e.Requester == nil {
|
|
e.Requester = request.New(e.Name,
|
|
new(http.Client))
|
|
}
|
|
}
|
|
|
|
// SetHTTPClientTimeout sets the timeout value for the exchanges
|
|
// HTTP Client
|
|
func (e *Base) SetHTTPClientTimeout(t time.Duration) {
|
|
e.checkAndInitRequester()
|
|
e.Requester.HTTPClient.Timeout = t
|
|
}
|
|
|
|
// SetHTTPClient sets exchanges HTTP client
|
|
func (e *Base) SetHTTPClient(h *http.Client) {
|
|
e.checkAndInitRequester()
|
|
e.Requester.HTTPClient = h
|
|
}
|
|
|
|
// GetHTTPClient gets the exchanges HTTP client
|
|
func (e *Base) GetHTTPClient() *http.Client {
|
|
e.checkAndInitRequester()
|
|
return e.Requester.HTTPClient
|
|
}
|
|
|
|
// SetHTTPClientUserAgent sets the exchanges HTTP user agent
|
|
func (e *Base) SetHTTPClientUserAgent(ua string) {
|
|
e.checkAndInitRequester()
|
|
e.Requester.UserAgent = ua
|
|
e.HTTPUserAgent = ua
|
|
}
|
|
|
|
// GetHTTPClientUserAgent gets the exchanges HTTP user agent
|
|
func (e *Base) GetHTTPClientUserAgent() string {
|
|
return e.HTTPUserAgent
|
|
}
|
|
|
|
// SetClientProxyAddress sets a proxy address for REST and websocket requests
|
|
func (e *Base) SetClientProxyAddress(addr string) error {
|
|
if addr != "" {
|
|
proxy, err := url.Parse(addr)
|
|
if err != nil {
|
|
return fmt.Errorf("exchange.go - setting proxy address error %s",
|
|
err)
|
|
}
|
|
|
|
// No needs to check err here as the only err condition is an empty
|
|
// string which is already checked above
|
|
_ = e.Requester.SetProxy(proxy)
|
|
|
|
if e.Websocket != nil {
|
|
err = e.Websocket.SetProxyAddress(addr)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SetFeatureDefaults sets the exchanges default feature
|
|
// support set
|
|
func (e *Base) SetFeatureDefaults() {
|
|
if e.Config.Features == nil {
|
|
s := &config.FeaturesConfig{
|
|
Supports: config.FeaturesSupportedConfig{
|
|
Websocket: e.Features.Supports.Websocket,
|
|
REST: e.Features.Supports.REST,
|
|
RESTCapabilities: protocol.Features{
|
|
AutoPairUpdates: e.Features.Supports.RESTCapabilities.AutoPairUpdates,
|
|
},
|
|
},
|
|
}
|
|
|
|
if e.Config.SupportsAutoPairUpdates != nil {
|
|
s.Supports.RESTCapabilities.AutoPairUpdates = *e.Config.SupportsAutoPairUpdates
|
|
s.Enabled.AutoPairUpdates = *e.Config.SupportsAutoPairUpdates
|
|
} else {
|
|
s.Supports.RESTCapabilities.AutoPairUpdates = e.Features.Supports.RESTCapabilities.AutoPairUpdates
|
|
s.Enabled.AutoPairUpdates = e.Features.Supports.RESTCapabilities.AutoPairUpdates
|
|
if !s.Supports.RESTCapabilities.AutoPairUpdates {
|
|
e.Config.CurrencyPairs.LastUpdated = time.Now().Unix()
|
|
e.CurrencyPairs.LastUpdated = e.Config.CurrencyPairs.LastUpdated
|
|
}
|
|
}
|
|
e.Config.Features = s
|
|
e.Config.SupportsAutoPairUpdates = nil
|
|
} else {
|
|
if e.Features.Supports.RESTCapabilities.AutoPairUpdates != e.Config.Features.Supports.RESTCapabilities.AutoPairUpdates {
|
|
e.Config.Features.Supports.RESTCapabilities.AutoPairUpdates = e.Features.Supports.RESTCapabilities.AutoPairUpdates
|
|
|
|
if !e.Config.Features.Supports.RESTCapabilities.AutoPairUpdates {
|
|
e.Config.CurrencyPairs.LastUpdated = time.Now().Unix()
|
|
}
|
|
}
|
|
|
|
if e.Features.Supports.REST != e.Config.Features.Supports.REST {
|
|
e.Config.Features.Supports.REST = e.Features.Supports.REST
|
|
}
|
|
|
|
if e.Features.Supports.RESTCapabilities.TickerBatching != e.Config.Features.Supports.RESTCapabilities.TickerBatching {
|
|
e.Config.Features.Supports.RESTCapabilities.TickerBatching = e.Features.Supports.RESTCapabilities.TickerBatching
|
|
}
|
|
|
|
if e.Features.Supports.Websocket != e.Config.Features.Supports.Websocket {
|
|
e.Config.Features.Supports.Websocket = e.Features.Supports.Websocket
|
|
}
|
|
|
|
e.Features.Enabled.AutoPairUpdates = e.Config.Features.Enabled.AutoPairUpdates
|
|
}
|
|
}
|
|
|
|
// SetAPICredentialDefaults sets the API Credential validator defaults
|
|
func (e *Base) SetAPICredentialDefaults() {
|
|
// Exchange hardcoded settings take precedence and overwrite the config settings
|
|
if e.Config.API.CredentialsValidator == nil {
|
|
e.Config.API.CredentialsValidator = new(config.APICredentialsValidatorConfig)
|
|
}
|
|
if e.Config.API.CredentialsValidator.RequiresKey != e.API.CredentialsValidator.RequiresKey {
|
|
e.Config.API.CredentialsValidator.RequiresKey = e.API.CredentialsValidator.RequiresKey
|
|
}
|
|
|
|
if e.Config.API.CredentialsValidator.RequiresSecret != e.API.CredentialsValidator.RequiresSecret {
|
|
e.Config.API.CredentialsValidator.RequiresSecret = e.API.CredentialsValidator.RequiresSecret
|
|
}
|
|
|
|
if e.Config.API.CredentialsValidator.RequiresBase64DecodeSecret != e.API.CredentialsValidator.RequiresBase64DecodeSecret {
|
|
e.Config.API.CredentialsValidator.RequiresBase64DecodeSecret = e.API.CredentialsValidator.RequiresBase64DecodeSecret
|
|
}
|
|
|
|
if e.Config.API.CredentialsValidator.RequiresClientID != e.API.CredentialsValidator.RequiresClientID {
|
|
e.Config.API.CredentialsValidator.RequiresClientID = e.API.CredentialsValidator.RequiresClientID
|
|
}
|
|
|
|
if e.Config.API.CredentialsValidator.RequiresPEM != e.API.CredentialsValidator.RequiresPEM {
|
|
e.Config.API.CredentialsValidator.RequiresPEM = e.API.CredentialsValidator.RequiresPEM
|
|
}
|
|
}
|
|
|
|
// SupportsRESTTickerBatchUpdates returns whether or not the
|
|
// exhange supports REST batch ticker fetching
|
|
func (e *Base) SupportsRESTTickerBatchUpdates() bool {
|
|
return e.Features.Supports.RESTCapabilities.TickerBatching
|
|
}
|
|
|
|
// SupportsAutoPairUpdates returns whether or not the exchange supports
|
|
// auto currency pair updating
|
|
func (e *Base) SupportsAutoPairUpdates() bool {
|
|
if e.Features.Supports.RESTCapabilities.AutoPairUpdates ||
|
|
e.Features.Supports.WebsocketCapabilities.AutoPairUpdates {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// GetLastPairsUpdateTime returns the unix timestamp of when the exchanges
|
|
// currency pairs were last updated
|
|
func (e *Base) GetLastPairsUpdateTime() int64 {
|
|
return e.CurrencyPairs.LastUpdated
|
|
}
|
|
|
|
// GetAssetTypes returns the available asset types for an individual exchange
|
|
func (e *Base) GetAssetTypes() asset.Items {
|
|
return e.CurrencyPairs.GetAssetTypes()
|
|
}
|
|
|
|
// GetPairAssetType returns the associated asset type for the currency pair
|
|
// This method is only useful for exchanges that have pair names with multiple delimiters (BTC-USD-0626)
|
|
// Helpful if the exchange has only a single asset type but in that case the asset type can be hard coded
|
|
func (e *Base) GetPairAssetType(c currency.Pair) (asset.Item, error) {
|
|
assetTypes := e.GetAssetTypes()
|
|
for i := range assetTypes {
|
|
avail, err := e.GetAvailablePairs(assetTypes[i])
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if avail.Contains(c, true) {
|
|
return assetTypes[i], nil
|
|
}
|
|
}
|
|
return "", errors.New("asset type not associated with currency pair")
|
|
}
|
|
|
|
// GetClientBankAccounts returns banking details associated with
|
|
// a client for withdrawal purposes
|
|
func (e *Base) GetClientBankAccounts(exchangeName, withdrawalCurrency string) (*banking.Account, error) {
|
|
cfg := config.GetConfig()
|
|
return cfg.GetClientBankAccounts(exchangeName, withdrawalCurrency)
|
|
}
|
|
|
|
// GetExchangeBankAccounts returns banking details associated with an
|
|
// exchange for funding purposes
|
|
func (e *Base) GetExchangeBankAccounts(id, depositCurrency string) (*banking.Account, error) {
|
|
cfg := config.GetConfig()
|
|
return cfg.GetExchangeBankAccounts(e.Name, id, depositCurrency)
|
|
}
|
|
|
|
// SetCurrencyPairFormat checks the exchange request and config currency pair
|
|
// formats and syncs it with the exchanges SetDefault settings
|
|
func (e *Base) SetCurrencyPairFormat() {
|
|
if e.Config.CurrencyPairs == nil {
|
|
e.Config.CurrencyPairs = new(currency.PairsManager)
|
|
}
|
|
|
|
e.Config.CurrencyPairs.UseGlobalFormat = e.CurrencyPairs.UseGlobalFormat
|
|
if e.Config.CurrencyPairs.UseGlobalFormat {
|
|
e.Config.CurrencyPairs.RequestFormat = e.CurrencyPairs.RequestFormat
|
|
e.Config.CurrencyPairs.ConfigFormat = e.CurrencyPairs.ConfigFormat
|
|
return
|
|
}
|
|
|
|
if e.Config.CurrencyPairs.ConfigFormat != nil {
|
|
e.Config.CurrencyPairs.ConfigFormat = nil
|
|
}
|
|
if e.Config.CurrencyPairs.RequestFormat != nil {
|
|
e.Config.CurrencyPairs.RequestFormat = nil
|
|
}
|
|
|
|
assetTypes := e.GetAssetTypes()
|
|
for x := range assetTypes {
|
|
if _, err := e.Config.CurrencyPairs.Get(assetTypes[x]); err != nil {
|
|
ps, err := e.CurrencyPairs.Get(assetTypes[x])
|
|
if err != nil {
|
|
continue
|
|
}
|
|
e.Config.CurrencyPairs.Store(assetTypes[x], *ps)
|
|
}
|
|
}
|
|
}
|
|
|
|
// SetConfigPairs sets the exchanges currency pairs to the pairs set in the config
|
|
func (e *Base) SetConfigPairs() error {
|
|
assetTypes := e.Config.CurrencyPairs.GetAssetTypes()
|
|
exchangeAssets := e.CurrencyPairs.GetAssetTypes()
|
|
for x := range assetTypes {
|
|
if !exchangeAssets.Contains(assetTypes[x]) {
|
|
log.Warnf(log.ExchangeSys,
|
|
"%s exchange asset type %s unsupported, please manually remove from configuration",
|
|
e.Name,
|
|
assetTypes[x])
|
|
}
|
|
cfgPS, err := e.Config.CurrencyPairs.Get(assetTypes[x])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var enabledAsset bool
|
|
if e.Config.CurrencyPairs.IsAssetEnabled(assetTypes[x]) == nil {
|
|
enabledAsset = true
|
|
}
|
|
e.CurrencyPairs.SetAssetEnabled(assetTypes[x], enabledAsset)
|
|
|
|
if e.Config.CurrencyPairs.UseGlobalFormat {
|
|
e.CurrencyPairs.StorePairs(assetTypes[x], cfgPS.Available, false)
|
|
e.CurrencyPairs.StorePairs(assetTypes[x], cfgPS.Enabled, true)
|
|
continue
|
|
}
|
|
exchPS, err := e.CurrencyPairs.Get(assetTypes[x])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cfgPS.ConfigFormat = exchPS.ConfigFormat
|
|
cfgPS.RequestFormat = exchPS.RequestFormat
|
|
e.CurrencyPairs.StorePairs(assetTypes[x], cfgPS.Available, false)
|
|
e.CurrencyPairs.StorePairs(assetTypes[x], cfgPS.Enabled, true)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetAuthenticatedAPISupport returns whether the exchange supports
|
|
// authenticated API requests
|
|
func (e *Base) GetAuthenticatedAPISupport(endpoint uint8) bool {
|
|
switch endpoint {
|
|
case RestAuthentication:
|
|
return e.API.AuthenticatedSupport
|
|
case WebsocketAuthentication:
|
|
return e.API.AuthenticatedWebsocketSupport
|
|
}
|
|
return false
|
|
}
|
|
|
|
// GetName is a method that returns the name of the exchange base
|
|
func (e *Base) GetName() string {
|
|
return e.Name
|
|
}
|
|
|
|
// GetEnabledFeatures returns the exchanges enabled features
|
|
func (e *Base) GetEnabledFeatures() FeaturesEnabled {
|
|
return e.Features.Enabled
|
|
}
|
|
|
|
// GetSupportedFeatures returns the exchanges supported features
|
|
func (e *Base) GetSupportedFeatures() FeaturesSupported {
|
|
return e.Features.Supports
|
|
}
|
|
|
|
// GetPairFormat returns the pair format based on the exchange and
|
|
// asset type
|
|
func (e *Base) GetPairFormat(assetType asset.Item, requestFormat bool) (currency.PairFormat, error) {
|
|
if e.CurrencyPairs.UseGlobalFormat {
|
|
if requestFormat {
|
|
if e.CurrencyPairs.RequestFormat == nil {
|
|
return currency.PairFormat{},
|
|
errors.New("global request format is nil")
|
|
}
|
|
return *e.CurrencyPairs.RequestFormat, nil
|
|
}
|
|
|
|
if e.CurrencyPairs.ConfigFormat == nil {
|
|
return currency.PairFormat{},
|
|
errors.New("global config format is nil")
|
|
}
|
|
return *e.CurrencyPairs.ConfigFormat, nil
|
|
}
|
|
|
|
ps, err := e.CurrencyPairs.Get(assetType)
|
|
if err != nil {
|
|
return currency.PairFormat{}, err
|
|
}
|
|
|
|
if requestFormat {
|
|
if ps.RequestFormat == nil {
|
|
return currency.PairFormat{},
|
|
errors.New("asset type request format is nil")
|
|
}
|
|
return *ps.RequestFormat, nil
|
|
}
|
|
|
|
if ps.ConfigFormat == nil {
|
|
return currency.PairFormat{},
|
|
errors.New("asset type config format is nil")
|
|
}
|
|
return *ps.ConfigFormat, nil
|
|
}
|
|
|
|
// GetEnabledPairs is a method that returns the enabled currency pairs of
|
|
// the exchange by asset type, if the asset type is disabled this will return no
|
|
// enabled pairs
|
|
func (e *Base) GetEnabledPairs(a asset.Item) (currency.Pairs, error) {
|
|
err := e.CurrencyPairs.IsAssetEnabled(a)
|
|
if err != nil {
|
|
return nil, nil
|
|
}
|
|
format, err := e.GetPairFormat(a, false)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
enabledpairs, err := e.CurrencyPairs.GetPairs(a, true)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return enabledpairs.Format(format.Delimiter,
|
|
format.Index,
|
|
format.Uppercase),
|
|
nil
|
|
}
|
|
|
|
// GetRequestFormattedPairAndAssetType is a method that returns the enabled currency pair of
|
|
// along with its asset type. Only use when there is no chance of the same name crossing over
|
|
func (e *Base) GetRequestFormattedPairAndAssetType(p string) (currency.Pair, asset.Item, error) {
|
|
assetTypes := e.GetAssetTypes()
|
|
var response currency.Pair
|
|
for i := range assetTypes {
|
|
format, err := e.GetPairFormat(assetTypes[i], true)
|
|
if err != nil {
|
|
return response, assetTypes[i], err
|
|
}
|
|
|
|
pairs, err := e.CurrencyPairs.GetPairs(assetTypes[i], true)
|
|
if err != nil {
|
|
return response, assetTypes[i], err
|
|
}
|
|
|
|
for j := range pairs {
|
|
formattedPair := pairs[j].Format(format.Delimiter, format.Uppercase)
|
|
if strings.EqualFold(formattedPair.String(), p) {
|
|
return formattedPair, assetTypes[i], nil
|
|
}
|
|
}
|
|
}
|
|
return response, "", errors.New("pair not found: " + p)
|
|
}
|
|
|
|
// GetAvailablePairs is a method that returns the available currency pairs
|
|
// of the exchange by asset type
|
|
func (e *Base) GetAvailablePairs(assetType asset.Item) (currency.Pairs, error) {
|
|
format, err := e.GetPairFormat(assetType, false)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
pairs, err := e.CurrencyPairs.GetPairs(assetType, false)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return pairs.Format(format.Delimiter, format.Index, format.Uppercase), nil
|
|
}
|
|
|
|
// SupportsPair returns true or not whether a currency pair exists in the
|
|
// exchange available currencies or not
|
|
func (e *Base) SupportsPair(p currency.Pair, enabledPairs bool, assetType asset.Item) error {
|
|
if enabledPairs {
|
|
pairs, err := e.GetEnabledPairs(assetType)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if pairs.Contains(p, false) {
|
|
return nil
|
|
}
|
|
return errors.New("pair not supported")
|
|
}
|
|
|
|
avail, err := e.GetAvailablePairs(assetType)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if avail.Contains(p, false) {
|
|
return nil
|
|
}
|
|
return errors.New("pair not supported")
|
|
}
|
|
|
|
// FormatExchangeCurrencies returns a string containing
|
|
// the exchanges formatted currency pairs
|
|
func (e *Base) FormatExchangeCurrencies(pairs []currency.Pair, assetType asset.Item) (string, error) {
|
|
var currencyItems strings.Builder
|
|
pairFmt, err := e.GetPairFormat(assetType, true)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
for x := range pairs {
|
|
format, err := e.FormatExchangeCurrency(pairs[x], assetType)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
currencyItems.WriteString(format.String())
|
|
if x == len(pairs)-1 {
|
|
continue
|
|
}
|
|
currencyItems.WriteString(pairFmt.Separator)
|
|
}
|
|
|
|
if currencyItems.Len() == 0 {
|
|
return "", errors.New("returned empty string")
|
|
}
|
|
return currencyItems.String(), nil
|
|
}
|
|
|
|
// FormatExchangeCurrency is a method that formats and returns a currency pair
|
|
// based on the user currency display preferences
|
|
func (e *Base) FormatExchangeCurrency(p currency.Pair, assetType asset.Item) (currency.Pair, error) {
|
|
pairFmt, err := e.GetPairFormat(assetType, true)
|
|
if err != nil {
|
|
return currency.Pair{}, err
|
|
}
|
|
return p.Format(pairFmt.Delimiter, pairFmt.Uppercase), nil
|
|
}
|
|
|
|
// SetEnabled is a method that sets if the exchange is enabled
|
|
func (e *Base) SetEnabled(enabled bool) {
|
|
e.Enabled = enabled
|
|
}
|
|
|
|
// IsEnabled is a method that returns if the current exchange is enabled
|
|
func (e *Base) IsEnabled() bool {
|
|
return e.Enabled
|
|
}
|
|
|
|
// SetAPIKeys is a method that sets the current API keys for the exchange
|
|
func (e *Base) SetAPIKeys(apiKey, apiSecret, clientID string) {
|
|
e.API.Credentials.Key = apiKey
|
|
e.API.Credentials.ClientID = clientID
|
|
|
|
if e.API.CredentialsValidator.RequiresBase64DecodeSecret {
|
|
result, err := crypto.Base64Decode(apiSecret)
|
|
if err != nil {
|
|
e.API.AuthenticatedSupport = false
|
|
e.API.AuthenticatedWebsocketSupport = false
|
|
log.Warnf(log.ExchangeSys,
|
|
warningBase64DecryptSecretKeyFailed,
|
|
e.Name)
|
|
return
|
|
}
|
|
e.API.Credentials.Secret = string(result)
|
|
} else {
|
|
e.API.Credentials.Secret = apiSecret
|
|
}
|
|
}
|
|
|
|
// SetupDefaults sets the exchange settings based on the supplied config
|
|
func (e *Base) SetupDefaults(exch *config.ExchangeConfig) error {
|
|
e.Enabled = true
|
|
e.LoadedByConfig = true
|
|
e.Config = exch
|
|
e.Verbose = exch.Verbose
|
|
|
|
e.API.AuthenticatedSupport = exch.API.AuthenticatedSupport
|
|
e.API.AuthenticatedWebsocketSupport = exch.API.AuthenticatedWebsocketSupport
|
|
if e.API.AuthenticatedSupport || e.API.AuthenticatedWebsocketSupport {
|
|
e.SetAPIKeys(exch.API.Credentials.Key,
|
|
exch.API.Credentials.Secret,
|
|
exch.API.Credentials.ClientID)
|
|
}
|
|
|
|
if exch.HTTPTimeout <= time.Duration(0) {
|
|
exch.HTTPTimeout = DefaultHTTPTimeout
|
|
} else {
|
|
e.SetHTTPClientTimeout(exch.HTTPTimeout)
|
|
}
|
|
|
|
if exch.CurrencyPairs == nil {
|
|
exch.CurrencyPairs = new(currency.PairsManager)
|
|
}
|
|
|
|
e.HTTPDebugging = exch.HTTPDebugging
|
|
e.SetHTTPClientUserAgent(exch.HTTPUserAgent)
|
|
e.SetCurrencyPairFormat()
|
|
|
|
err := e.SetConfigPairs()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
e.SetFeatureDefaults()
|
|
err = e.SetAPIURL()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
e.SetAPICredentialDefaults()
|
|
|
|
err = e.SetClientProxyAddress(exch.ProxyAddress)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
e.BaseCurrencies = exch.BaseCurrencies
|
|
return nil
|
|
}
|
|
|
|
// AllowAuthenticatedRequest checks to see if the required fields have been set
|
|
// before sending an authenticated API request
|
|
func (e *Base) AllowAuthenticatedRequest() bool {
|
|
if e.SkipAuthCheck {
|
|
return true
|
|
}
|
|
|
|
// Individual package usage, allow request if API credentials are valid a
|
|
// and without needing to set AuthenticatedSupport to true
|
|
if !e.LoadedByConfig {
|
|
return e.ValidateAPICredentials()
|
|
}
|
|
|
|
// Bot usage, AuthenticatedSupport can be disabled by user if desired, so
|
|
// don't allow authenticated requests.
|
|
if !e.API.AuthenticatedSupport && !e.API.AuthenticatedWebsocketSupport {
|
|
return false
|
|
}
|
|
|
|
// Check to see if the user has enabled AuthenticatedSupport, but has
|
|
// invalid API credentials set and loaded by config
|
|
return e.ValidateAPICredentials()
|
|
}
|
|
|
|
// ValidateAPICredentials validates the exchanges API credentials
|
|
func (e *Base) ValidateAPICredentials() bool {
|
|
if e.API.CredentialsValidator.RequiresKey {
|
|
if e.API.Credentials.Key == "" ||
|
|
e.API.Credentials.Key == config.DefaultAPIKey {
|
|
log.Warnf(log.ExchangeSys,
|
|
"exchange %s requires API key but default/empty one set",
|
|
e.Name)
|
|
return false
|
|
}
|
|
}
|
|
|
|
if e.API.CredentialsValidator.RequiresSecret {
|
|
if e.API.Credentials.Secret == "" ||
|
|
e.API.Credentials.Secret == config.DefaultAPISecret {
|
|
log.Warnf(log.ExchangeSys,
|
|
"exchange %s requires API secret but default/empty one set",
|
|
e.Name)
|
|
return false
|
|
}
|
|
}
|
|
|
|
if e.API.CredentialsValidator.RequiresPEM {
|
|
if e.API.Credentials.PEMKey == "" ||
|
|
strings.Contains(e.API.Credentials.PEMKey, "JUSTADUMMY") {
|
|
log.Warnf(log.ExchangeSys,
|
|
"exchange %s requires API PEM key but default/empty one set",
|
|
e.Name)
|
|
return false
|
|
}
|
|
}
|
|
|
|
if e.API.CredentialsValidator.RequiresClientID {
|
|
if e.API.Credentials.ClientID == "" ||
|
|
e.API.Credentials.ClientID == config.DefaultAPIClientID {
|
|
log.Warnf(log.ExchangeSys,
|
|
"exchange %s requires API ClientID but default/empty one set",
|
|
e.Name)
|
|
return false
|
|
}
|
|
}
|
|
|
|
if e.API.CredentialsValidator.RequiresBase64DecodeSecret && !e.LoadedByConfig {
|
|
_, err := crypto.Base64Decode(e.API.Credentials.Secret)
|
|
if err != nil {
|
|
log.Warnf(log.ExchangeSys,
|
|
"exchange %s API secret base64 decode failed: %s",
|
|
e.Name, err)
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// SetPairs sets the exchange currency pairs for either enabledPairs or
|
|
// availablePairs
|
|
func (e *Base) SetPairs(pairs currency.Pairs, assetType asset.Item, enabled bool) error {
|
|
if len(pairs) == 0 {
|
|
return fmt.Errorf("%s SetPairs error - pairs is empty", e.Name)
|
|
}
|
|
|
|
pairFmt, err := e.GetPairFormat(assetType, false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var newPairs currency.Pairs
|
|
for x := range pairs {
|
|
newPairs = append(newPairs, pairs[x].Format(pairFmt.Delimiter,
|
|
pairFmt.Uppercase))
|
|
}
|
|
|
|
e.CurrencyPairs.StorePairs(assetType, newPairs, enabled)
|
|
e.Config.CurrencyPairs.StorePairs(assetType, newPairs, enabled)
|
|
return nil
|
|
}
|
|
|
|
// UpdatePairs updates the exchange currency pairs for either enabledPairs or
|
|
// availablePairs
|
|
func (e *Base) UpdatePairs(exchangeProducts currency.Pairs, assetType asset.Item, enabled, force bool) error {
|
|
exchangeProducts = exchangeProducts.Upper()
|
|
var products currency.Pairs
|
|
for x := range exchangeProducts {
|
|
if exchangeProducts[x].String() == "" {
|
|
continue
|
|
}
|
|
products = append(products, exchangeProducts[x])
|
|
}
|
|
|
|
var updateType string
|
|
targetPairs, err := e.CurrencyPairs.GetPairs(assetType, enabled)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if enabled {
|
|
updateType = "enabled"
|
|
} else {
|
|
updateType = "available"
|
|
}
|
|
|
|
newPairs, removedPairs := targetPairs.FindDifferences(products)
|
|
if force || len(newPairs) > 0 || len(removedPairs) > 0 {
|
|
if force {
|
|
log.Debugf(log.ExchangeSys,
|
|
"%s forced update of %s [%v] pairs.",
|
|
e.Name,
|
|
updateType,
|
|
strings.ToUpper(assetType.String()))
|
|
} else {
|
|
if len(newPairs) > 0 {
|
|
log.Debugf(log.ExchangeSys,
|
|
"%s Updating %s pairs [%v] - Added: %s.\n",
|
|
e.Name,
|
|
updateType,
|
|
strings.ToUpper(assetType.String()),
|
|
newPairs)
|
|
}
|
|
if len(removedPairs) > 0 {
|
|
log.Debugf(log.ExchangeSys,
|
|
"%s Updating %s pairs [%v] - Removed: %s.\n",
|
|
e.Name,
|
|
updateType,
|
|
strings.ToUpper(assetType.String()),
|
|
removedPairs)
|
|
}
|
|
}
|
|
|
|
e.Config.CurrencyPairs.StorePairs(assetType, products, enabled)
|
|
e.CurrencyPairs.StorePairs(assetType, products, enabled)
|
|
|
|
if !enabled {
|
|
// If available pairs are changed we will remove currency pair items
|
|
// that are still included in the enabled pairs list.
|
|
enabledPairs, err := e.CurrencyPairs.GetPairs(assetType, true)
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
_, remove := enabledPairs.FindDifferences(products)
|
|
for i := range remove {
|
|
enabledPairs = enabledPairs.Remove(remove[i])
|
|
}
|
|
|
|
if len(remove) > 0 {
|
|
log.Debugf(log.ExchangeSys,
|
|
"%s Checked and updated enabled pairs [%v] - Removed: %s.\n",
|
|
e.Name,
|
|
strings.ToUpper(assetType.String()),
|
|
remove)
|
|
|
|
e.Config.CurrencyPairs.StorePairs(assetType, enabledPairs, true)
|
|
e.CurrencyPairs.StorePairs(assetType, enabledPairs, true)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SetAPIURL sets configuration API URL for an exchange
|
|
func (e *Base) SetAPIURL() error {
|
|
if e.Config.API.Endpoints.URL == "" || e.Config.API.Endpoints.URLSecondary == "" {
|
|
return fmt.Errorf("exchange %s: SetAPIURL error. URL vals are empty", e.Name)
|
|
}
|
|
|
|
checkInsecureEndpoint := func(endpoint string) {
|
|
if strings.Contains(endpoint, "https") {
|
|
return
|
|
}
|
|
log.Warnf(log.ExchangeSys,
|
|
"%s is using HTTP instead of HTTPS [%s] for API functionality, an"+
|
|
" attacker could eavesdrop on this connection. Use at your"+
|
|
" own risk.",
|
|
e.Name, endpoint)
|
|
}
|
|
|
|
if e.Config.API.Endpoints.URL != config.APIURLNonDefaultMessage {
|
|
e.API.Endpoints.URL = e.Config.API.Endpoints.URL
|
|
checkInsecureEndpoint(e.API.Endpoints.URL)
|
|
}
|
|
if e.Config.API.Endpoints.URLSecondary != config.APIURLNonDefaultMessage {
|
|
e.API.Endpoints.URLSecondary = e.Config.API.Endpoints.URLSecondary
|
|
checkInsecureEndpoint(e.API.Endpoints.URLSecondary)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetAPIURL returns the set API URL
|
|
func (e *Base) GetAPIURL() string {
|
|
return e.API.Endpoints.URL
|
|
}
|
|
|
|
// GetSecondaryAPIURL returns the set Secondary API URL
|
|
func (e *Base) GetSecondaryAPIURL() string {
|
|
return e.API.Endpoints.URLSecondary
|
|
}
|
|
|
|
// GetAPIURLDefault returns exchange default URL
|
|
func (e *Base) GetAPIURLDefault() string {
|
|
return e.API.Endpoints.URLDefault
|
|
}
|
|
|
|
// GetAPIURLSecondaryDefault returns exchange default secondary URL
|
|
func (e *Base) GetAPIURLSecondaryDefault() string {
|
|
return e.API.Endpoints.URLSecondaryDefault
|
|
}
|
|
|
|
// SupportsREST returns whether or not the exchange supports
|
|
// REST
|
|
func (e *Base) SupportsREST() bool {
|
|
return e.Features.Supports.REST
|
|
}
|
|
|
|
// GetWithdrawPermissions passes through the exchange's withdraw permissions
|
|
func (e *Base) GetWithdrawPermissions() uint32 {
|
|
return e.Features.Supports.WithdrawPermissions
|
|
}
|
|
|
|
// SupportsWithdrawPermissions compares the supplied permissions with the exchange's to verify they're supported
|
|
func (e *Base) SupportsWithdrawPermissions(permissions uint32) bool {
|
|
exchangePermissions := e.GetWithdrawPermissions()
|
|
return permissions&exchangePermissions == permissions
|
|
}
|
|
|
|
// FormatWithdrawPermissions will return each of the exchange's compatible withdrawal methods in readable form
|
|
func (e *Base) FormatWithdrawPermissions() string {
|
|
var services []string
|
|
for i := 0; i < 32; i++ {
|
|
var check uint32 = 1 << uint32(i)
|
|
if e.GetWithdrawPermissions()&check != 0 {
|
|
switch check {
|
|
case AutoWithdrawCrypto:
|
|
services = append(services, AutoWithdrawCryptoText)
|
|
case AutoWithdrawCryptoWithAPIPermission:
|
|
services = append(services, AutoWithdrawCryptoWithAPIPermissionText)
|
|
case AutoWithdrawCryptoWithSetup:
|
|
services = append(services, AutoWithdrawCryptoWithSetupText)
|
|
case WithdrawCryptoWith2FA:
|
|
services = append(services, WithdrawCryptoWith2FAText)
|
|
case WithdrawCryptoWithSMS:
|
|
services = append(services, WithdrawCryptoWithSMSText)
|
|
case WithdrawCryptoWithEmail:
|
|
services = append(services, WithdrawCryptoWithEmailText)
|
|
case WithdrawCryptoWithWebsiteApproval:
|
|
services = append(services, WithdrawCryptoWithWebsiteApprovalText)
|
|
case WithdrawCryptoWithAPIPermission:
|
|
services = append(services, WithdrawCryptoWithAPIPermissionText)
|
|
case AutoWithdrawFiat:
|
|
services = append(services, AutoWithdrawFiatText)
|
|
case AutoWithdrawFiatWithAPIPermission:
|
|
services = append(services, AutoWithdrawFiatWithAPIPermissionText)
|
|
case AutoWithdrawFiatWithSetup:
|
|
services = append(services, AutoWithdrawFiatWithSetupText)
|
|
case WithdrawFiatWith2FA:
|
|
services = append(services, WithdrawFiatWith2FAText)
|
|
case WithdrawFiatWithSMS:
|
|
services = append(services, WithdrawFiatWithSMSText)
|
|
case WithdrawFiatWithEmail:
|
|
services = append(services, WithdrawFiatWithEmailText)
|
|
case WithdrawFiatWithWebsiteApproval:
|
|
services = append(services, WithdrawFiatWithWebsiteApprovalText)
|
|
case WithdrawFiatWithAPIPermission:
|
|
services = append(services, WithdrawFiatWithAPIPermissionText)
|
|
case WithdrawCryptoViaWebsiteOnly:
|
|
services = append(services, WithdrawCryptoViaWebsiteOnlyText)
|
|
case WithdrawFiatViaWebsiteOnly:
|
|
services = append(services, WithdrawFiatViaWebsiteOnlyText)
|
|
case NoFiatWithdrawals:
|
|
services = append(services, NoFiatWithdrawalsText)
|
|
default:
|
|
services = append(services, fmt.Sprintf("%s[1<<%v]", UnknownWithdrawalTypeText, i))
|
|
}
|
|
}
|
|
}
|
|
if len(services) > 0 {
|
|
return strings.Join(services, " & ")
|
|
}
|
|
|
|
return NoAPIWithdrawalMethodsText
|
|
}
|
|
|
|
// SupportsAsset whether or not the supplied asset is supported
|
|
// by the exchange
|
|
func (e *Base) SupportsAsset(a asset.Item) bool {
|
|
_, ok := e.CurrencyPairs.Pairs[a]
|
|
return ok
|
|
}
|
|
|
|
// PrintEnabledPairs prints the exchanges enabled asset pairs
|
|
func (e *Base) PrintEnabledPairs() {
|
|
for k, v := range e.CurrencyPairs.Pairs {
|
|
log.Infof(log.ExchangeSys, "%s Asset type %v:\n\t Enabled pairs: %v",
|
|
e.Name, strings.ToUpper(k.String()), v.Enabled)
|
|
}
|
|
}
|
|
|
|
// GetBase returns the exchange base
|
|
func (e *Base) GetBase() *Base { return e }
|
|
|
|
// CheckTransientError catches transient errors and returns nil if found, used
|
|
// for validation of API credentials
|
|
func (e *Base) CheckTransientError(err error) error {
|
|
if _, ok := err.(net.Error); ok {
|
|
log.Warnf(log.ExchangeSys,
|
|
"%s net error captured, will not disable authentication %s",
|
|
e.Name,
|
|
err)
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
// DisableRateLimiter disables the rate limiting system for the exchange
|
|
func (e *Base) DisableRateLimiter() error {
|
|
return e.Requester.DisableRateLimiter()
|
|
}
|
|
|
|
// EnableRateLimiter enables the rate limiting system for the exchange
|
|
func (e *Base) EnableRateLimiter() error {
|
|
return e.Requester.EnableRateLimiter()
|
|
}
|
|
|
|
// StoreAssetPairFormat initialises and stores a defined asset format
|
|
func (e *Base) StoreAssetPairFormat(a asset.Item, f currency.PairStore) error {
|
|
if a.String() == "" {
|
|
return fmt.Errorf("%s cannot add to pairs manager, no asset provided",
|
|
e.Name)
|
|
}
|
|
|
|
if f.RequestFormat == nil {
|
|
return fmt.Errorf("%s cannot add to pairs manager, request pair format not provided",
|
|
e.Name)
|
|
}
|
|
|
|
if f.ConfigFormat == nil {
|
|
return fmt.Errorf("%s cannot add to pairs manager, config pair format not provided",
|
|
e.Name)
|
|
}
|
|
|
|
if e.CurrencyPairs.Pairs == nil {
|
|
e.CurrencyPairs.Pairs = make(map[asset.Item]*currency.PairStore)
|
|
}
|
|
|
|
e.CurrencyPairs.Pairs[a] = &f
|
|
return nil
|
|
}
|
|
|
|
// SetGlobalPairsManager sets defined asset and pairs management system with
|
|
// with global formatting
|
|
func (e *Base) SetGlobalPairsManager(request, config *currency.PairFormat, assets ...asset.Item) error {
|
|
if request == nil {
|
|
return fmt.Errorf("%s cannot set pairs manager, request pair format not provided",
|
|
e.Name)
|
|
}
|
|
|
|
if config == nil {
|
|
return fmt.Errorf("%s cannot set pairs manager, config pair format not provided",
|
|
e.Name)
|
|
}
|
|
|
|
if len(assets) == 0 {
|
|
return fmt.Errorf("%s cannot set pairs manager, no assets provided",
|
|
e.Name)
|
|
}
|
|
|
|
e.CurrencyPairs.UseGlobalFormat = true
|
|
e.CurrencyPairs.RequestFormat = request
|
|
e.CurrencyPairs.ConfigFormat = config
|
|
|
|
if e.CurrencyPairs.Pairs != nil {
|
|
return fmt.Errorf("%s cannot set pairs manager, pairs already set",
|
|
e.Name)
|
|
}
|
|
|
|
e.CurrencyPairs.Pairs = make(map[asset.Item]*currency.PairStore)
|
|
|
|
for i := range assets {
|
|
if assets[i].String() == "" {
|
|
e.CurrencyPairs.Pairs = nil
|
|
return fmt.Errorf("%s cannot set pairs manager, asset is empty string",
|
|
e.Name)
|
|
}
|
|
e.CurrencyPairs.Pairs[assets[i]] = new(currency.PairStore)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// GetWebsocket returns a pointer to the exchange websocket
|
|
func (e *Base) GetWebsocket() (*stream.Websocket, error) {
|
|
if e.Websocket == nil {
|
|
return nil, common.ErrFunctionNotSupported
|
|
}
|
|
return e.Websocket, nil
|
|
}
|
|
|
|
// SupportsWebsocket returns whether or not the exchange supports
|
|
// websocket
|
|
func (e *Base) SupportsWebsocket() bool {
|
|
return e.Features.Supports.Websocket
|
|
}
|
|
|
|
// IsWebsocketEnabled returns whether or not the exchange has its
|
|
// websocket client enabled
|
|
func (e *Base) IsWebsocketEnabled() bool {
|
|
if e.Websocket == nil {
|
|
return false
|
|
}
|
|
return e.Websocket.IsEnabled()
|
|
}
|
|
|
|
// FlushWebsocketChannels refreshes websocket channel subscriptions based on
|
|
// websocket features. Used in the event of a pair/asset or subscription change.
|
|
func (e *Base) FlushWebsocketChannels() error {
|
|
if e.Websocket == nil {
|
|
return nil
|
|
}
|
|
return e.Websocket.FlushChannels()
|
|
}
|
|
|
|
// SubscribeToWebsocketChannels appends to ChannelsToSubscribe
|
|
// which lets websocket.manageSubscriptions handle subscribing
|
|
func (e *Base) SubscribeToWebsocketChannels(channels []stream.ChannelSubscription) error {
|
|
if e.Websocket == nil {
|
|
return common.ErrFunctionNotSupported
|
|
}
|
|
return e.Websocket.SubscribeToChannels(channels)
|
|
}
|
|
|
|
// UnsubscribeToWebsocketChannels removes from ChannelsToSubscribe
|
|
// which lets websocket.manageSubscriptions handle unsubscribing
|
|
func (e *Base) UnsubscribeToWebsocketChannels(channels []stream.ChannelSubscription) error {
|
|
if e.Websocket == nil {
|
|
return common.ErrFunctionNotSupported
|
|
}
|
|
return e.Websocket.UnsubscribeChannels(channels)
|
|
}
|
|
|
|
// GetSubscriptions returns a copied list of subscriptions
|
|
func (e *Base) GetSubscriptions() ([]stream.ChannelSubscription, error) {
|
|
if e.Websocket == nil {
|
|
return nil, common.ErrFunctionNotSupported
|
|
}
|
|
return e.Websocket.GetSubscriptions(), nil
|
|
}
|
|
|
|
// AuthenticateWebsocket sends an authentication message to the websocket
|
|
func (e *Base) AuthenticateWebsocket() error {
|
|
return common.ErrFunctionNotSupported
|
|
}
|
|
|
|
// KlineIntervalEnabled returns if requested interval is enabled on exchange
|
|
func (e *Base) KlineIntervalEnabled(in kline.Interval) bool {
|
|
return e.Features.Enabled.Kline.Intervals[in.Word()]
|
|
}
|
|
|
|
// FormatExchangeKlineInterval returns Interval to string
|
|
// Exchanges can override this if they require custom formatting
|
|
func (e *Base) FormatExchangeKlineInterval(in kline.Interval) string {
|
|
return strconv.FormatFloat(in.Duration().Seconds(), 'f', 0, 64)
|
|
}
|