codebase: Cleanup various things (#1935)

* codebase: Rid base64/hex to string common funcs

* codebase: Rid local scope variable usage and other improvements

* codebase: Refactor currency pair usage across multiple exchanges

- Updated HitBTC tests to use the new currency pair format.
- Modified Kraken futures types to use currency.Pair instead of string for Symbol.
- Adjusted Kraken wrapper methods to handle currency pairs correctly.
- Refined OKX tests and types to utilize currency.Pair for instrument IDs.
- Enhanced Poloniex tests to consistently use predefined currency pairs.
- Streamlined order and orderbook tests to replace string pairs with currency.NewBTCUSD().
- Improved Yobit tests to utilize a standardized currency pair format.
- Updated validator wrapper to use currency pairs directly instead of string conversions.

* codebase: Use types.Number where possible

* refactor: update PayoutFee type to types.Number for consistency

* Refactor: Remove crypto functions to use standard library and other minor changes

- Removed custom crypto functions for SHA256, SHA512, and MD5 from the common/crypto package.
- Replaced usages of removed functions with standard library implementations in various files including:
  - cmd/websocket_client/main.go
  - engine/apiserver.go
  - exchanges/kraken/kraken.go
  - exchanges/lbank/lbank.go
  - exchanges/okx/okx_business_websocket.go
  - exchanges/kucoin/kucoin_websocket.go
  - gctscript/vm/vm.go
- Updated tests to reflect changes in the crypto functions.
- Renamed several functions for clarity, particularly in the context of order book updates across multiple exchanges.

* refactor: replace assert with require for consistency in test assertions

* refactor: Improve Binance futures candlestick test, standardise orderbook update function names and improve test parallelism

* refactor: Replace require.Len with require.Equal for better output in TestGetFuturesKlineData
This commit is contained in:
Adrian Gallagher
2025-06-12 14:12:36 +10:00
committed by GitHub
parent ce134a0a1d
commit d5ba674fc4
115 changed files with 1327 additions and 3112 deletions

View File

@@ -3,15 +3,14 @@ package hitbtc
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/crypto"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
@@ -450,13 +449,11 @@ func (h *HitBTC) SendAuthenticatedHTTPRequest(ctx context.Context, ep exchange.U
return err
}
headers := make(map[string]string)
headers["Authorization"] = "Basic " + crypto.Base64Encode([]byte(creds.Key+":"+creds.Secret))
path := fmt.Sprintf("%s/%s", ePoint, endpoint)
headers["Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(creds.Key+":"+creds.Secret))
item := &request.Item{
Method: method,
Path: path,
Path: ePoint + "/" + endpoint,
Headers: headers,
Result: result,
Verbose: h.Verbose,
@@ -490,10 +487,7 @@ func (h *HitBTC) GetFee(ctx context.Context, feeBuilder *exchange.FeeBuilder) (f
if err != nil {
return 0, err
}
fee, err = strconv.ParseFloat(currencyInfo.PayoutFee, 64)
if err != nil {
return 0, err
}
fee = currencyInfo.PayoutFee.Float64()
case exchange.CryptocurrencyDepositFee:
fee = calculateCryptocurrencyDepositFee(feeBuilder.Pair.Base,
feeBuilder.Amount)

View File

@@ -39,6 +39,8 @@ const (
canManipulateRealOrders = false
)
var spotPair = currency.NewBTCUSD().Format(currency.PairFormat{Uppercase: true})
func TestMain(m *testing.M) {
h.SetDefaults()
cfg := config.GetConfig()
@@ -69,54 +71,36 @@ func TestMain(m *testing.M) {
}
func TestGetOrderbook(t *testing.T) {
_, err := h.GetOrderbook(t.Context(), "BTCUSD", 50)
if err != nil {
t.Error("Test failed - HitBTC GetOrderbook() error", err)
}
_, err := h.GetOrderbook(t.Context(), spotPair.String(), 50)
assert.NoError(t, err, "GetOrderbook should not error")
}
func TestGetTrades(t *testing.T) {
_, err := h.GetTrades(t.Context(), "BTCUSD", "", "", 0, 0, 0, 0)
if err != nil {
t.Error("Test failed - HitBTC GetTradeHistory() error", err)
}
_, err := h.GetTrades(t.Context(), spotPair.String(), "", "", 0, 0, 0, 0)
assert.NoError(t, err, "GetTrades should not error")
}
func TestGetChartCandles(t *testing.T) {
_, err := h.GetCandles(t.Context(),
"BTCUSD", "", "D1", time.Now().Add(-24*time.Hour), time.Now())
if err != nil {
t.Error("Test failed - HitBTC GetChartData() error", err)
}
_, err := h.GetCandles(t.Context(), spotPair.String(), "", "D1", time.Now().Add(-24*time.Hour), time.Now())
assert.NoError(t, err, "GetCandles should not error")
}
func TestGetHistoricCandles(t *testing.T) {
t.Parallel()
pair, err := currency.NewPairFromString("BTC-USD")
if err != nil {
t.Fatal(err)
}
startTime := time.Now().Add(-time.Hour * 6)
end := time.Now()
_, err = h.GetHistoricCandles(t.Context(), pair, asset.Spot, kline.OneMin, startTime, end)
if err != nil {
t.Fatal(err)
}
_, err := h.GetHistoricCandles(t.Context(), spotPair, asset.Spot, kline.OneMin, startTime, end)
assert.NoError(t, err, "GetHistoricCandles should not error")
}
func TestGetHistoricCandlesExtended(t *testing.T) {
t.Parallel()
pair, err := currency.NewPairFromString("BTC-USD")
if err != nil {
t.Fatal(err)
}
startTime := time.Unix(1546300800, 0)
end := time.Unix(1577836799, 0)
_, err = h.GetHistoricCandlesExtended(t.Context(), pair, asset.Spot, kline.OneHour, startTime, end)
if err != nil {
t.Fatal(err)
}
_, err := h.GetHistoricCandlesExtended(t.Context(), spotPair, asset.Spot, kline.OneHour, startTime, end)
assert.NoError(t, err, "GetHistoricCandlesExtended should not error")
}
func TestGetCurrencies(t *testing.T) {
@@ -191,10 +175,8 @@ func TestGetAllTickers(t *testing.T) {
}
func TestGetSingularTicker(t *testing.T) {
_, err := h.GetTicker(t.Context(), "BTCUSD")
if err != nil {
t.Error(err)
}
_, err := h.GetTicker(t.Context(), spotPair.String())
assert.NoError(t, err, "GetTicker should not error")
}
func TestGetFee(t *testing.T) {
@@ -964,81 +946,51 @@ func TestWsTrades(t *testing.T) {
}
}
func Test_FormatExchangeKlineInterval(t *testing.T) {
func TestFormatExchangeKlineInterval(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
for _, tc := range []struct {
interval kline.Interval
output string
}{
{
"OneMin",
kline.OneMin,
"M1",
},
{
"OneDay",
kline.OneDay,
"D1",
},
{
"SevenDay",
kline.SevenDay,
"D7",
},
{
"OneMonth",
kline.OneMonth,
"1M",
},
}
for x := range testCases {
test := testCases[x]
t.Run(test.name, func(t *testing.T) {
} {
t.Run(tc.interval.String(), func(t *testing.T) {
t.Parallel()
ret, err := formatExchangeKlineInterval(test.interval)
if err != nil {
t.Fatal(err)
}
if ret != test.output {
t.Fatalf("unexpected result return expected: %v received: %v", test.output, ret)
}
ret, err := formatExchangeKlineInterval(tc.interval)
require.NoError(t, err)
assert.Equal(t, tc.output, ret)
})
}
}
func TestGetRecentTrades(t *testing.T) {
t.Parallel()
currencyPair, err := currency.NewPairFromString("BTCUSD")
if err != nil {
t.Fatal(err)
}
_, err = h.GetRecentTrades(t.Context(), currencyPair, asset.Spot)
if err != nil {
t.Error(err)
}
_, err := h.GetRecentTrades(t.Context(), spotPair, asset.Spot)
assert.NoError(t, err, "GetRecentTrades should not error")
}
func TestGetHistoricTrades(t *testing.T) {
t.Parallel()
currencyPair, err := currency.NewPairFromString("BTCUSD")
if err != nil {
t.Fatal(err)
}
_, err = h.GetHistoricTrades(t.Context(),
currencyPair, asset.Spot, time.Now().Add(-time.Minute*15), time.Now())
if err != nil && err != common.ErrFunctionNotSupported {
t.Error(err)
}
_, err := h.GetHistoricTrades(t.Context(), spotPair, asset.Spot, time.Now().Add(-time.Minute*15), time.Now())
assert.NoError(t, err, "GetHistoricTrades should not error")
// longer term
_, err = h.GetHistoricTrades(t.Context(),
currencyPair, asset.Spot,
time.Now().Add(-time.Minute*60*200),
time.Now().Add(-time.Minute*60*199))
if err != nil {
t.Error(err)
}
_, err = h.GetHistoricTrades(t.Context(), spotPair, asset.Spot, time.Now().Add(-time.Minute*60*200), time.Now().Add(-time.Minute*60*199))
assert.NoError(t, err, "GetHistoricTrades should not error")
}
func TestGetActiveOrderByClientOrderID(t *testing.T) {

View File

@@ -4,6 +4,7 @@ import (
"time"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/types"
)
// TickerResponse is the response type
@@ -66,17 +67,17 @@ type ChartData struct {
// Currencies hold the full range of data for a specified currency
type Currencies struct {
ID string `json:"id"` // Currency identifier.
FullName string `json:"fullName"` // Currency full name
Crypto bool `json:"crypto"` // Is currency belongs to blockchain (false for ICO and fiat, like EUR)
PayinEnabled bool `json:"payinEnabled"` // Is allowed for deposit (false for ICO)
PayinPaymentID bool `json:"payinPaymentId"` // Is required to provide additional information other than the address for deposit
PayinConfirmations int64 `json:"payinConfirmations"` // Blocks confirmations count for deposit
PayoutEnabled bool `json:"payoutEnabled"` // Is allowed for withdraw (false for ICO)
PayoutIsPaymentID bool `json:"payoutIsPaymentId"` // Is allowed to provide additional information for withdraw
TransferEnabled bool `json:"transferEnabled"` // Is allowed to transfer between trading and account (may be disabled on maintain)
Delisted bool `json:"delisted"` // True if currency delisted (stopped deposit and trading)
PayoutFee string `json:"payoutFee"` // Default withdraw fee
ID string `json:"id"` // Currency identifier.
FullName string `json:"fullName"` // Currency full name
Crypto bool `json:"crypto"` // Is currency belongs to blockchain (false for ICO and fiat, like EUR)
PayinEnabled bool `json:"payinEnabled"` // Is allowed for deposit (false for ICO)
PayinPaymentID bool `json:"payinPaymentId"` // Is required to provide additional information other than the address for deposit
PayinConfirmations int64 `json:"payinConfirmations"` // Blocks confirmations count for deposit
PayoutEnabled bool `json:"payoutEnabled"` // Is allowed for withdraw (false for ICO)
PayoutIsPaymentID bool `json:"payoutIsPaymentId"` // Is allowed to provide additional information for withdraw
TransferEnabled bool `json:"transferEnabled"` // Is allowed to transfer between trading and account (may be disabled on maintain)
Delisted bool `json:"delisted"` // True if currency delisted (stopped deposit and trading)
PayoutFee types.Number `json:"payoutFee"` // Default withdraw fee
}
// LoanOrder contains information about your loans

View File

@@ -2,6 +2,7 @@ package hitbtc
import (
"context"
"encoding/hex"
"errors"
"fmt"
"net/http"
@@ -548,9 +549,7 @@ func (h *HitBTC) wsLogin(ctx context.Context) error {
}
h.Websocket.SetCanUseAuthenticatedEndpoints(true)
n := strconv.FormatInt(time.Now().Unix(), 10)
hmac, err := crypto.GetHMAC(crypto.HashSHA256,
[]byte(n),
[]byte(creds.Secret))
hmac, err := crypto.GetHMAC(crypto.HashSHA256, []byte(n), []byte(creds.Secret))
if err != nil {
return err
}
@@ -561,7 +560,7 @@ func (h *HitBTC) wsLogin(ctx context.Context) error {
Algo: "HS256",
PKey: creds.Key,
Nonce: n,
Signature: crypto.HexEncodeToString(hmac),
Signature: hex.EncodeToString(hmac),
},
ID: h.Websocket.Conn.GenerateMessageID(false),
}