mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-15 07:26:49 +00:00
* Modifications for a smoother live run * Fixes data appending * Successfully allows multi-currency live trading. Adds multiple currencies to live DCA strategy * Attempting to get cash and carry working * Poor attempts at sorting out data and appending it properly with USD in mind * =designs new live data handler * Updates cash and carry strat to work * adds test coverage. begins closeallpositions function * Updates cash and carry to work live * New kline.Event type. Cancels orders on close. Rn types * =Fixes USD funding issue * =fixes tests * fixes tests AGAIN * adds coverage to close all orders * crummy tests, should override * more tests * more tests * more coverage * removes scourge of currency.Pair maps. More tests * missed currency stuff * Fixes USD data issue & collateral issue. Needs to close ALL orders * Now triggers updates on the very first data entry * All my problems are solved now???? * fixes tests, extends coverage * there is some really funky candle stuff going on * my brain is melting * better shutdown management, fixes freezing bug * fixes data duplication issues, adds retries to requests * reduces logging, adds verbose options * expands coverage over all new functionality * fixes fun bug from curr == curr to curr.Equal(curr) * fixes setup issues and tests * starts adding external wallet amounts for funding * more setup for assets * setup live fund calcs and placing orders * successfully performs automated cash and carry * merge fixes * funding properly set at all times * fixes some bugs, need to address currencystatistics still * adds 'appeneded' trait, attempts to fix some stats * fixes stat bugs, adds cool new fetchfees feature * fixes terrible processing bugs * tightens realorder stats, sadly loses some live stats * this actually sets everything correctly for bothcd ..cd ..cd ..cd ..cd ..! * fix tests * coverage * beautiful new test coverage * docs * adds new fee getter delayer * commits from the correct directory * Lint * adds verbose to fund manager * Fix bug in t2b2 strat. Update dca live config. Docs * go mod tidy * update buf * buf + test improvement * Post merge fixes * fixes surprise offset bug * fix sizing restrictions for cash and carry * fix server lints * merge fixes * test fixesss * lintle fixles * slowloris * rn run to task, bug fixes, close all on close * rpc lint and fixes * bugfix: order manager not processing orders properly * somewhat addresses nits * absolutely broken end of day commit * absolutely massive knockon effects from nits * massive knockon effects continue * fixes things * address remaining nits * jk now fixes things * addresses the easier nits * more nit fixers * more niterinos addressederinos * refactors holdings and does some nits * so buf * addresses some nits, fixes holdings bugs * cleanup * attempts to fix alert chans to prevent many chans waiting? * terrible code, will revert * to be reviewed in detail tomorrow * Fixes up channel system * smashes those nits * fixes extra candles, fixes collateral bug, tests * fixes data races, introduces reflection * more checks n tests * Fixes cash and carry issues. Fixes more cool bugs * fixes ~typer~ typo * replace spot strats from ftx to binance * fixes all the tests I just destroyed * removes example path, rm verbose * 1) what 2) removes FTX references from the Backtester * renamed, non-working strategies * Removes FTX references almost as fast as sbf removes funds * regen docs, add contrib names,sort contrib names * fixes merge renamings * Addresses nits. Fixes setting API credentials. Fixes Binance limit retrieval * Fixes live order bugs with real orders and without * Apply suggestions from code review Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> * Update backtester/engine/live.go Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> * Update backtester/engine/live.go Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> * Update backtester/config/strategyconfigbuilder/main.go Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io> * updates docs * even better docs Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>
222 lines
6.4 KiB
Go
222 lines
6.4 KiB
Go
package account
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"sync"
|
|
|
|
"google.golang.org/grpc/metadata"
|
|
)
|
|
|
|
// contextCredential is a string flag for use with context values when setting
|
|
// credentials internally or via gRPC.
|
|
type contextCredential string
|
|
|
|
const (
|
|
// ContextCredentialsFlag used for retrieving api credentials from context
|
|
ContextCredentialsFlag contextCredential = "apicredentials"
|
|
// ContextSubAccountFlag used for retrieving just the sub account from
|
|
// context, when the default config credentials sub account needs to be
|
|
// changed while the same keys can be used.
|
|
ContextSubAccountFlag contextCredential = "subaccountoverride"
|
|
|
|
apiKeyDisplaySize = 16
|
|
)
|
|
|
|
// Default credential values
|
|
const (
|
|
Key = "key"
|
|
Secret = "secret"
|
|
SubAccountSTR = "subaccount"
|
|
ClientID = "clientid"
|
|
OneTimePassword = "otp"
|
|
PEMKey = "pemkey"
|
|
)
|
|
|
|
var (
|
|
errMetaDataIsNil = errors.New("meta data is nil")
|
|
errInvalidCredentialMetaDataLength = errors.New("invalid meta data to process credentials")
|
|
errMissingInfo = errors.New("cannot parse meta data missing information in key value pair")
|
|
)
|
|
|
|
// Credentials define parameters that allow for an authenticated request.
|
|
type Credentials struct {
|
|
Key string
|
|
Secret string
|
|
ClientID string // TODO: Implement with exchange orders functionality
|
|
PEMKey string
|
|
SubAccount string
|
|
OneTimePassword string
|
|
// TODO: Add AccessControl uint8 for READ/WRITE/Withdraw capabilities.
|
|
}
|
|
|
|
// GetMetaData returns the credentials for metadata context deployment
|
|
func (c *Credentials) GetMetaData() (flag, values string) {
|
|
vals := make([]string, 0, 6)
|
|
if c.Key != "" {
|
|
vals = append(vals, Key+":"+c.Key)
|
|
}
|
|
if c.Secret != "" {
|
|
vals = append(vals, Secret+":"+c.Secret)
|
|
}
|
|
if c.SubAccount != "" {
|
|
vals = append(vals, SubAccountSTR+":"+c.SubAccount)
|
|
}
|
|
if c.ClientID != "" {
|
|
vals = append(vals, ClientID+":"+c.ClientID)
|
|
}
|
|
if c.PEMKey != "" {
|
|
vals = append(vals, PEMKey+":"+c.PEMKey)
|
|
}
|
|
if c.OneTimePassword != "" {
|
|
vals = append(vals, OneTimePassword+":"+c.OneTimePassword)
|
|
}
|
|
return string(ContextCredentialsFlag), strings.Join(vals, ",")
|
|
}
|
|
|
|
// String prints out basic credential info (obfuscated) to track key instances
|
|
// associated with exchanges.
|
|
func (c *Credentials) String() string {
|
|
obfuscated := c.Key
|
|
if len(obfuscated) > apiKeyDisplaySize {
|
|
obfuscated = obfuscated[:apiKeyDisplaySize]
|
|
}
|
|
return fmt.Sprintf("Key:[%s...] SubAccount:[%s] ClientID:[%s]",
|
|
obfuscated,
|
|
c.SubAccount,
|
|
c.ClientID)
|
|
}
|
|
|
|
// getInternal returns the values for assignment to an internal context
|
|
func (c *Credentials) getInternal() (contextCredential, *ContextCredentialsStore) {
|
|
if c.IsEmpty() {
|
|
return "", nil
|
|
}
|
|
store := &ContextCredentialsStore{}
|
|
store.Load(c)
|
|
return ContextCredentialsFlag, store
|
|
}
|
|
|
|
// IsEmpty return true if the underlying credentials type has not been filled
|
|
// with at least one item.
|
|
func (c *Credentials) IsEmpty() bool {
|
|
return c == nil || c.ClientID == "" &&
|
|
c.Key == "" &&
|
|
c.OneTimePassword == "" &&
|
|
c.PEMKey == "" &&
|
|
c.Secret == "" &&
|
|
c.SubAccount == ""
|
|
}
|
|
|
|
// Equal determines if the keys are the same.
|
|
// OTP omitted because it's generated per request.
|
|
// PEMKey and Secret omitted because of direct correlation with api key.
|
|
func (c *Credentials) Equal(other *Credentials) bool {
|
|
return c != nil &&
|
|
other != nil &&
|
|
c.Key == other.Key &&
|
|
c.ClientID == other.ClientID &&
|
|
(c.SubAccount == other.SubAccount || c.SubAccount == "" && other.SubAccount == "main" || c.SubAccount == "main" && other.SubAccount == "")
|
|
}
|
|
|
|
// ContextCredentialsStore protects the stored credentials for use in a context
|
|
type ContextCredentialsStore struct {
|
|
creds *Credentials
|
|
mu sync.RWMutex
|
|
}
|
|
|
|
// Load stores provided credentials
|
|
func (c *ContextCredentialsStore) Load(creds *Credentials) {
|
|
// Segregate from external call
|
|
cpy := *creds
|
|
c.mu.Lock()
|
|
c.creds = &cpy
|
|
c.mu.Unlock()
|
|
}
|
|
|
|
// Get returns the full credentials from the store
|
|
func (c *ContextCredentialsStore) Get() *Credentials {
|
|
c.mu.RLock()
|
|
creds := *c.creds
|
|
c.mu.RUnlock()
|
|
return &creds
|
|
}
|
|
|
|
// ParseCredentialsMetadata intercepts and converts credentials metadata to a
|
|
// static type for authentication processing and protection.
|
|
func ParseCredentialsMetadata(ctx context.Context, md metadata.MD) (context.Context, error) {
|
|
if md == nil {
|
|
return ctx, errMetaDataIsNil
|
|
}
|
|
|
|
credMD, ok := md[string(ContextCredentialsFlag)]
|
|
if !ok || len(credMD) == 0 {
|
|
return ctx, nil
|
|
}
|
|
|
|
if len(credMD) != 1 {
|
|
return ctx, errInvalidCredentialMetaDataLength
|
|
}
|
|
|
|
segregatedCreds := strings.Split(credMD[0], ",")
|
|
var ctxCreds Credentials
|
|
var subAccountHere string
|
|
for x := range segregatedCreds {
|
|
keyVals := strings.Split(segregatedCreds[x], ":")
|
|
if len(keyVals) != 2 {
|
|
return ctx, fmt.Errorf("%w received %v fields, expected 2 contains: %s",
|
|
errMissingInfo,
|
|
len(keyVals),
|
|
keyVals)
|
|
}
|
|
switch keyVals[0] {
|
|
case Key:
|
|
ctxCreds.Key = keyVals[1]
|
|
case Secret:
|
|
ctxCreds.Secret = keyVals[1]
|
|
case SubAccountSTR:
|
|
// Capture sub account as this can override if other values are
|
|
// not included in metadata.
|
|
subAccountHere = keyVals[1]
|
|
case ClientID:
|
|
ctxCreds.ClientID = keyVals[1]
|
|
case PEMKey:
|
|
ctxCreds.PEMKey = keyVals[1]
|
|
case OneTimePassword:
|
|
ctxCreds.OneTimePassword = keyVals[1]
|
|
}
|
|
}
|
|
if ctxCreds.IsEmpty() && subAccountHere != "" {
|
|
// This will override default sub account details if needed.
|
|
return DeploySubAccountOverrideToContext(ctx, subAccountHere), nil
|
|
}
|
|
// merge sub account to main context credentials
|
|
ctxCreds.SubAccount = subAccountHere
|
|
return DeployCredentialsToContext(ctx, &ctxCreds), nil
|
|
}
|
|
|
|
// DeployCredentialsToContext sets credentials for internal use to context which
|
|
// can override default credential values.
|
|
func DeployCredentialsToContext(ctx context.Context, creds *Credentials) context.Context {
|
|
flag, store := creds.getInternal()
|
|
return context.WithValue(ctx, flag, store)
|
|
}
|
|
|
|
// DeploySubAccountOverrideToContext sets subaccount as override to credentials
|
|
// as a separate flag.
|
|
func DeploySubAccountOverrideToContext(ctx context.Context, subAccount string) context.Context {
|
|
return context.WithValue(ctx, ContextSubAccountFlag, subAccount)
|
|
}
|
|
|
|
// String strings the credentials in a protected way.
|
|
func (p *Protected) String() string {
|
|
return p.creds.String()
|
|
}
|
|
|
|
// Equal determines if the keys are the same
|
|
func (p *Protected) Equal(other *Credentials) bool {
|
|
return p.creds.Equal(other)
|
|
}
|