Files
gocryptotrader/config/config_types.go
Andrew f6fd94ea69 Engine: Scripting support (#383)
* WIP

* updated appveyor and increased deadline 5 seconds due to increased linters being added

* revert files to upstream/engine

* WIP

* WIP

* mod file changes

* added script manager

* Added manager/and cli interfaces to scripting

* Added script task handler

* WIP - Added timer/repeat support and fleshed out wrapper further

* autoload support added + WIP

* WIP commit

* added account balance info

* btc markets temp work around

* WIP - merged with upstream for new order package BTC Markets responses broken

* Cancel order wrapper WIP

*  order wrapper update

* Added test coverage for VM

* moved to map for VM List shutdown of all VM now handled added gctcli commands for list and stop of running scripts

* added override to load/execute for path

* fixed incorrect channel shutdown added further test coverage and restructured gctcli commands into sub commands

* increased test coverage for packages

* Added docs cleaned up tests and example scripts

* Test coverage increased for module/gct/exchange package

* windows fixes

* merged upstream/engine

* WIP

* logger fixes - removed pointer to bool check removed duplicate test check for logger

* remove unused mutex

* added inital upload support

* fix linter issues for go-fmt

* added zip support for uploading and added base for fund withdrawing

* changed error return types and also log errors, fix zip path issue

* improved error outputs and code flow

* pairs response fix added protobuf defs for stop all and list all

* added stop all running scripts general clean up and moved across to OrderManager

* linter fixes (gofmt)

* added list all command

* rewrote zip handler to be cleaner also fixed file overwrite on upload

* added query command reworked tests

* added further error checking to compileandrun corrected use of pointers for accountinfo

* bumped tengo version

* Removed named returns reworded log messages removed unused falseptr

* WIP

* Added virutal machine limit improved config options

* added model for script event added upload validation

* script_event table has been completed, tests for wrapper functions implemented

* README updates

* reverted changes opened new PR to move withdraw struct outs

* intial work on adding withdraw support after merger of withdraw package

* started work on examples

* Added crypto withdraw support

* fix switch case assignment and gofmt project

* Reworking Fiat withdraw request pending #402

* removed double pointer call

* added withdraw support for fiat  currencies

* added tests for withdraw methods increased readme

* removed local tengo require and also fix linter issues

* Added default log size const added basic test for invalid script execution

* First pass at moving wrapper to validator package to allow proper validation of uploaded scripts

* Added script details to README added config test added test for no file extension

* moved tests to const and fixed incorrect pathing

* added test coverage to withdraw package

* corrected file close handling

* point to included configtest.json

* extended validator support when a script is uploaded

* Bug fix on bool logic

* Added mutex

* Don't create autit events on test execution

* reverted common to master

* moved file rename to unix timestamp format

* converted logger enabled back to pointer as i need nilness check also moved scriptid to text over blob

* started work on autoload add/remove support

* First round of PR fixes (mostly commented exports)

* Moved GCTScript load to last, removed unneeded error from cleanup()

* Comment clairty for AuitEventID

* added autoload add/remove command to cli

* added tests for autoload

* Test updates for Exchanges

* linter fixes (gofmt)

* Removed double check of engine pointer

* remove possible nil pointer on GetSpecificTicker

* Fixed not closing file handler on write that causes archive removal to fail

* file handler Close clean ups

* corrected spelling on error return and return invalid name n autoload

* moved strings to cosnt moved bool pointer creation to convert package

* new zip extractor added

* Validation has been added to archive uploads

* removed shadow var on err

* added ok check to conversion

* converted condition check

* basic test for zip extract added

* new zip handler

* reverted back to old atomic loading system

* removed shadow err

* lets add a new line

* added space to error return

* command line toggle for script now works properly

* readme updated

* set configLoaded to true

* check for configLoaded condition

* added mutex to allow for multiple access on virtual machine increased test coverage disable script manager if scripting is disabled

* linked up to enable/disablesubsystem commands

* added start/stop example to readme

* reworked logic on test as check should be done on Load()

* updated to tengo v2

* linters

* lower time on ntp client to stop slippage

* remove all fails if any fail validtion from an archive

* remove vm from list if timer is invalid

* removed shadow on err

* remove config creation from NTPCheck test

* WIP testing DB changes

* add unique constraint

* WIP: created has many model

* linters run

* basic sqlite3 support added for new database format

* linters run

* Added test coverage for script repo

* removed unused print

* updated env vars for CI instances

* updated env vars for CI instances

* Updated test packages

* Test updates for postgresql

* removed invalid tests from postgres

* remove duplication of struct and improved code flow

* general cleanup

* wording changes on log output

* use databasemgr logger and add support for autoload without file extension

* corrected test naming

* return correct error

* return correct error again version 82

* store scriptdata on creation

* Hello

* Errorln -> Errorf

* Removed unused vars

* Read me updates

* testing without parallel

* comment on exported type

* added nil check against VM for test

* add debugging information

* gofmt

* remove verbose and data sent to channel

* Added debug information

* linter fixes (gofmt)

* remove unused CompileAndRun() call

* test sleep to see if issue is timing related

* semi-concurrent map fixes

* one day i will run gofmt or setup precommit hooks

* new line :D

* increased test coverage

* added correct sleep time

* Moved over to sync map

* linter fixes (gofmt)

* goimports

* moved VM related methods to vm.go

* new line at end of file

* trying increased timeout on golangci-lint for appveyor

* add debugging information

* removed timeout

* reworked timeout logic

* linter fixes (gofmt)

* increased test coverage

* increased test coverage

* one day i will run gofmt or setup precommit hooks

* removed unused exchange test

* increased golangci-lint timeout

* Added nil check on shutdown and test coverage for it lowered timeout back to 1:30

* reworked ID system

* removed script hash as it was unused

* added comments on exported methods and read me update

* reorder code

* removed to atomic.value for test execution flag

* increased test coverage

* move add further up execution

* point to correct script file
2020-01-23 13:54:04 +11:00

451 lines
19 KiB
Go

package config
import (
"fmt"
"strings"
"sync"
"time"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base"
"github.com/thrasher-corp/gocryptotrader/database"
"github.com/thrasher-corp/gocryptotrader/exchanges/protocol"
gctscript "github.com/thrasher-corp/gocryptotrader/gctscript/vm"
log "github.com/thrasher-corp/gocryptotrader/logger"
"github.com/thrasher-corp/gocryptotrader/portfolio"
)
// Constants declared here are filename strings and test strings
const (
FXProviderFixer = "fixer"
EncryptedFile = "config.dat"
File = "config.json"
TestFile = "../testdata/configtest.json"
fileEncryptionPrompt = 0
fileEncryptionEnabled = 1
fileEncryptionDisabled = -1
pairsLastUpdatedWarningThreshold = 30 // 30 days
defaultHTTPTimeout = time.Second * 15
defaultWebsocketResponseCheckTimeout = time.Millisecond * 30
defaultWebsocketResponseMaxLimit = time.Second * 7
defaultWebsocketOrderbookBufferLimit = 5
defaultWebsocketTrafficTimeout = time.Second * 30
maxAuthFailures = 3
defaultNTPAllowedDifference = 50000000
defaultNTPAllowedNegativeDifference = 50000000
DefaultAPIKey = "Key"
DefaultAPISecret = "Secret"
DefaultAPIClientID = "ClientID"
)
// Constants here hold some messages
const (
ErrExchangeNameEmpty = "exchange #%d name is empty"
ErrExchangeAvailablePairsEmpty = "exchange %s available pairs is empty"
ErrExchangeEnabledPairsEmpty = "exchange %s enabled pairs is empty"
ErrExchangeBaseCurrenciesEmpty = "exchange %s base currencies is empty"
ErrExchangeNotFound = "exchange %s not found"
ErrNoEnabledExchanges = "no exchanges enabled"
ErrCryptocurrenciesEmpty = "cryptocurrencies variable is empty"
ErrFailureOpeningConfig = "fatal error opening %s file. Error: %s"
ErrCheckingConfigValues = "fatal error checking config values. Error: %s"
ErrSavingConfigBytesMismatch = "config file %q bytes comparison doesn't match, read %s expected %s"
ErrBankAccountNotFound = "bank account ID: %v not found"
WarningWebserverCredentialValuesEmpty = "webserver support disabled due to empty Username/Password values"
WarningWebserverListenAddressInvalid = "webserver support disabled due to invalid listen address"
WarningExchangeAuthAPIDefaultOrEmptyValues = "exchange %s authenticated API support disabled due to default/empty APIKey/Secret/ClientID values"
WarningPairsLastUpdatedThresholdExceeded = "exchange %s last manual update of available currency pairs has exceeded %d days. Manual update required!"
)
// Constants here define unset default values displayed in the config.json
// file
const (
APIURLNonDefaultMessage = "NON_DEFAULT_HTTP_LINK_TO_EXCHANGE_API"
WebsocketURLNonDefaultMessage = "NON_DEFAULT_HTTP_LINK_TO_WEBSOCKET_EXCHANGE_API"
DefaultUnsetAPIKey = "Key"
DefaultUnsetAPISecret = "Secret"
DefaultUnsetAccountPlan = "accountPlan"
DefaultForexProviderExchangeRatesAPI = "ExchangeRates"
)
// Variables here are used for configuration
var (
Cfg Config
IsInitialSetup bool
testBypass bool
m sync.Mutex
)
// Config is the overarching object that holds all the information for
// prestart management of Portfolio, Communications, Webserver and Enabled
// Exchanges
type Config struct {
Name string `json:"name"`
EncryptConfig int `json:"encryptConfig"`
GlobalHTTPTimeout time.Duration `json:"globalHTTPTimeout"`
Database database.Config `json:"database"`
Logging log.Config `json:"logging"`
ConnectionMonitor ConnectionMonitorConfig `json:"connectionMonitor"`
Profiler ProfilerConfig `json:"profiler"`
NTPClient NTPClientConfig `json:"ntpclient"`
GCTScript gctscript.Config `json:"gctscript"`
Currency CurrencyConfig `json:"currencyConfig"`
Communications CommunicationsConfig `json:"communications"`
RemoteControl RemoteControlConfig `json:"remoteControl"`
Portfolio portfolio.Base `json:"portfolioAddresses"`
Exchanges []ExchangeConfig `json:"exchanges"`
BankAccounts []BankAccount `json:"bankAccounts"`
// Deprecated config settings, will be removed at a future date
Webserver *WebserverConfig `json:"webserver,omitempty"`
CurrencyPairFormat *CurrencyPairFormatConfig `json:"currencyPairFormat,omitempty"`
FiatDisplayCurrency *currency.Code `json:"fiatDispayCurrency,omitempty"`
Cryptocurrencies *currency.Currencies `json:"cryptocurrencies,omitempty"`
SMS *SMSGlobalConfig `json:"smsGlobal,omitempty"`
}
// ConnectionMonitorConfig defines the connection monitor variables to ensure
// that there is internet connectivity
type ConnectionMonitorConfig struct {
DNSList []string `json:"preferredDNSList"`
PublicDomainList []string `json:"preferredDomainList"`
CheckInterval time.Duration `json:"checkInterval"`
}
// ExchangeConfig holds all the information needed for each enabled Exchange.
type ExchangeConfig struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
UseSandbox bool `json:"useSandbox,omitempty"`
HTTPTimeout time.Duration `json:"httpTimeout"`
HTTPUserAgent string `json:"httpUserAgent,omitempty"`
HTTPDebugging bool `json:"httpDebugging,omitempty"`
HTTPRateLimiter *HTTPRateLimitConfig `json:"httpRateLimiter,omitempty"`
WebsocketResponseCheckTimeout time.Duration `json:"websocketResponseCheckTimeout"`
WebsocketResponseMaxLimit time.Duration `json:"websocketResponseMaxLimit"`
WebsocketTrafficTimeout time.Duration `json:"websocketTrafficTimeout"`
WebsocketOrderbookBufferLimit int `json:"websocketOrderbookBufferLimit"`
ProxyAddress string `json:"proxyAddress,omitempty"`
BaseCurrencies currency.Currencies `json:"baseCurrencies"`
CurrencyPairs *currency.PairsManager `json:"currencyPairs"`
API APIConfig `json:"api"`
Features *FeaturesConfig `json:"features"`
BankAccounts []BankAccount `json:"bankAccounts,omitempty"`
// Deprecated settings which will be removed in a future update
AvailablePairs *currency.Pairs `json:"availablePairs,omitempty"`
EnabledPairs *currency.Pairs `json:"enabledPairs,omitempty"`
AssetTypes *string `json:"assetTypes,omitempty"`
PairsLastUpdated *int64 `json:"pairsLastUpdated,omitempty"`
ConfigCurrencyPairFormat *currency.PairFormat `json:"configCurrencyPairFormat,omitempty"`
RequestCurrencyPairFormat *currency.PairFormat `json:"requestCurrencyPairFormat,omitempty"`
AuthenticatedAPISupport *bool `json:"authenticatedApiSupport,omitempty"`
AuthenticatedWebsocketAPISupport *bool `json:"authenticatedWebsocketApiSupport,omitempty"`
APIKey *string `json:"apiKey,omitempty"`
APISecret *string `json:"apiSecret,omitempty"`
APIAuthPEMKeySupport *bool `json:"apiAuthPemKeySupport,omitempty"`
APIAuthPEMKey *string `json:"apiAuthPemKey,omitempty"`
APIURL *string `json:"apiUrl,omitempty"`
APIURLSecondary *string `json:"apiUrlSecondary,omitempty"`
ClientID *string `json:"clientId,omitempty"`
SupportsAutoPairUpdates *bool `json:"supportsAutoPairUpdates,omitempty"`
Websocket *bool `json:"websocket,omitempty"`
WebsocketURL *string `json:"websocketUrl,omitempty"`
}
// ProfilerConfig defines the profiler configuration to enable pprof
type ProfilerConfig struct {
Enabled bool `json:"enabled"`
}
// NTPClientConfig defines a network time protocol configuration to allow for
// positive and negative differences
type NTPClientConfig struct {
Level int `json:"enabled"`
Pool []string `json:"pool"`
AllowedDifference *time.Duration `json:"allowedDifference"`
AllowedNegativeDifference *time.Duration `json:"allowedNegativeDifference"`
}
// GRPCConfig stores the gRPC settings
type GRPCConfig struct {
Enabled bool `json:"enabled"`
ListenAddress string `json:"listenAddress"`
GRPCProxyEnabled bool `json:"grpcProxyEnabled"`
GRPCProxyListenAddress string `json:"grpcProxyListenAddress"`
}
// DepcrecatedRPCConfig stores the deprecatedRPCConfig settings
type DepcrecatedRPCConfig struct {
Enabled bool `json:"enabled"`
ListenAddress string `json:"listenAddress"`
}
// WebsocketRPCConfig stores the websocket config info
type WebsocketRPCConfig struct {
Enabled bool `json:"enabled"`
ListenAddress string `json:"listenAddress"`
ConnectionLimit int `json:"connectionLimit"`
MaxAuthFailures int `json:"maxAuthFailures"`
AllowInsecureOrigin bool `json:"allowInsecureOrigin"`
}
// RemoteControlConfig stores the RPC services config
type RemoteControlConfig struct {
Username string `json:"username"`
Password string `json:"password"`
GRPC GRPCConfig `json:"gRPC"`
DeprecatedRPC DepcrecatedRPCConfig `json:"deprecatedRPC"`
WebsocketRPC WebsocketRPCConfig `json:"websocketRPC"`
}
// WebserverConfig stores the old webserver config
type WebserverConfig struct {
Enabled bool `json:"enabled"`
AdminUsername string `json:"adminUsername"`
AdminPassword string `json:"adminPassword"`
ListenAddress string `json:"listenAddress"`
WebsocketConnectionLimit int `json:"websocketConnectionLimit"`
WebsocketMaxAuthFailures int `json:"websocketMaxAuthFailures"`
WebsocketAllowInsecureOrigin bool `json:"websocketAllowInsecureOrigin"`
}
// Post holds the bot configuration data
type Post struct {
Data Config `json:"data"`
}
// CurrencyPairFormatConfig stores the users preferred currency pair display
type CurrencyPairFormatConfig struct {
Uppercase bool `json:"uppercase"`
Delimiter string `json:"delimiter,omitempty"`
Separator string `json:"separator,omitempty"`
Index string `json:"index,omitempty"`
}
// BankAccount holds differing bank account details by supported funding
// currency
type BankAccount struct {
Enabled bool `json:"enabled"`
ID string `json:"id,omitempty"`
BankName string `json:"bankName"`
BankAddress string `json:"bankAddress"`
BankPostalCode string `json:"bankPostalCode"`
BankPostalCity string `json:"bankPostalCity"`
BankCountry string `json:"bankCountry"`
AccountName string `json:"accountName"`
AccountNumber string `json:"accountNumber"`
SWIFTCode string `json:"swiftCode"`
IBAN string `json:"iban"`
BSBNumber string `json:"bsbNumber,omitempty"`
SupportedCurrencies string `json:"supportedCurrencies"`
SupportedExchanges string `json:"supportedExchanges,omitempty"`
}
// Validate validates bank account settings
func (b *BankAccount) Validate() error {
if b.BankName == "" ||
b.BankAddress == "" ||
b.BankPostalCode == "" ||
b.BankPostalCity == "" ||
b.BankCountry == "" ||
b.AccountName == "" ||
b.SupportedCurrencies == "" {
return fmt.Errorf(
"banking details for %s is enabled but variables not set correctly",
b.BankName)
}
if b.SupportedExchanges == "" {
b.SupportedExchanges = "ALL"
}
if strings.Contains(strings.ToUpper(
b.SupportedCurrencies),
currency.AUD.String()) {
if b.BSBNumber == "" ||
b.SWIFTCode == "" {
return fmt.Errorf(
"banking details for %s is enabled but BSB/SWIFT values not set",
b.BankName)
}
} else {
// Either IBAN or SWIFT code is OK
if b.IBAN == "" && b.SWIFTCode == "" {
return fmt.Errorf(
"banking details for %s is enabled but SWIFT/IBAN values not set",
b.BankName)
}
}
return nil
}
// BankTransaction defines a related banking transaction
type BankTransaction struct {
ReferenceNumber string `json:"referenceNumber"`
TransactionNumber string `json:"transactionNumber"`
PaymentInstructions string `json:"paymentInstructions"`
}
// CurrencyConfig holds all the information needed for currency related manipulation
type CurrencyConfig struct {
ForexProviders []base.Settings `json:"forexProviders"`
CryptocurrencyProvider CryptocurrencyProvider `json:"cryptocurrencyProvider"`
Cryptocurrencies currency.Currencies `json:"cryptocurrencies"`
CurrencyPairFormat *CurrencyPairFormatConfig `json:"currencyPairFormat"`
FiatDisplayCurrency currency.Code `json:"fiatDisplayCurrency"`
CurrencyFileUpdateDuration time.Duration `json:"currencyFileUpdateDuration"`
ForeignExchangeUpdateDuration time.Duration `json:"foreignExchangeUpdateDuration"`
}
// CryptocurrencyProvider defines coinmarketcap tools
type CryptocurrencyProvider struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
APIkey string `json:"apiKey"`
AccountPlan string `json:"accountPlan"`
}
// CommunicationsConfig holds all the information needed for each
// enabled communication package
type CommunicationsConfig struct {
SlackConfig SlackConfig `json:"slack"`
SMSGlobalConfig SMSGlobalConfig `json:"smsGlobal"`
SMTPConfig SMTPConfig `json:"smtp"`
TelegramConfig TelegramConfig `json:"telegram"`
}
// IsAnyEnabled returns whether or any any comms relayers
// are enabled
func (c *CommunicationsConfig) IsAnyEnabled() bool {
if c.SMSGlobalConfig.Enabled ||
c.SMTPConfig.Enabled ||
c.SlackConfig.Enabled ||
c.TelegramConfig.Enabled {
return true
}
return false
}
// SlackConfig holds all variables to start and run the Slack package
type SlackConfig struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
TargetChannel string `json:"targetChannel"`
VerificationToken string `json:"verificationToken"`
}
// SMSContact stores the SMS contact info
type SMSContact struct {
Name string `json:"name"`
Number string `json:"number"`
Enabled bool `json:"enabled"`
}
// SMSGlobalConfig structure holds all the variables you need for instant
// messaging and broadcast used by SMSGlobal
type SMSGlobalConfig struct {
Name string `json:"name"`
From string `json:"from"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
Username string `json:"username"`
Password string `json:"password"`
Contacts []SMSContact `json:"contacts"`
}
// SMTPConfig holds all variables to start and run the SMTP package
type SMTPConfig struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
Host string `json:"host"`
Port string `json:"port"`
AccountName string `json:"accountName"`
AccountPassword string `json:"accountPassword"`
From string `json:"from"`
RecipientList string `json:"recipientList"`
}
// TelegramConfig holds all variables to start and run the Telegram package
type TelegramConfig struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
VerificationToken string `json:"verificationToken"`
}
// FeaturesSupportedConfig stores the exchanges supported features
type FeaturesSupportedConfig struct {
REST bool `json:"restAPI"`
RESTCapabilities protocol.Features `json:"restCapabilities,omitempty"`
Websocket bool `json:"websocketAPI"`
WebsocketCapabilities protocol.Features `json:"websocketCapabilities,omitempty"`
}
// FeaturesEnabledConfig stores the exchanges enabled features
type FeaturesEnabledConfig struct {
AutoPairUpdates bool `json:"autoPairUpdates"`
Websocket bool `json:"websocketAPI"`
}
// FeaturesConfig stores the exchanges supported and enabled features
type FeaturesConfig struct {
Supports FeaturesSupportedConfig `json:"supports"`
Enabled FeaturesEnabledConfig `json:"enabled"`
}
// APIEndpointsConfig stores the API endpoint addresses
type APIEndpointsConfig struct {
URL string `json:"url"`
URLSecondary string `json:"urlSecondary"`
WebsocketURL string `json:"websocketURL"`
}
// APICredentialsConfig stores the API credentials
type APICredentialsConfig struct {
Key string `json:"key,omitempty"`
Secret string `json:"secret,omitempty"`
ClientID string `json:"clientID,omitempty"`
PEMKey string `json:"pemKey,omitempty"`
OTPSecret string `json:"otpSecret,omitempty"`
}
// APICredentialsValidatorConfig stores the API credentials validator settings
type APICredentialsValidatorConfig struct {
// For Huobi (optional)
RequiresPEM bool `json:"requiresPEM,omitempty"`
RequiresKey bool `json:"requiresKey,omitempty"`
RequiresSecret bool `json:"requiresSecret,omitempty"`
RequiresClientID bool `json:"requiresClientID,omitempty"`
RequiresBase64DecodeSecret bool `json:"requiresBase64DecodeSecret,omitempty"`
}
// APIConfig stores the exchange API config
type APIConfig struct {
AuthenticatedSupport bool `json:"authenticatedSupport"`
AuthenticatedWebsocketSupport bool `json:"authenticatedWebsocketApiSupport"`
PEMKeySupport bool `json:"pemKeySupport,omitempty"`
Endpoints APIEndpointsConfig `json:"endpoints"`
Credentials APICredentialsConfig `json:"credentials"`
CredentialsValidator *APICredentialsValidatorConfig `json:"credentialsValidator,omitempty"`
}
// HTTPRateConfig stores the exchanges HTTP rate limiter config
type HTTPRateConfig struct {
Duration time.Duration `json:"duration"`
Rate int `json:"rate"`
}
// HTTPRateLimitConfig stores the rate limit config
type HTTPRateLimitConfig struct {
Unauthenticated HTTPRateConfig `json:"unauthenticated"`
Authenticated HTTPRateConfig `json:"authenticated"`
}