engine

package
v0.0.0-...-068a453 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 12, 2024 License: MIT Imports: 115 Imported by: 32

Documentation

Index

Constants

View Source
const (
	WebsocketResponseSuccess = "OK"

	DeprecatedName = "deprecated_rpc"
	WebsocketName  = "websocket_rpc"
)

Const vars for websocket

View Source
const (
	// CurrencyStateManagementName defines the manager name string
	CurrencyStateManagementName = "currency_state_manager"
	// DefaultStateManagerDelay defines the default duration when the manager
	// fetches and updates each exchange for its currency state
	DefaultStateManagerDelay = time.Minute
)
View Source
const (
	// MsgStatusOK message to display when status is "OK"
	MsgStatusOK string = "ok"
	// MsgStatusSuccess message to display when status is successful
	MsgStatusSuccess string = "success"
	// MsgStatusError message to display when failure occurs
	MsgStatusError string = "error"
)
View Source
const (
	ItemPrice     = "PRICE"
	ItemOrderbook = "ORDERBOOK"

	ConditionGreaterThan        = ">"
	ConditionGreaterThanOrEqual = ">="
	ConditionLessThan           = "<"
	ConditionLessThanOrEqual    = "<="
	ConditionIsEqual            = "=="

	ActionSMSNotify    = "SMS"
	ActionConsolePrint = "CONSOLE_PRINT"
	ActionTest         = "ACTION_TEST"
)

Event const vars

View Source
const (
	// MsgSubSystemStarting message to return when subsystem is starting up
	MsgSubSystemStarting = "starting..."
	// MsgSubSystemStarted message to return when subsystem has started
	MsgSubSystemStarted = "started."
	// MsgSubSystemShuttingDown message to return when a subsystem is shutting down
	MsgSubSystemShuttingDown = "shutting down..."
	// MsgSubSystemShutdown message to return when a subsystem has shutdown
	MsgSubSystemShutdown = "shutdown."
)
View Source
const (
	SyncItemTicker syncItemType = iota
	SyncItemOrderbook
	SyncItemTrade
	SyncManagerName = "exchange_syncer"
)

const holds the sync item types

View Source
const CommunicationsManagerName = "communications"

CommunicationsManagerName is an exported subsystem name

View Source
const ConnectionManagerName = "internet_monitor"

ConnectionManagerName is an exported subsystem name

View Source
const DatabaseConnectionManagerName = "database"

DatabaseConnectionManagerName is an exported subsystem name

View Source
const (

	// NTPManagerName is an exported subsystem name
	NTPManagerName = "ntp_timekeeper"
)
View Source
const OrderManagerName = "orders"

OrderManagerName is an exported subsystem name

View Source
const PortfolioManagerName = "portfolio"

PortfolioManagerName is an exported subsystem name

Variables

View Source
var (
	ErrDepositAddressStoreIsNil = errors.New("deposit address store is nil")
	ErrDepositAddressNotFound   = errors.New("deposit address does not exist")
)

vars related to the deposit address helpers

View Source
var (
	ErrNoExchangesLoaded     = errors.New("no exchanges have been loaded")
	ErrExchangeNotFound      = errors.New("exchange not found")
	ErrExchangeAlreadyLoaded = errors.New("exchange already loaded")
	ErrExchangeFailedToLoad  = errors.New("exchange failed to load")
	ErrExchangeNameIsEmpty   = errors.New("exchange name is empty")
)

vars related to exchange functions

View Source
var (
	// ErrOrdersAlreadyExists occurs when the order already exists in the manager
	ErrOrdersAlreadyExists = errors.New("order already exists")
	// ErrOrderIDCannotBeEmpty occurs when an order does not have an ID
	ErrOrderIDCannotBeEmpty = errors.New("orderID cannot be empty")
	// ErrOrderNotFound occurs when an order is not found in the orderstore
	ErrOrderNotFound = errors.New("order does not exist")
)

vars for the fund manager package

View Source
var (
	// ErrSubSystemAlreadyStarted message to return when a subsystem is already started
	ErrSubSystemAlreadyStarted = errors.New("subsystem already started")
	// ErrSubSystemNotStarted message to return when subsystem not started
	ErrSubSystemNotStarted = errors.New("subsystem not started")
	// ErrNilSubsystem is returned when a subsystem hasn't had its Setup() func run
	ErrNilSubsystem = errors.New("subsystem not setup")
)
View Source
var (

	// ErrWebsocketServiceNotRunning occurs when a message is sent to be broadcast via websocket
	// and its not running
	ErrWebsocketServiceNotRunning = errors.New("websocket service not started")
)
View Source
var (
	// ErrWithdrawRequestNotFound message to display when no record is found
	ErrWithdrawRequestNotFound = errors.New("request not found")
)
View Source
var (
	EventSleepDelay = defaultSleepDelay
)

vars related to events package

View Source
var (
	// PortfolioSleepDelay defines the default sleep time between portfolio manager runs
	PortfolioSleepDelay = time.Minute
)

Functions

func BroadcastWebsocketMessage

func BroadcastWebsocketMessage(evt WebsocketEvent) error

BroadcastWebsocketMessage meow

func CheckCerts

func CheckCerts(certDir string) error

CheckCerts checks and verifies RPC server certificates

func GetCollatedExchangeAccountInfoByCoin

func GetCollatedExchangeAccountInfoByCoin(accounts []account.Holdings) map[currency.Code]account.Balance

GetCollatedExchangeAccountInfoByCoin collates individual exchange account information and turns it into a map string of exchange.AccountCurrencyInfo

func GetExchangeHighestPriceByCurrencyPair

func GetExchangeHighestPriceByCurrencyPair(p currency.Pair, a asset.Item) (string, error)

GetExchangeHighestPriceByCurrencyPair returns the exchange with the highest price for a given currency pair and asset type

func GetExchangeLowestPriceByCurrencyPair

func GetExchangeLowestPriceByCurrencyPair(p currency.Pair, assetType asset.Item) (string, error)

GetExchangeLowestPriceByCurrencyPair returns the exchange with the lowest price for a given currency pair and asset type

func GetRelatableCryptocurrencies

func GetRelatableCryptocurrencies(p currency.Pair) currency.Pairs

GetRelatableCryptocurrencies returns a list of currency pairs if it can find any relatable currencies (e.g ETHBTC -> ETHLTC -> ETHUSDT -> ETHREP)

func GetRelatableCurrencies

func GetRelatableCurrencies(p currency.Pair, incOrig, incUSDT bool) currency.Pairs

GetRelatableCurrencies returns a list of currency pairs if it can find any relatable currencies (e.g BTCUSD -> BTC USDT -> XBT USDT -> XBT USD) incOrig includes the supplied pair if desired

func GetRelatableFiatCurrencies

func GetRelatableFiatCurrencies(p currency.Pair) currency.Pairs

GetRelatableFiatCurrencies returns a list of currency pairs if it can find any relatable currencies (e.g ETHUSD -> ETHAUD -> ETHGBP -> ETHJPY)

func IsRelatablePairs

func IsRelatablePairs(p1, p2 currency.Pair, includeUSDT bool) bool

IsRelatablePairs checks to see if the two pairs are relatable

func NewExchangeByNameWithDefaults

func NewExchangeByNameWithDefaults(ctx context.Context, name string) (exchange.IBotExchange, error)

NewExchangeByNameWithDefaults returns a defaulted exchange by its name if it exists. This will allocate a new exchange and setup the default config for it. This will automatically fetch available pairs.

func NewSupportedExchangeByName

func NewSupportedExchangeByName(name string) (exchange.IBotExchange, error)

NewSupportedExchangeByName helps create a new exchange to be loaded that is supported by GCT. This function will return an error if the exchange is not supported.

func StartRPCServer

func StartRPCServer(engine *Engine)

StartRPCServer starts a gRPC server with TLS auth

func StartWebsocketHandler

func StartWebsocketHandler()

StartWebsocketHandler starts the websocket hub and routine which handles clients

Types

type AllEnabledExchangeAccounts

type AllEnabledExchangeAccounts struct {
	Data []account.Holdings `json:"data"`
}

AllEnabledExchangeAccounts holds all enabled accounts info

type AllEnabledExchangeCurrencies

type AllEnabledExchangeCurrencies struct {
	Data []EnabledExchangeCurrencies `json:"data"`
}

AllEnabledExchangeCurrencies holds the enabled exchange currencies

type AllEnabledExchangeOrderbooks

type AllEnabledExchangeOrderbooks struct {
	Data []EnabledExchangeOrderbooks `json:"data"`
}

AllEnabledExchangeOrderbooks holds the enabled exchange orderbooks

type CommunicationManager

type CommunicationManager struct {
	// contains filtered or unexported fields
}

CommunicationManager ensures operations of communications

func SetupCommunicationManager

func SetupCommunicationManager(cfg *base.CommunicationsConfig) (*CommunicationManager, error)

SetupCommunicationManager creates a communications manager

func (*CommunicationManager) GetStatus

func (m *CommunicationManager) GetStatus() (map[string]base.CommsStatus, error)

GetStatus returns the status of communications

func (*CommunicationManager) IsRunning

func (m *CommunicationManager) IsRunning() bool

IsRunning safely checks whether the subsystem is running

func (*CommunicationManager) PushEvent

func (m *CommunicationManager) PushEvent(evt base.Event)

PushEvent pushes an event to the communications relay

func (*CommunicationManager) Start

func (m *CommunicationManager) Start() error

Start runs the subsystem

func (*CommunicationManager) Stop

func (m *CommunicationManager) Stop() error

Stop attempts to shutdown the subsystem

type CoreSettings

type CoreSettings struct {
	EnableDryRun                bool
	EnableAllExchanges          bool
	EnableAllPairs              bool
	EnableCoinmarketcapAnalysis bool
	EnablePortfolioManager      bool
	EnableDataHistoryManager    bool
	PortfolioManagerDelay       time.Duration
	EnableGRPC                  bool
	EnableGRPCProxy             bool
	EnableGRPCShutdown          bool
	EnableWebsocketRPC          bool
	EnableDeprecatedRPC         bool
	EnableCommsRelayer          bool
	EnableExchangeSyncManager   bool
	EnableDepositAddressManager bool
	EnableEventManager          bool
	EnableOrderManager          bool
	EnableConnectivityMonitor   bool
	EnableDatabaseManager       bool
	EnableGCTScriptManager      bool
	EnableNTPClient             bool
	EnableWebsocketRoutine      bool
	EnableCurrencyStateManager  bool
	EventManagerDelay           time.Duration
	EnableFuturesTracking       bool
	Verbose                     bool
	EnableDispatcher            bool
	DispatchMaxWorkerAmount     int
	DispatchJobsLimit           int
	Exchanges                   string
}

CoreSettings defines settings related to core engine operations

type CurrencyStateManager

type CurrencyStateManager struct {
	// contains filtered or unexported fields
}

CurrencyStateManager manages currency states

func SetupCurrencyStateManager

func SetupCurrencyStateManager(interval time.Duration, em iExchangeManager) (*CurrencyStateManager, error)

SetupCurrencyStateManager applies configuration parameters before running

func (*CurrencyStateManager) CanDepositRPC

func (c *CurrencyStateManager) CanDepositRPC(exchName string, cc currency.Code, a asset.Item) (*gctrpc.GenericResponse, error)

CanDepositRPC determines if the currency code is operational for depositing to an exchange for RPC

func (*CurrencyStateManager) CanTradePairRPC

func (c *CurrencyStateManager) CanTradePairRPC(exchName string, pair currency.Pair, a asset.Item) (*gctrpc.GenericResponse, error)

CanTradePairRPC determines if the pair is operational for trading for RPC

func (*CurrencyStateManager) CanTradeRPC

func (c *CurrencyStateManager) CanTradeRPC(exchName string, cc currency.Code, a asset.Item) (*gctrpc.GenericResponse, error)

CanTradeRPC determines if the currency code is operational for trading for RPC

func (*CurrencyStateManager) CanWithdrawRPC

func (c *CurrencyStateManager) CanWithdrawRPC(exchName string, cc currency.Code, a asset.Item) (*gctrpc.GenericResponse, error)

CanWithdrawRPC determines if the currency code is operational for withdrawal from an exchange for RPC

func (*CurrencyStateManager) GetAllRPC

func (c *CurrencyStateManager) GetAllRPC(exchName string) (*gctrpc.CurrencyStateResponse, error)

GetAllRPC returns a full snapshot of currency states, whether they are able to be withdrawn, deposited or traded on an exchange for RPC.

func (*CurrencyStateManager) IsRunning

func (c *CurrencyStateManager) IsRunning() bool

IsRunning safely checks whether the subsystem is running

func (*CurrencyStateManager) Start

func (c *CurrencyStateManager) Start() error

Start runs the subsystem

func (*CurrencyStateManager) Stop

func (c *CurrencyStateManager) Stop() error

Stop stops the subsystem

type CustomExchangeBuilder

type CustomExchangeBuilder interface {
	NewExchangeByName(name string) (exchange.IBotExchange, error)
}

CustomExchangeBuilder interface allows external applications to create custom/unsupported exchanges that satisfy the IBotExchange interface.

type DataHistoryJob

type DataHistoryJob struct {
	ID               uuid.UUID
	Nickname         string
	Exchange         string
	Asset            asset.Item
	Pair             currency.Pair
	StartDate        time.Time
	EndDate          time.Time
	Interval         kline.Interval
	RunBatchLimit    int64
	RequestSizeLimit int64
	DataType         dataHistoryDataType
	MaxRetryAttempts int64
	Status           dataHistoryStatus
	CreatedDate      time.Time
	Results          map[int64][]DataHistoryJobResult

	OverwriteExistingData    bool
	ConversionInterval       kline.Interval
	DecimalPlaceComparison   int64
	SecondaryExchangeSource  string
	IssueTolerancePercentage float64
	ReplaceOnIssue           bool
	// Prerequisites mean this job is paused until the prerequisite job is completed
	PrerequisiteJobID       uuid.UUID
	PrerequisiteJobNickname string
	// contains filtered or unexported fields
}

DataHistoryJob used to gather candle/trade history and save to the database

type DataHistoryJobResult

type DataHistoryJobResult struct {
	ID                uuid.UUID
	JobID             uuid.UUID
	IntervalStartDate time.Time
	IntervalEndDate   time.Time
	Status            dataHistoryStatus
	Result            string
	Date              time.Time
}

DataHistoryJobResult contains details on the result of a history request

type DataHistoryJobSummary

type DataHistoryJobSummary struct {
	Nickname                string
	Exchange                string
	Asset                   asset.Item
	Pair                    currency.Pair
	StartDate               time.Time
	EndDate                 time.Time
	Interval                kline.Interval
	Status                  dataHistoryStatus
	DataType                dataHistoryDataType
	ResultRanges            []string
	OverwriteExistingData   bool
	ConversionInterval      kline.Interval
	PrerequisiteJobNickname string
}

DataHistoryJobSummary is a human readable summary of the job for quickly understanding the status of a given job

type DataHistoryManager

type DataHistoryManager struct {
	// contains filtered or unexported fields
}

DataHistoryManager is responsible for synchronising, retrieving and saving candle and trade data from loaded jobs

func SetupDataHistoryManager

func SetupDataHistoryManager(em iExchangeManager, dcm iDatabaseConnectionManager, cfg *config.DataHistoryManager) (*DataHistoryManager, error)

SetupDataHistoryManager creates a data history manager subsystem

func (*DataHistoryManager) CheckCandleIssue

func (m *DataHistoryManager) CheckCandleIssue(job *DataHistoryJob, multiplier int64, apiData, dbData float64, candleField string) (issue string, replace bool)

CheckCandleIssue verifies that stored data matches API data a job can specify a level of rounding along with a tolerance percentage a job can also replace data with API data if the database data exceeds the tolerance

func (*DataHistoryManager) GenerateJobSummary

func (m *DataHistoryManager) GenerateJobSummary(nickname string) (*DataHistoryJobSummary, error)

GenerateJobSummary returns a human readable summary of a job's status

func (*DataHistoryManager) GetActiveJobs

func (m *DataHistoryManager) GetActiveJobs() ([]DataHistoryJob, error)

GetActiveJobs returns all jobs with the status `dataHistoryStatusActive`

func (*DataHistoryManager) GetAllJobStatusBetween

func (m *DataHistoryManager) GetAllJobStatusBetween(start, end time.Time) ([]*DataHistoryJob, error)

GetAllJobStatusBetween will return all jobs between two ferns

func (*DataHistoryManager) GetByID

func (m *DataHistoryManager) GetByID(id uuid.UUID) (*DataHistoryJob, error)

GetByID returns a job's details from its ID

func (*DataHistoryManager) GetByNickname

func (m *DataHistoryManager) GetByNickname(nickname string, fullDetails bool) (*DataHistoryJob, error)

GetByNickname searches for jobs by name and returns it if found returns nil if not if fullDetails is enabled, it will retrieve all job history results from the database

func (*DataHistoryManager) IsRunning

func (m *DataHistoryManager) IsRunning() bool

IsRunning checks whether the subsystem is running

func (*DataHistoryManager) PrepareJobs

func (m *DataHistoryManager) PrepareJobs() ([]*DataHistoryJob, error)

PrepareJobs will validate the config jobs, verify their status with the database and return all valid jobs to be processed m.jobs will be overridden by this function

func (*DataHistoryManager) SetJobRelationship

func (m *DataHistoryManager) SetJobRelationship(prerequisiteJobNickname, jobNickname string) error

SetJobRelationship will add/modify/delete a relationship with an existing job it will add the relationship and set the jobNickname job to paused if deleting, it will remove the relationship from the database and set the job to active

func (*DataHistoryManager) SetJobStatus

func (m *DataHistoryManager) SetJobStatus(nickname, id string, status dataHistoryStatus) error

SetJobStatus helper function to assist in setting a job to deleted

func (*DataHistoryManager) Start

func (m *DataHistoryManager) Start() error

Start runs the subsystem

func (*DataHistoryManager) Stop

func (m *DataHistoryManager) Stop() error

Stop stops the subsystem

func (*DataHistoryManager) UpsertJob

func (m *DataHistoryManager) UpsertJob(job *DataHistoryJob, insertOnly bool) error

UpsertJob allows for GRPC interaction to upsert a job to be processed

type DatabaseConnectionManager

type DatabaseConnectionManager struct {
	// contains filtered or unexported fields
}

DatabaseConnectionManager holds the database connection and its status

func SetupDatabaseConnectionManager

func SetupDatabaseConnectionManager(cfg *database.Config) (*DatabaseConnectionManager, error)

SetupDatabaseConnectionManager creates a new database manager

func (*DatabaseConnectionManager) GetInstance

func (m *DatabaseConnectionManager) GetInstance() database.IDatabase

GetInstance returns a limited scoped database instance

func (*DatabaseConnectionManager) IsConnected

func (m *DatabaseConnectionManager) IsConnected() bool

IsConnected is an exported check to verify if the database is connected

func (*DatabaseConnectionManager) IsRunning

func (m *DatabaseConnectionManager) IsRunning() bool

IsRunning safely checks whether the subsystem is running

func (*DatabaseConnectionManager) Start

func (m *DatabaseConnectionManager) Start(wg *sync.WaitGroup) (err error)

Start sets up the database connection manager to maintain a SQL connection

func (*DatabaseConnectionManager) Stop

func (m *DatabaseConnectionManager) Stop() error

Stop stops the database manager and closes the connection Stop attempts to shutdown the subsystem

type DepositAddressManager

type DepositAddressManager struct {
	// contains filtered or unexported fields
}

DepositAddressManager manages the exchange deposit address store

func SetupDepositAddressManager

func SetupDepositAddressManager() *DepositAddressManager

SetupDepositAddressManager returns a DepositAddressManager

func (*DepositAddressManager) GetDepositAddressByExchangeAndCurrency

func (m *DepositAddressManager) GetDepositAddressByExchangeAndCurrency(exchName, chain string, currencyItem currency.Code) (deposit.Address, error)

GetDepositAddressByExchangeAndCurrency returns a deposit address for the specified exchange and cryptocurrency if it exists

func (*DepositAddressManager) GetDepositAddressesByExchange

func (m *DepositAddressManager) GetDepositAddressesByExchange(exchName string) (map[string][]deposit.Address, error)

GetDepositAddressesByExchange returns a list of cryptocurrency addresses for the specified exchange if they exist

func (*DepositAddressManager) IsSynced

func (m *DepositAddressManager) IsSynced() bool

IsSynced returns whether or not the deposit address store has synced its data

func (*DepositAddressManager) Sync

func (m *DepositAddressManager) Sync(addresses map[string]map[string][]deposit.Address) error

Sync synchronises all deposit addresses

type EnabledExchangeCurrencies

type EnabledExchangeCurrencies struct {
	ExchangeName   string         `json:"exchangeName"`
	ExchangeValues []ticker.Price `json:"exchangeValues"`
}

EnabledExchangeCurrencies is a sub type for singular exchanges and respective currencies

type EnabledExchangeOrderbooks

type EnabledExchangeOrderbooks struct {
	ExchangeName   string           `json:"exchangeName"`
	ExchangeValues []orderbook.Base `json:"exchangeValues"`
}

EnabledExchangeOrderbooks is a sub type for singular exchanges and respective orderbooks

type Engine

type Engine struct {
	Config *config.Config

	CommunicationsManager *CommunicationManager

	DatabaseManager       *DatabaseConnectionManager
	DepositAddressManager *DepositAddressManager

	ExchangeManager *ExchangeManager

	OrderManager *OrderManager

	WebsocketRoutineManager *WebsocketRoutineManager
	WithdrawManager         *WithdrawManager

	Settings Settings

	GRPCShutdownSignal chan struct{}
	ServicesWG         sync.WaitGroup
	// contains filtered or unexported fields
}

Engine contains configuration, portfolio manager, exchange & ticker data and is the overarching type across this code base.

var Bot *Engine

Bot is a happy global engine to allow various areas of the application to access its setup services and functions

func New

func New() (*Engine, error)

New starts a new engine

func NewFromSettings

func NewFromSettings(settings *Settings, flagSet map[string]bool) (*Engine, error)

NewFromSettings starts a new engine based on supplied settings

func (*Engine) GetAllActiveTickers

func (bot *Engine) GetAllActiveTickers(ctx context.Context) []EnabledExchangeCurrencies

GetAllActiveTickers returns all enabled exchange tickers

func (*Engine) GetAllAvailablePairs

func (bot *Engine) GetAllAvailablePairs(enabledExchangesOnly bool, assetType asset.Item) currency.Pairs

GetAllAvailablePairs returns a list of all available pairs on either enabled or disabled exchanges

func (*Engine) GetAllExchangeCryptocurrencyDepositAddresses

func (bot *Engine) GetAllExchangeCryptocurrencyDepositAddresses() map[string]map[string][]deposit.Address

GetAllExchangeCryptocurrencyDepositAddresses obtains an exchanges deposit cryptocurrency list

func (*Engine) GetAuthAPISupportedExchanges

func (bot *Engine) GetAuthAPISupportedExchanges() []string

GetAuthAPISupportedExchanges returns a list of auth api enabled exchanges

func (*Engine) GetCryptocurrenciesByExchange

func (bot *Engine) GetCryptocurrenciesByExchange(exchangeName string, enabledExchangesOnly, enabledPairs bool, assetType asset.Item) ([]string, error)

GetCryptocurrenciesByExchange returns a list of cryptocurrencies the exchange supports

func (*Engine) GetCryptocurrencyDepositAddressesByExchange

func (bot *Engine) GetCryptocurrencyDepositAddressesByExchange(exchName string) (map[string][]deposit.Address, error)

GetCryptocurrencyDepositAddressesByExchange returns the cryptocurrency deposit addresses for a particular exchange

func (*Engine) GetExchangeByName

func (bot *Engine) GetExchangeByName(exchName string) (exchange.IBotExchange, error)

GetExchangeByName returns an exchange given an exchange name

func (*Engine) GetExchangeCryptocurrencyDepositAddress

func (bot *Engine) GetExchangeCryptocurrencyDepositAddress(ctx context.Context, exchName, accountID, chain string, item currency.Code, bypassCache bool) (*deposit.Address, error)

GetExchangeCryptocurrencyDepositAddress returns the cryptocurrency deposit address for a particular exchange

func (*Engine) GetExchangeNames

func (bot *Engine) GetExchangeNames(enabledOnly bool) []string

GetExchangeNames returns a list of enabled or disabled exchanges

func (*Engine) GetExchangeNamesByCurrency

func (bot *Engine) GetExchangeNamesByCurrency(p currency.Pair, enabled bool, assetType asset.Item) []string

GetExchangeNamesByCurrency returns a list of exchanges supporting a currency pair based on whether the exchange is enabled or not

func (*Engine) GetExchangeOTPByName

func (bot *Engine) GetExchangeOTPByName(exchName string) (string, error)

GetExchangeOTPByName returns a OTP code for the desired exchange if it exists

func (*Engine) GetExchangeOTPs

func (bot *Engine) GetExchangeOTPs() (map[string]string, error)

GetExchangeOTPs returns OTP codes for all exchanges which have a otpsecret stored

func (*Engine) GetExchanges

func (bot *Engine) GetExchanges() []exchange.IBotExchange

GetExchanges retrieves the loaded exchanges

func (*Engine) GetRPCEndpoints

func (bot *Engine) GetRPCEndpoints() (map[string]RPCEndpoint, error)

GetRPCEndpoints returns a list of RPC endpoints and their listen addrs

func (*Engine) GetSpecificAvailablePairs

func (bot *Engine) GetSpecificAvailablePairs(enabledExchangesOnly, fiatPairs, includeUSDT, cryptoPairs bool, assetType asset.Item) currency.Pairs

GetSpecificAvailablePairs returns a list of supported pairs based on specific parameters

func (*Engine) GetSpecificOrderbook

func (bot *Engine) GetSpecificOrderbook(ctx context.Context, p currency.Pair, exchangeName string, assetType asset.Item) (*orderbook.Base, error)

GetSpecificOrderbook returns a specific orderbook given the currency, exchangeName and assetType

func (*Engine) GetSpecificTicker

func (bot *Engine) GetSpecificTicker(ctx context.Context, p currency.Pair, exchangeName string, assetType asset.Item) (*ticker.Price, error)

GetSpecificTicker returns a specific ticker given the currency, exchangeName and assetType

func (*Engine) GetSubsystemsStatus

func (bot *Engine) GetSubsystemsStatus() map[string]bool

GetSubsystemsStatus returns the status of various subsystems

func (*Engine) IsOnline

func (bot *Engine) IsOnline() bool

IsOnline returns whether or not the engine has Internet connectivity

func (*Engine) LoadExchange

func (bot *Engine) LoadExchange(name string) error

LoadExchange loads an exchange by name. Optional wait group can be added for external synchronization.

func (*Engine) MapCurrenciesByExchange

func (bot *Engine) MapCurrenciesByExchange(p currency.Pairs, enabledExchangesOnly bool, assetType asset.Item) map[string]currency.Pairs

MapCurrenciesByExchange returns a list of currency pairs mapped to an exchange

func (*Engine) RegisterWebsocketDataHandler

func (bot *Engine) RegisterWebsocketDataHandler(fn WebsocketDataHandler, interceptorOnly bool) error

RegisterWebsocketDataHandler registers an externally defined data handler for diverting and handling websocket notifications across all enabled exchanges. InterceptorOnly as true will purge all other registered handlers (including default) bypassing all other handling.

func (*Engine) SetDefaultWebsocketDataHandler

func (bot *Engine) SetDefaultWebsocketDataHandler() error

SetDefaultWebsocketDataHandler sets the default websocket handler and removing all pre-existing handlers

func (*Engine) SetSubsystem

func (bot *Engine) SetSubsystem(subSystemName string, enable bool) error

SetSubsystem enables or disables an engine subsystem

func (*Engine) SetupExchanges

func (bot *Engine) SetupExchanges() error

SetupExchanges sets up the exchanges used by the Bot

func (*Engine) Start

func (bot *Engine) Start() error

Start starts the engine

func (*Engine) Stop

func (bot *Engine) Stop()

Stop correctly shuts down engine saving configuration files

func (*Engine) UnloadExchange

func (bot *Engine) UnloadExchange(exchName string) error

UnloadExchange unloads an exchange by name

func (*Engine) WaitForInitialCurrencySync

func (bot *Engine) WaitForInitialCurrencySync() error

WaitForInitialCurrencySync allows for a routine to wait for the initial sync of the currency pair syncer management system.

type Event

type Event struct {
	ID        int64
	Exchange  string
	Item      string
	Condition EventConditionParams
	Pair      currency.Pair
	Asset     asset.Item
	Action    string
	Executed  bool
}

Event struct holds the event variables

func (*Event) String

func (e *Event) String() string

String turns the structure event into a string

type EventConditionParams

type EventConditionParams struct {
	Condition string
	Price     float64

	CheckBids       bool
	CheckAsks       bool
	OrderbookAmount float64
}

EventConditionParams holds the event condition variables

type ExchangeManager

type ExchangeManager struct {
	Builder CustomExchangeBuilder
	// contains filtered or unexported fields
}

ExchangeManager manages what exchanges are loaded

func NewExchangeManager

func NewExchangeManager() *ExchangeManager

NewExchangeManager creates a new exchange manager

func (*ExchangeManager) Add

Add adds an exchange

func (*ExchangeManager) GetExchangeByName

func (m *ExchangeManager) GetExchangeByName(exchangeName string) (exchange.IBotExchange, error)

GetExchangeByName returns an exchange by its name if it exists

func (*ExchangeManager) GetExchanges

func (m *ExchangeManager) GetExchanges() ([]exchange.IBotExchange, error)

GetExchanges returns all stored exchanges

func (*ExchangeManager) NewExchangeByName

func (m *ExchangeManager) NewExchangeByName(name string) (exchange.IBotExchange, error)

NewExchangeByName helps create a new exchange to be loaded

func (*ExchangeManager) RemoveExchange

func (m *ExchangeManager) RemoveExchange(exchangeName string) error

RemoveExchange removes an exchange from the manager

func (*ExchangeManager) Shutdown

func (m *ExchangeManager) Shutdown(shutdownTimeout time.Duration) error

Shutdown shuts down all exchanges and unloads them

type ExchangeSyncerSettings

type ExchangeSyncerSettings struct {
	EnableTickerSyncing    bool
	EnableOrderbookSyncing bool
	EnableTradeSyncing     bool
	SyncWorkersCount       int
	SyncContinuously       bool
	SyncTimeoutREST        time.Duration
	SyncTimeoutWebsocket   time.Duration
}

ExchangeSyncerSettings defines settings for the exchange pair synchronisation

type ExchangeTuningSettings

type ExchangeTuningSettings struct {
	EnableExchangeHTTPRateLimiter       bool
	EnableExchangeHTTPDebugging         bool
	EnableExchangeVerbose               bool
	ExchangePurgeCredentials            bool
	EnableExchangeAutoPairUpdates       bool
	DisableExchangeAutoPairUpdates      bool
	EnableExchangeRESTSupport           bool
	EnableExchangeWebsocketSupport      bool
	TradeBufferProcessingInterval       time.Duration
	RequestMaxRetryAttempts             int
	AlertSystemPreAllocationCommsBuffer int // See exchanges/alert.go
	ExchangeShutdownTimeout             time.Duration
	HTTPTimeout                         time.Duration
	HTTPUserAgent                       string
	HTTPProxy                           string
	GlobalHTTPTimeout                   time.Duration
	GlobalHTTPUserAgent                 string
	GlobalHTTPProxy                     string
}

ExchangeTuningSettings defines settings related to an exchange

type FlagSet

type FlagSet map[string]bool

FlagSet defines set flags from command line args for comparison methods

func (FlagSet) WithBool

func (f FlagSet) WithBool(key string, flagValue *bool, configValue bool)

WithBool checks the supplied flag. If set it will override the config boolean value as a command line takes precedence. If not set will fall back to config options.

type ForexSettings

type ForexSettings struct {
	EnableCurrencyConverter bool
	EnableCurrencyLayer     bool
	EnableExchangeRates     bool
	EnableFixer             bool
	EnableOpenExchangeRates bool
}

ForexSettings defines settings related to the foreign exchange services

type GCTScriptSettings

type GCTScriptSettings struct {
	MaxVirtualMachines uint
}

GCTScriptSettings defines settings related to the GCTScript virtual machine

type OrderManager

type OrderManager struct {
	// contains filtered or unexported fields
}

OrderManager processes and stores orders across enabled exchanges

func SetupOrderManager

func SetupOrderManager(exchangeManager iExchangeManager, communicationsManager iCommsManager, wg *sync.WaitGroup, cfg *config.OrderManager) (*OrderManager, error)

SetupOrderManager will boot up the OrderManager

func (*OrderManager) Add

func (m *OrderManager) Add(o *order.Detail) error

Add adds an order to the orderstore

func (*OrderManager) Cancel

func (m *OrderManager) Cancel(ctx context.Context, cancel *order.Cancel) error

Cancel will find the order in the OrderManager, send a cancel request to the exchange and if successful, update the status of the order

func (*OrderManager) CancelAllOrders

func (m *OrderManager) CancelAllOrders(ctx context.Context, exchanges []exchange.IBotExchange)

CancelAllOrders iterates and cancels all orders for each exchange provided

func (*OrderManager) ClearFuturesTracking

func (m *OrderManager) ClearFuturesTracking(exch string, item asset.Item, pair currency.Pair) error

ClearFuturesTracking will clear existing futures positions for a given exchange, asset, pair for the event that positions have not been tracked accurately

func (*OrderManager) Exists

func (m *OrderManager) Exists(o *order.Detail) bool

Exists checks whether an order exists in the order store

func (*OrderManager) FetchAndUpdateExchangeOrder

func (m *OrderManager) FetchAndUpdateExchangeOrder(exch exchange.IBotExchange, ord *order.Detail, assetType asset.Item) error

FetchAndUpdateExchangeOrder calls the exchange to upsert an order to the order store

func (*OrderManager) GetAllOpenFuturesPositions

func (m *OrderManager) GetAllOpenFuturesPositions() ([]futures.Position, error)

GetAllOpenFuturesPositions returns all open futures positions stored within the order manager's futures position tracker that match the provided params

func (*OrderManager) GetByExchangeAndID

func (m *OrderManager) GetByExchangeAndID(exchangeName, id string) (*order.Detail, error)

GetByExchangeAndID returns a copy of an order from an exchange if it matches the ID

func (*OrderManager) GetFuturesPositionsForExchange

func (m *OrderManager) GetFuturesPositionsForExchange(exch string, item asset.Item, pair currency.Pair) ([]futures.Position, error)

GetFuturesPositionsForExchange returns futures positions stored within the order manager's futures position tracker that match the provided params

func (*OrderManager) GetOpenFuturesPosition

func (m *OrderManager) GetOpenFuturesPosition(exch string, item asset.Item, pair currency.Pair) (*futures.Position, error)

GetOpenFuturesPosition returns an open futures position stored within the order manager's futures position tracker that match the provided params

func (*OrderManager) GetOrderInfo

func (m *OrderManager) GetOrderInfo(ctx context.Context, exchangeName, orderID string, cp currency.Pair, a asset.Item) (order.Detail, error)

GetOrderInfo calls the exchange's wrapper GetOrderInfo function and stores the result in the order manager

func (*OrderManager) GetOrdersActive

func (m *OrderManager) GetOrdersActive(f *order.Filter) ([]order.Detail, error)

GetOrdersActive returns a snapshot of all orders in the order store that have a status that indicates it's currently tradable

func (*OrderManager) GetOrdersFiltered

func (m *OrderManager) GetOrdersFiltered(f *order.Filter) ([]order.Detail, error)

GetOrdersFiltered returns a snapshot of all orders in the order store. Filtering is applied based on the order.Filter unless entries are empty

func (*OrderManager) GetOrdersSnapshot

func (m *OrderManager) GetOrdersSnapshot(s order.Status) []order.Detail

GetOrdersSnapshot returns a snapshot of all orders in the orderstore. It optionally filters any orders that do not match the status but a status of "" or ANY will include all the time adds contexts for when the snapshot is relevant for

func (*OrderManager) IsRunning

func (m *OrderManager) IsRunning() bool

IsRunning safely checks whether the subsystem is running

func (*OrderManager) Modify

func (m *OrderManager) Modify(ctx context.Context, mod *order.Modify) (*order.ModifyResponse, error)

Modify depends on the order.Modify.ID and order.Modify.Exchange fields to uniquely identify an order to modify.

func (*OrderManager) Start

func (m *OrderManager) Start() error

Start runs the subsystem

func (*OrderManager) Stop

func (m *OrderManager) Stop() error

Stop attempts to shutdown the subsystem

func (*OrderManager) Submit

func (m *OrderManager) Submit(ctx context.Context, newOrder *order.Submit) (*OrderSubmitResponse, error)

Submit will take in an order struct, send it to the exchange and populate it in the OrderManager if successful

func (*OrderManager) SubmitFakeOrder

func (m *OrderManager) SubmitFakeOrder(newOrder *order.Submit, resultingOrder *order.SubmitResponse, checkExchangeLimits bool) (*OrderSubmitResponse, error)

SubmitFakeOrder runs through the same process as order submission but does not touch live endpoints

func (*OrderManager) UpdateExistingOrder

func (m *OrderManager) UpdateExistingOrder(od *order.Detail) error

UpdateExistingOrder will update an existing order in the orderstore

func (*OrderManager) UpdateOpenPositionUnrealisedPNL

func (m *OrderManager) UpdateOpenPositionUnrealisedPNL(e string, item asset.Item, pair currency.Pair, last float64, updated time.Time) (decimal.Decimal, error)

UpdateOpenPositionUnrealisedPNL finds an open position from an exchange asset pair, then calculates the unrealisedPNL using the latest ticker data

func (*OrderManager) UpsertOrder

func (m *OrderManager) UpsertOrder(od *order.Detail) (resp *OrderUpsertResponse, err error)

UpsertOrder updates an existing order or adds a new one to the orderstore

type OrderSubmitResponse

type OrderSubmitResponse struct {
	*order.Detail
	InternalOrderID string
}

OrderSubmitResponse contains the order response along with an internal order ID

type OrderUpsertResponse

type OrderUpsertResponse struct {
	OrderDetails order.Detail
	IsNewOrder   bool
}

OrderUpsertResponse contains a copy of the resulting order details and a bool indicating if the order details were inserted (true) or updated (false)

type RPCEndpoint

type RPCEndpoint struct {
	Started    bool
	ListenAddr string
}

RPCEndpoint stores an RPC endpoint status and addr

type RPCServer

RPCServer struct

func (*RPCServer) AddEvent

AddEvent adds an event

func (*RPCServer) AddPortfolioAddress

AddPortfolioAddress adds an address to the portfoliomanager manager

func (*RPCServer) CancelAllOrders

CancelAllOrders cancels all orders, filterable by exchange

func (*RPCServer) CancelBatchOrders

CancelBatchOrders cancels an orders specified by exchange, currency pair and asset type

func (*RPCServer) CancelOrder

CancelOrder cancels an order specified by exchange, currency pair and asset type

func (*RPCServer) ChangePositionMargin

ChangePositionMargin sets a position's margin

func (*RPCServer) ConvertTradesToCandles

ConvertTradesToCandles converts trades to candles using the interval requested returns the data too for extra fun scrutiny

func (*RPCServer) CurrencyStateDeposit

CurrencyStateDeposit determines via RPC if the currency code is operational for depositing to an exchange

func (*RPCServer) CurrencyStateGetAll

CurrencyStateGetAll returns a full snapshot of currency states, whether they are able to be withdrawn, deposited or traded on an exchange.

func (*RPCServer) CurrencyStateTrading

CurrencyStateTrading determines via RPC if the currency code is operational for trading

func (*RPCServer) CurrencyStateTradingPair

CurrencyStateTradingPair determines via RPC if the pair is operational for trading

func (*RPCServer) CurrencyStateWithdraw

CurrencyStateWithdraw determines via RPC if the currency code is operational for withdrawal from an exchange

func (*RPCServer) DisableExchange

DisableExchange disables an exchange

func (*RPCServer) DisableSubsystem

DisableSubsystem disables a engine subsystem

func (*RPCServer) EnableExchange

EnableExchange enables an exchange

func (*RPCServer) EnableSubsystem

EnableSubsystem enables a engine subsystem

func (*RPCServer) FindMissingSavedCandleIntervals

FindMissingSavedCandleIntervals is used to help determine what candle data is missing

func (*RPCServer) FindMissingSavedTradeIntervals

FindMissingSavedTradeIntervals is used to help determine what trade data is missing

func (*RPCServer) GCTScriptAutoLoadToggle

func (s *RPCServer) GCTScriptAutoLoadToggle(_ context.Context, r *gctrpc.GCTScriptAutoLoadRequest) (*gctrpc.GenericResponse, error)

GCTScriptAutoLoadToggle adds or removes an entry to the autoload list

func (*RPCServer) GCTScriptExecute

GCTScriptExecute execute a script

func (*RPCServer) GCTScriptListAll

GCTScriptListAll lists all scripts inside the default script path

func (*RPCServer) GCTScriptQuery

GCTScriptQuery queries a running script and returns script running information

func (*RPCServer) GCTScriptReadScript

GCTScriptReadScript read a script and return contents

func (*RPCServer) GCTScriptStatus

GCTScriptStatus returns a slice of current running scripts that includes next run time and uuid

func (*RPCServer) GCTScriptStop

GCTScriptStop terminate a running script

func (*RPCServer) GCTScriptStopAll

GCTScriptStopAll stops all running scripts

func (*RPCServer) GCTScriptUpload

GCTScriptUpload upload a new script to ScriptPath

func (*RPCServer) GetAccountInfo

GetAccountInfo returns an account balance for a specific exchange

func (*RPCServer) GetAccountInfoStream

GetAccountInfoStream streams an account balance for a specific exchange

func (*RPCServer) GetActiveDataHistoryJobs

func (s *RPCServer) GetActiveDataHistoryJobs(_ context.Context, _ *gctrpc.GetInfoRequest) (*gctrpc.DataHistoryJobs, error)

GetActiveDataHistoryJobs returns any active data history job details

func (*RPCServer) GetAllManagedPositions

GetAllManagedPositions returns all open positions from the order manager, no calling any API endpoints to return this information

func (*RPCServer) GetAuditEvent

GetAuditEvent returns matching audit events from database

func (*RPCServer) GetAvailableTransferChains

GetAvailableTransferChains returns the supported transfer chains specified by exchange and cryptocurrency

func (*RPCServer) GetCollateral

GetCollateral returns the total collateral for an exchange's asset as exchanges can scale collateral and represent it in a singular currency, a user can opt to include a breakdown by currency

func (*RPCServer) GetCollateralMode

GetCollateralMode returns the collateral type for the account asset

func (*RPCServer) GetCommunicationRelayers

GetCommunicationRelayers returns the status of the engines communication relayers

func (*RPCServer) GetConfig

GetConfig returns the bots config

func (*RPCServer) GetCryptocurrencyDepositAddress

GetCryptocurrencyDepositAddress returns a cryptocurrency deposit address specified by exchange and cryptocurrency

func (*RPCServer) GetCryptocurrencyDepositAddresses

GetCryptocurrencyDepositAddresses returns a list of cryptocurrency deposit addresses specified by an exchange

func (*RPCServer) GetCurrencyTradeURL

GetCurrencyTradeURL returns the URL for the trading pair

func (*RPCServer) GetDataHistoryJobDetails

GetDataHistoryJobDetails returns a data history job's details can request all data history results with r.FullDetails

func (*RPCServer) GetDataHistoryJobSummary

GetDataHistoryJobSummary provides a general look at how a data history job is going with the "resultSummaries" property

func (*RPCServer) GetDataHistoryJobsBetween

GetDataHistoryJobsBetween returns all jobs created between supplied dates

func (*RPCServer) GetEvents

GetEvents returns the stored events list

func (*RPCServer) GetExchangeAssets

GetExchangeAssets returns the supported asset types

func (*RPCServer) GetExchangeInfo

GetExchangeInfo gets info for a specific exchange

func (*RPCServer) GetExchangeOTPCode

GetExchangeOTPCode retrieves an exchanges OTP code

func (*RPCServer) GetExchangeOTPCodes

GetExchangeOTPCodes retrieves OTP codes for all exchanges which have an OTP secret installed

func (*RPCServer) GetExchangeOrderbookStream

GetExchangeOrderbookStream streams all orderbooks associated with an exchange

func (*RPCServer) GetExchangePairs

GetExchangePairs returns a list of exchange supported assets and related pairs

func (*RPCServer) GetExchangeTickerStream

GetExchangeTickerStream streams all tickers associated with an exchange

func (*RPCServer) GetExchanges

GetExchanges returns a list of exchanges Param is whether or not you wish to list enabled exchanges

func (*RPCServer) GetForexProviders

GetForexProviders returns a list of available forex providers

func (*RPCServer) GetForexRates

GetForexRates returns a list of forex rates

func (*RPCServer) GetFundingRates

GetFundingRates returns the funding rates for an exchange, asset, pair

func (*RPCServer) GetFuturesPositionsOrders

GetFuturesPositionsOrders returns futures position orders from exchange API

func (*RPCServer) GetFuturesPositionsSummary

GetFuturesPositionsSummary returns a summary of futures positions for an exchange asset pair from the API

func (*RPCServer) GetHistoricCandles

GetHistoricCandles returns historical candles for a given exchange

func (*RPCServer) GetHistoricTrades

GetHistoricTrades returns trades between a set of dates

func (*RPCServer) GetInfo

GetInfo returns info about the current GoCryptoTrader session

func (*RPCServer) GetLatestFundingRate

GetLatestFundingRate returns the latest funding rate for an exchange, asset, pair

func (*RPCServer) GetLeverage

GetLeverage returns the leverage for the account asset pair

func (*RPCServer) GetLoggerDetails

GetLoggerDetails returns a loggers details

func (*RPCServer) GetManagedOrders

GetManagedOrders returns all orders from the Order Manager for the provided exchange, asset type and currency pair

func (*RPCServer) GetManagedPosition

GetManagedPosition returns an open positions from the order manager, no calling any API endpoints to return this information

func (*RPCServer) GetMarginRatesHistory

GetMarginRatesHistory returns the margin lending or borrow rates for an exchange, asset, currency along with many customisable options

func (*RPCServer) GetOpenInterest

GetOpenInterest fetches the open interest from the exchange

func (*RPCServer) GetOrder

GetOrder returns order information based on exchange and order ID

func (*RPCServer) GetOrderbook

GetOrderbook returns an orderbook for a specific exchange, currency pair and asset type

func (*RPCServer) GetOrderbookAmountByImpact

GetOrderbookAmountByImpact using the requested impact percentage requirement determines the amount on orderbook that can fit that will slip the orderbook.

func (*RPCServer) GetOrderbookAmountByNominal

GetOrderbookAmountByNominal using the requested nominal percentage requirement returns the amount on orderbook that can fit without exceeding that value.

func (*RPCServer) GetOrderbookMovement

GetOrderbookMovement using the requested amount simulates a buy or sell and returns the nominal/impact percentages and costings.

func (*RPCServer) GetOrderbookStream

GetOrderbookStream streams the requested updated orderbook

func (*RPCServer) GetOrderbooks

GetOrderbooks returns a list of orderbooks for all enabled exchanges and all enabled currency pairs

func (*RPCServer) GetOrders

GetOrders returns all open orders, filtered by exchange, currency pair or asset type between optional dates

func (*RPCServer) GetPortfolio

GetPortfolio returns the portfoliomanager details

func (*RPCServer) GetPortfolioSummary

GetPortfolioSummary returns the portfoliomanager summary

func (*RPCServer) GetRPCEndpoints

GetRPCEndpoints returns a list of API endpoints

func (*RPCServer) GetRecentTrades

GetRecentTrades returns trades

func (*RPCServer) GetSavedTrades

GetSavedTrades returns trades from the database

func (*RPCServer) GetSubsystems

GetSubsystems returns a list of subsystems and their status

func (*RPCServer) GetTechnicalAnalysis

GetTechnicalAnalysis using the requested technical analysis method will return a set(s) of signals for price action analysis.

func (*RPCServer) GetTicker

GetTicker returns the ticker for a specified exchange, currency pair and asset type

func (*RPCServer) GetTickerStream

GetTickerStream streams the requested updated ticker

func (*RPCServer) GetTickers

GetTickers returns a list of tickers for all enabled exchanges and all enabled currency pairs

func (*RPCServer) ModifyOrder

ModifyOrder modifies an existing order if it exists

func (*RPCServer) RemoveEvent

RemoveEvent removes an event, specified by an event ID

func (*RPCServer) RemovePortfolioAddress

RemovePortfolioAddress removes an address from the portfoliomanager manager

func (*RPCServer) SetAllExchangePairs

SetAllExchangePairs enables or disables an exchanges pairs

func (*RPCServer) SetCollateralMode

SetCollateralMode sets the collateral type for the account asset

func (*RPCServer) SetDataHistoryJobStatus

SetDataHistoryJobStatus sets a data history job's status

func (*RPCServer) SetExchangeAsset

SetExchangeAsset enables or disables an exchanges asset type

func (*RPCServer) SetExchangePair

SetExchangePair enables/disabled the specified pair(s) on an exchange

func (*RPCServer) SetExchangeTradeProcessing

SetExchangeTradeProcessing allows the setting of exchange trade processing

func (*RPCServer) SetLeverage

SetLeverage sets the leverage for the account asset pair

func (*RPCServer) SetLoggerDetails

SetLoggerDetails sets a loggers details

func (*RPCServer) SetMarginType

SetMarginType sets the margin type for the account asset pair

func (*RPCServer) Shutdown

Shutdown terminates bot session externally

func (*RPCServer) SimulateOrder

SimulateOrder simulates an order specified by exchange, currency pair and asset type

func (*RPCServer) StartRPCRESTProxy

func (s *RPCServer) StartRPCRESTProxy()

StartRPCRESTProxy starts a gRPC proxy

func (*RPCServer) SubmitOrder

SubmitOrder submits an order specified by exchange, currency pair and asset type

func (*RPCServer) UpdateAccountInfo

UpdateAccountInfo forces an update of the account info

func (*RPCServer) UpdateDataHistoryJobPrerequisite

func (s *RPCServer) UpdateDataHistoryJobPrerequisite(_ context.Context, r *gctrpc.UpdateDataHistoryJobPrerequisiteRequest) (*gctrpc.GenericResponse, error)

UpdateDataHistoryJobPrerequisite sets or removes a prerequisite job for an existing job if the prerequisite job is "", then the relationship is removed

func (*RPCServer) UpdateExchangeSupportedPairs

func (s *RPCServer) UpdateExchangeSupportedPairs(ctx context.Context, r *gctrpc.UpdateExchangeSupportedPairsRequest) (*gctrpc.GenericResponse, error)

UpdateExchangeSupportedPairs forces an update of the supported pairs which will update the available pairs list and remove any assets that are disabled by the exchange

func (*RPCServer) UpsertDataHistoryJob

UpsertDataHistoryJob adds or updates a data history job for the data history manager It will upsert the entry in the database and allow for the processing of the job

func (*RPCServer) WebsocketGetInfo

WebsocketGetInfo returns websocket connection information

func (*RPCServer) WebsocketGetSubscriptions

WebsocketGetSubscriptions returns websocket subscription analysis

func (*RPCServer) WebsocketSetEnabled

WebsocketSetEnabled enables or disables the websocket client

func (*RPCServer) WebsocketSetProxy

WebsocketSetProxy sets client websocket connection proxy

func (*RPCServer) WebsocketSetURL

WebsocketSetURL sets exchange websocket client connection URL

func (*RPCServer) WhaleBomb

WhaleBomb finds the amount required to reach a specific price target for a given exchange, pair and asset type

func (*RPCServer) WithdrawCryptocurrencyFunds

func (s *RPCServer) WithdrawCryptocurrencyFunds(ctx context.Context, r *gctrpc.WithdrawCryptoRequest) (*gctrpc.WithdrawResponse, error)

WithdrawCryptocurrencyFunds withdraws cryptocurrency funds specified by exchange

func (*RPCServer) WithdrawFiatFunds

func (s *RPCServer) WithdrawFiatFunds(ctx context.Context, r *gctrpc.WithdrawFiatRequest) (*gctrpc.WithdrawResponse, error)

WithdrawFiatFunds withdraws fiat funds specified by exchange

func (*RPCServer) WithdrawalEventByID

WithdrawalEventByID returns previous withdrawal request details

func (*RPCServer) WithdrawalEventsByDate

WithdrawalEventsByDate returns previous withdrawal request details by exchange

func (*RPCServer) WithdrawalEventsByExchange

WithdrawalEventsByExchange returns previous withdrawal request details by exchange

type Route

type Route struct {
	Name        string
	Method      string
	Pattern     string
	HandlerFunc http.HandlerFunc
}

Route is a sub type that holds the request routes

type Settings

type Settings struct {
	ConfigFile            string
	DataDir               string
	MigrationDir          string
	LogFile               string
	GoMaxProcs            int
	CheckParamInteraction bool

	CoreSettings
	ExchangeSyncerSettings
	ForexSettings
	ExchangeTuningSettings
	GCTScriptSettings
	WithdrawSettings

	// Main shutdown channel
	Shutdown chan struct{}
}

Settings stores engine params. Please define a settings struct for automatic display of instance settings. For example, if you define a struct named ManagerSettings, it will be displayed as a subheading "Manager Settings" and individual field names such as 'EnableManager' will be displayed as "Enable Manager: true/false".

func (*Settings) PrintLoadedSettings

func (s *Settings) PrintLoadedSettings()

PrintLoadedSettings logs loaded settings.

type SyncManager

type SyncManager struct {
	// contains filtered or unexported fields
}

SyncManager stores the exchange currency pair syncer object

func SetupSyncManager

func SetupSyncManager(c *config.SyncManagerConfig, exchangeManager iExchangeManager, remoteConfig *config.RemoteControlConfig, websocketRoutineManagerEnabled bool) (*SyncManager, error)

SetupSyncManager creates a new CurrencyPairSyncer

func (*SyncManager) FormatCurrency

func (m *SyncManager) FormatCurrency(cp currency.Pair) string

FormatCurrency is a method that formats and returns a currency pair based on the user currency display preferences

func (*SyncManager) IsRunning

func (m *SyncManager) IsRunning() bool

IsRunning safely checks whether the subsystem is running

func (*SyncManager) PrintOrderbookSummary

func (m *SyncManager) PrintOrderbookSummary(result *orderbook.Base, protocol string, err error)

PrintOrderbookSummary outputs orderbook results

func (*SyncManager) PrintTickerSummary

func (m *SyncManager) PrintTickerSummary(result *ticker.Price, protocol string, err error)

PrintTickerSummary outputs the ticker results

func (*SyncManager) Start

func (m *SyncManager) Start() error

Start runs the subsystem

func (*SyncManager) Stop

func (m *SyncManager) Stop() error

Stop shuts down the exchange currency pair syncer

func (*SyncManager) WaitForInitialSync

func (m *SyncManager) WaitForInitialSync() error

WaitForInitialSync allows for a routine to wait for an initial sync to be completed without exposing the underlying type. This needs to be called in a separate routine.

func (*SyncManager) WebsocketUpdate

func (m *SyncManager) WebsocketUpdate(exchangeName string, p currency.Pair, a asset.Item, syncType syncItemType, err error) error

WebsocketUpdate notifies the SyncManager to change the last updated time for a exchange asset pair And set IsUsingWebsocket to true. It should be used externally only from websocket updaters

type WebsocketAuth

type WebsocketAuth struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

WebsocketAuth is a struct used for

type WebsocketDataHandler

type WebsocketDataHandler func(service string, incoming interface{}) error

WebsocketDataHandler defines a function signature for a function that handles data coming from websocket connections.

type WebsocketEvent

type WebsocketEvent struct {
	Exchange  string `json:"exchange,omitempty"`
	AssetType string `json:"assetType,omitempty"`
	Event     string
	Data      interface{}
}

WebsocketEvent is the struct used for websocket events

type WebsocketEventResponse

type WebsocketEventResponse struct {
	Event string      `json:"event"`
	Data  interface{} `json:"data"`
	Error string      `json:"error"`
}

WebsocketEventResponse is the struct used for websocket event responses

type WebsocketOrderbookTickerRequest

type WebsocketOrderbookTickerRequest struct {
	Exchange  string `json:"exchangeName"`
	Currency  string `json:"currency"`
	AssetType string `json:"assetType"`
}

WebsocketOrderbookTickerRequest is a struct used for ticker and orderbook requests

type WebsocketRoutineManager

type WebsocketRoutineManager struct {
	// contains filtered or unexported fields
}

WebsocketRoutineManager is used to process websocket updates from a unified location

func (*WebsocketRoutineManager) FormatCurrency

func (m *WebsocketRoutineManager) FormatCurrency(p currency.Pair) currency.Pair

FormatCurrency is a method that formats and returns a currency pair based on the user currency display preferences

func (*WebsocketRoutineManager) IsRunning

func (m *WebsocketRoutineManager) IsRunning() bool

IsRunning safely checks whether the subsystem is running

func (*WebsocketRoutineManager) Start

func (m *WebsocketRoutineManager) Start() error

Start runs the subsystem

func (*WebsocketRoutineManager) Stop

func (m *WebsocketRoutineManager) Stop() error

Stop attempts to shutdown the subsystem

type WithdrawManager

type WithdrawManager struct {
	// contains filtered or unexported fields
}

WithdrawManager is responsible for performing withdrawal requests and saving them to the database

func SetupWithdrawManager

func SetupWithdrawManager(em iExchangeManager, pm iPortfolioManager, isDryRun bool) (*WithdrawManager, error)

SetupWithdrawManager creates a new withdraw manager

func (*WithdrawManager) SubmitWithdrawal

func (m *WithdrawManager) SubmitWithdrawal(ctx context.Context, req *withdraw.Request) (*withdraw.Response, error)

SubmitWithdrawal performs validation and submits a new withdraw request to exchange

func (*WithdrawManager) WithdrawEventByDate

func (m *WithdrawManager) WithdrawEventByDate(exchange string, start, end time.Time, limit int) ([]*withdraw.Response, error)

WithdrawEventByDate returns a withdrawal request by ID

func (*WithdrawManager) WithdrawalEventByExchange

func (m *WithdrawManager) WithdrawalEventByExchange(exchange string, limit int) ([]*withdraw.Response, error)

WithdrawalEventByExchange returns a withdrawal request by ID

func (*WithdrawManager) WithdrawalEventByExchangeID

func (m *WithdrawManager) WithdrawalEventByExchangeID(exchange, id string) (*withdraw.Response, error)

WithdrawalEventByExchangeID returns a withdrawal request by Exchange ID

func (*WithdrawManager) WithdrawalEventByID

func (m *WithdrawManager) WithdrawalEventByID(id string) (*withdraw.Response, error)

WithdrawalEventByID returns a withdrawal request by ID

type WithdrawSettings

type WithdrawSettings struct {
	WithdrawCacheSize uint64
}

WithdrawSettings defines settings related to Withdrawing cryptocurrency

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL