qbtrade/pkg/exchange/factory.go

76 lines
2.1 KiB
Go
Raw Normal View History

2024-06-27 14:42:38 +00:00
package exchange
import (
"fmt"
"os"
"strings"
"git.qtrade.icu/lychiyu/qbtrade/pkg/exchange/binance"
"git.qtrade.icu/lychiyu/qbtrade/pkg/exchange/bitget"
"git.qtrade.icu/lychiyu/qbtrade/pkg/exchange/bybit"
"git.qtrade.icu/lychiyu/qbtrade/pkg/exchange/kucoin"
"git.qtrade.icu/lychiyu/qbtrade/pkg/exchange/max"
"git.qtrade.icu/lychiyu/qbtrade/pkg/exchange/okex"
"git.qtrade.icu/lychiyu/qbtrade/pkg/types"
)
func NewPublic(exchangeName types.ExchangeName) (types.Exchange, error) {
2024-07-21 14:42:15 +00:00
exMinimal, err := New(exchangeName, "", "", "", "")
2024-06-27 14:42:38 +00:00
if err != nil {
return nil, err
}
if ex, ok := exMinimal.(types.Exchange); ok {
return ex, nil
}
return nil, fmt.Errorf("exchange %T does not implement types.Exchange", exMinimal)
}
2024-07-21 14:42:15 +00:00
func New(n types.ExchangeName, key, secret, passphrase, proxy string) (types.ExchangeMinimal, error) {
2024-06-27 14:42:38 +00:00
switch n {
case types.ExchangeBinance:
2024-07-21 14:42:15 +00:00
return binance.New(key, secret, proxy), nil
2024-06-27 14:42:38 +00:00
case types.ExchangeMax:
return max.New(key, secret), nil
case types.ExchangeOKEx:
return okex.New(key, secret, passphrase), nil
case types.ExchangeKucoin:
return kucoin.New(key, secret, passphrase), nil
case types.ExchangeBitget:
return bitget.New(key, secret, passphrase), nil
case types.ExchangeBybit:
return bybit.New(key, secret)
default:
return nil, fmt.Errorf("unsupported exchange: %v", n)
}
}
// NewWithEnvVarPrefix allocate and initialize the exchange instance with the given environment variable prefix
// When the varPrefix is a empty string, the default exchange name will be used as the prefix
func NewWithEnvVarPrefix(n types.ExchangeName, varPrefix string) (types.ExchangeMinimal, error) {
if len(varPrefix) == 0 {
varPrefix = n.String()
}
varPrefix = strings.ToUpper(varPrefix)
key := os.Getenv(varPrefix + "_API_KEY")
secret := os.Getenv(varPrefix + "_API_SECRET")
if len(key) == 0 || len(secret) == 0 {
return nil, fmt.Errorf("can not initialize exchange %s: empty key or secret, env var prefix: %s", n, varPrefix)
}
passphrase := os.Getenv(varPrefix + "_API_PASSPHRASE")
2024-07-21 14:42:15 +00:00
proxy := os.Getenv(varPrefix + "_PROXY")
return New(n, key, secret, passphrase, proxy)
2024-06-27 14:42:38 +00:00
}