Exchanges: Convert bespoke Number types to types.Number (#1429)

* Kucoin: Rename WsSpotTicker => WsSnapshot

* Kucoin: Replace kucoinNumber => types.Number

* Okcoin: Convert to types.Number

* Gateio: Convert to types.Number

* Okx: Convert to types.Number
This commit is contained in:
Gareth Kirwan
2023-12-28 04:55:23 +01:00
committed by GitHub
parent 9986e80e2d
commit 2b3c63c5b3
14 changed files with 334 additions and 583 deletions

View File

@@ -51,33 +51,3 @@ func (a *gateioTime) UnmarshalJSON(data []byte) error {
// Time represents a time instance.
func (a gateioTime) Time() time.Time { return time.Time(a) }
type gateioNumericalValue float64
// UnmarshalJSON is custom type json unmarshaller for gateioNumericalValue
func (a *gateioNumericalValue) UnmarshalJSON(data []byte) error {
var num interface{}
err := json.Unmarshal(data, &num)
if err != nil {
return err
}
switch d := num.(type) {
case float64:
*a = gateioNumericalValue(d)
case string:
if d == "" {
*a = gateioNumericalValue(0)
return nil
}
convNum, err := strconv.ParseFloat(d, 64)
if err != nil {
return err
}
*a = gateioNumericalValue(convNum)
}
return nil
}
// Float64 returns float64 value from gateioNumericalValue instance.
func (a gateioNumericalValue) Float64() float64 { return float64(a) }

View File

@@ -3307,45 +3307,6 @@ func TestParseGateioTimeUnmarshal(t *testing.T) {
}
}
func TestGateioNumericalValue(t *testing.T) {
t.Parallel()
in := &struct {
Number gateioNumericalValue `json:"number"`
}{}
numberJSON := `{"number":123442.231}`
err := json.Unmarshal([]byte(numberJSON), in)
if err != nil {
t.Fatal(err)
} else if in.Number != 123442.231 {
t.Fatalf("found %f, but expected %f", in.Number, 123442.231)
}
numberJSON = `{"number":"123442.231"}`
err = json.Unmarshal([]byte(numberJSON), in)
if err != nil {
t.Fatal(err)
} else if in.Number != 123442.231 {
t.Fatalf("found %f, but expected %s", in.Number, "123442.231")
}
numberJSON = `{"number":""}`
err = json.Unmarshal([]byte(numberJSON), in)
if err != nil {
t.Fatal(err)
} else if in.Number != 0 {
t.Fatalf("found %f, but expected %d", in.Number, 0)
}
numberJSON = `{"number":0}`
err = json.Unmarshal([]byte(numberJSON), in)
if err != nil {
t.Fatal(err)
} else if in.Number != 0 {
t.Fatalf("found %f, but expected %d", in.Number, 0)
}
}
func TestUpdateOrderExecutionLimits(t *testing.T) {
t.Parallel()

View File

@@ -492,36 +492,36 @@ type CurrencyInfo struct {
// CurrencyPairDetail represents a single currency pair detail.
type CurrencyPairDetail struct {
ID string `json:"id"`
Base string `json:"base"`
Quote string `json:"quote"`
TradingFee gateioNumericalValue `json:"fee"`
MinBaseAmount gateioNumericalValue `json:"min_base_amount"`
MinQuoteAmount gateioNumericalValue `json:"min_quote_amount"`
AmountPrecision float64 `json:"amount_precision"` // Amount scale
Precision float64 `json:"precision"` // Price scale
TradeStatus string `json:"trade_status"`
SellStart float64 `json:"sell_start"`
BuyStart float64 `json:"buy_start"`
ID string `json:"id"`
Base string `json:"base"`
Quote string `json:"quote"`
TradingFee types.Number `json:"fee"`
MinBaseAmount types.Number `json:"min_base_amount"`
MinQuoteAmount types.Number `json:"min_quote_amount"`
AmountPrecision float64 `json:"amount_precision"` // Amount scale
Precision float64 `json:"precision"` // Price scale
TradeStatus string `json:"trade_status"`
SellStart float64 `json:"sell_start"`
BuyStart float64 `json:"buy_start"`
}
// Ticker holds detail ticker information for a currency pair
type Ticker struct {
CurrencyPair string `json:"currency_pair"`
Last gateioNumericalValue `json:"last"`
LowestAsk gateioNumericalValue `json:"lowest_ask"`
HighestBid gateioNumericalValue `json:"highest_bid"`
ChangePercentage string `json:"change_percentage"`
ChangeUtc0 string `json:"change_utc0"`
ChangeUtc8 string `json:"change_utc8"`
BaseVolume gateioNumericalValue `json:"base_volume"`
QuoteVolume gateioNumericalValue `json:"quote_volume"`
High24H gateioNumericalValue `json:"high_24h"`
Low24H gateioNumericalValue `json:"low_24h"`
EtfNetValue string `json:"etf_net_value"`
EtfPreNetValue string `json:"etf_pre_net_value"`
EtfPreTimestamp gateioTime `json:"etf_pre_timestamp"`
EtfLeverage gateioNumericalValue `json:"etf_leverage"`
CurrencyPair string `json:"currency_pair"`
Last types.Number `json:"last"`
LowestAsk types.Number `json:"lowest_ask"`
HighestBid types.Number `json:"highest_bid"`
ChangePercentage string `json:"change_percentage"`
ChangeUtc0 string `json:"change_utc0"`
ChangeUtc8 string `json:"change_utc8"`
BaseVolume types.Number `json:"base_volume"`
QuoteVolume types.Number `json:"quote_volume"`
High24H types.Number `json:"high_24h"`
Low24H types.Number `json:"low_24h"`
EtfNetValue string `json:"etf_net_value"`
EtfPreNetValue string `json:"etf_pre_net_value"`
EtfPreTimestamp gateioTime `json:"etf_pre_timestamp"`
EtfLeverage types.Number `json:"etf_leverage"`
}
// OrderbookData holds orderbook ask and bid datas.
@@ -552,7 +552,7 @@ func (a *OrderbookData) MakeOrderbook() (*Orderbook, error) {
return nil, err
}
ob.Asks[x] = OrderbookItem{
Price: gateioNumericalValue(price),
Price: types.Number(price),
Amount: amount,
}
}
@@ -566,7 +566,7 @@ func (a *OrderbookData) MakeOrderbook() (*Orderbook, error) {
return nil, err
}
ob.Bids[x] = OrderbookItem{
Price: gateioNumericalValue(price),
Price: types.Number(price),
Amount: amount,
}
}
@@ -575,8 +575,8 @@ func (a *OrderbookData) MakeOrderbook() (*Orderbook, error) {
// OrderbookItem stores an orderbook item
type OrderbookItem struct {
Price gateioNumericalValue `json:"p"`
Amount float64 `json:"s"`
Price types.Number `json:"p"`
Amount float64 `json:"s"`
}
// Orderbook stores the orderbook data
@@ -744,8 +744,8 @@ type FuturesTicker struct {
// FuturesFundingRate represents futures funding rate response.
type FuturesFundingRate struct {
Timestamp gateioTime `json:"t"`
Rate gateioNumericalValue `json:"r"`
Timestamp gateioTime `json:"t"`
Rate types.Number `json:"r"`
}
// InsuranceBalance represents futures insurance balance item.
@@ -783,18 +783,18 @@ type IndexConstituent struct {
// LiquidationHistory represents liquidation history for a specifies settle.
type LiquidationHistory struct {
Time gateioTime `json:"time"`
Contract string `json:"contract"`
Size int64 `json:"size"`
Leverage string `json:"leverage"`
Margin string `json:"margin"`
EntryPrice types.Number `json:"entry_price"`
LiquidationPrice gateioNumericalValue `json:"liq_price"`
MarkPrice types.Number `json:"mark_price"`
OrderID int64 `json:"order_id"`
OrderPrice types.Number `json:"order_price"`
FillPrice types.Number `json:"fill_price"`
Left int64 `json:"left"`
Time gateioTime `json:"time"`
Contract string `json:"contract"`
Size int64 `json:"size"`
Leverage string `json:"leverage"`
Margin string `json:"margin"`
EntryPrice types.Number `json:"entry_price"`
LiquidationPrice types.Number `json:"liq_price"`
MarkPrice types.Number `json:"mark_price"`
OrderID int64 `json:"order_id"`
OrderPrice types.Number `json:"order_price"`
FillPrice types.Number `json:"fill_price"`
Left int64 `json:"left"`
}
// DeliveryContract represents a delivery contract instance detail.
@@ -888,12 +888,12 @@ type OptionContract struct {
// OptionSettlement list settlement history
type OptionSettlement struct {
Timestamp gateioTime `json:"time"`
Profit gateioNumericalValue `json:"profit"`
Fee gateioNumericalValue `json:"fee"`
SettlePrice types.Number `json:"settle_price"`
Contract string `json:"contract"`
StrikePrice types.Number `json:"strike_price"`
Timestamp gateioTime `json:"time"`
Profit types.Number `json:"profit"`
Fee types.Number `json:"fee"`
SettlePrice types.Number `json:"settle_price"`
Contract string `json:"contract"`
StrikePrice types.Number `json:"strike_price"`
}
// SwapCurrencies represents Flash Swap supported currencies
@@ -919,26 +919,26 @@ type MyOptionSettlement struct {
// OptionsTicker represents tickers of options contracts
type OptionsTicker struct {
Name currency.Pair `json:"name"`
LastPrice gateioNumericalValue `json:"last_price"`
MarkPrice gateioNumericalValue `json:"mark_price"`
PositionSize float64 `json:"position_size"`
Ask1Size float64 `json:"ask1_size"`
Ask1Price types.Number `json:"ask1_price"`
Bid1Size float64 `json:"bid1_size"`
Bid1Price types.Number `json:"bid1_price"`
Vega string `json:"vega"`
Theta string `json:"theta"`
Rho string `json:"rho"`
Gamma string `json:"gamma"`
Delta string `json:"delta"`
MarkImpliedVolatility gateioNumericalValue `json:"mark_iv"`
BidImpliedVolatility gateioNumericalValue `json:"bid_iv"`
AskImpliedVolatility gateioNumericalValue `json:"ask_iv"`
Leverage gateioNumericalValue `json:"leverage"`
Name currency.Pair `json:"name"`
LastPrice types.Number `json:"last_price"`
MarkPrice types.Number `json:"mark_price"`
PositionSize float64 `json:"position_size"`
Ask1Size float64 `json:"ask1_size"`
Ask1Price types.Number `json:"ask1_price"`
Bid1Size float64 `json:"bid1_size"`
Bid1Price types.Number `json:"bid1_price"`
Vega string `json:"vega"`
Theta string `json:"theta"`
Rho string `json:"rho"`
Gamma string `json:"gamma"`
Delta string `json:"delta"`
MarkImpliedVolatility types.Number `json:"mark_iv"`
BidImpliedVolatility types.Number `json:"bid_iv"`
AskImpliedVolatility types.Number `json:"ask_iv"`
Leverage types.Number `json:"leverage"`
// Added fields for the websocket
IndexPrice gateioNumericalValue `json:"index_price"`
IndexPrice types.Number `json:"index_price"`
}
// OptionsUnderlyingTicker represents underlying ticker
@@ -1389,39 +1389,39 @@ type CreateOrderRequestData struct {
// SpotOrder represents create order response.
type SpotOrder struct {
OrderID string `json:"id,omitempty"`
Text string `json:"text,omitempty"`
Succeeded bool `json:"succeeded"`
ErrorLabel string `json:"label,omitempty"`
Message string `json:"message,omitempty"`
CreateTime gateioTime `json:"create_time,omitempty"`
CreateTimeMs gateioTime `json:"create_time_ms,omitempty"`
UpdateTime gateioTime `json:"update_time,omitempty"`
UpdateTimeMs gateioTime `json:"update_time_ms,omitempty"`
CurrencyPair string `json:"currency_pair,omitempty"`
Status string `json:"status,omitempty"`
Type string `json:"type,omitempty"`
Account string `json:"account,omitempty"`
Side string `json:"side,omitempty"`
Amount types.Number `json:"amount,omitempty"`
Price types.Number `json:"price,omitempty"`
TimeInForce string `json:"time_in_force,omitempty"`
Iceberg string `json:"iceberg,omitempty"`
AutoRepay bool `json:"auto_repay"`
AutoBorrow bool `json:"auto_borrow"`
Left gateioNumericalValue `json:"left"`
AverageFillPrice types.Number `json:"avg_deal_price"`
FeeDeducted types.Number `json:"fee"`
FeeCurrency string `json:"fee_currency"`
FillPrice types.Number `json:"fill_price"` // Total filled in quote currency. Deprecated in favor of filled_total
FilledTotal types.Number `json:"filled_total"` // Total filled in quote currency
PointFee types.Number `json:"point_fee"`
GtFee string `json:"gt_fee,omitempty"`
GtDiscount bool `json:"gt_discount"`
GtMakerFee types.Number `json:"gt_maker_fee"`
GtTakerFee types.Number `json:"gt_taker_fee"`
RebatedFee types.Number `json:"rebated_fee"`
RebatedFeeCurrency string `json:"rebated_fee_currency"`
OrderID string `json:"id,omitempty"`
Text string `json:"text,omitempty"`
Succeeded bool `json:"succeeded"`
ErrorLabel string `json:"label,omitempty"`
Message string `json:"message,omitempty"`
CreateTime gateioTime `json:"create_time,omitempty"`
CreateTimeMs gateioTime `json:"create_time_ms,omitempty"`
UpdateTime gateioTime `json:"update_time,omitempty"`
UpdateTimeMs gateioTime `json:"update_time_ms,omitempty"`
CurrencyPair string `json:"currency_pair,omitempty"`
Status string `json:"status,omitempty"`
Type string `json:"type,omitempty"`
Account string `json:"account,omitempty"`
Side string `json:"side,omitempty"`
Amount types.Number `json:"amount,omitempty"`
Price types.Number `json:"price,omitempty"`
TimeInForce string `json:"time_in_force,omitempty"`
Iceberg string `json:"iceberg,omitempty"`
AutoRepay bool `json:"auto_repay"`
AutoBorrow bool `json:"auto_borrow"`
Left types.Number `json:"left"`
AverageFillPrice types.Number `json:"avg_deal_price"`
FeeDeducted types.Number `json:"fee"`
FeeCurrency string `json:"fee_currency"`
FillPrice types.Number `json:"fill_price"` // Total filled in quote currency. Deprecated in favor of filled_total
FilledTotal types.Number `json:"filled_total"` // Total filled in quote currency
PointFee types.Number `json:"point_fee"`
GtFee string `json:"gt_fee,omitempty"`
GtDiscount bool `json:"gt_discount"`
GtMakerFee types.Number `json:"gt_maker_fee"`
GtTakerFee types.Number `json:"gt_taker_fee"`
RebatedFee types.Number `json:"rebated_fee"`
RebatedFeeCurrency string `json:"rebated_fee_currency"`
}
// SpotOrdersDetail represents list of orders for specific currency pair
@@ -2067,34 +2067,34 @@ type WsOrderbookSnapshot struct {
// WsSpotOrder represents an order push data through the websocket channel.
type WsSpotOrder struct {
ID string `json:"id,omitempty"`
User int64 `json:"user"`
Text string `json:"text,omitempty"`
Succeeded bool `json:"succeeded,omitempty"`
Label string `json:"label,omitempty"`
Message string `json:"message,omitempty"`
CurrencyPair currency.Pair `json:"currency_pair,omitempty"`
Type string `json:"type,omitempty"`
Account string `json:"account,omitempty"`
Side string `json:"side,omitempty"`
Amount types.Number `json:"amount,omitempty"`
Price types.Number `json:"price,omitempty"`
TimeInForce string `json:"time_in_force,omitempty"`
Iceberg string `json:"iceberg,omitempty"`
Left gateioNumericalValue `json:"left,omitempty"`
FilledTotal types.Number `json:"filled_total,omitempty"`
Fee types.Number `json:"fee,omitempty"`
FeeCurrency string `json:"fee_currency,omitempty"`
PointFee string `json:"point_fee,omitempty"`
GtFee string `json:"gt_fee,omitempty"`
GtDiscount bool `json:"gt_discount,omitempty"`
RebatedFee string `json:"rebated_fee,omitempty"`
RebatedFeeCurrency string `json:"rebated_fee_currency,omitempty"`
Event string `json:"event"`
CreateTime gateioTime `json:"create_time,omitempty"`
CreateTimeMs gateioTime `json:"create_time_ms,omitempty"`
UpdateTime gateioTime `json:"update_time,omitempty"`
UpdateTimeMs gateioTime `json:"update_time_ms,omitempty"`
ID string `json:"id,omitempty"`
User int64 `json:"user"`
Text string `json:"text,omitempty"`
Succeeded bool `json:"succeeded,omitempty"`
Label string `json:"label,omitempty"`
Message string `json:"message,omitempty"`
CurrencyPair currency.Pair `json:"currency_pair,omitempty"`
Type string `json:"type,omitempty"`
Account string `json:"account,omitempty"`
Side string `json:"side,omitempty"`
Amount types.Number `json:"amount,omitempty"`
Price types.Number `json:"price,omitempty"`
TimeInForce string `json:"time_in_force,omitempty"`
Iceberg string `json:"iceberg,omitempty"`
Left types.Number `json:"left,omitempty"`
FilledTotal types.Number `json:"filled_total,omitempty"`
Fee types.Number `json:"fee,omitempty"`
FeeCurrency string `json:"fee_currency,omitempty"`
PointFee string `json:"point_fee,omitempty"`
GtFee string `json:"gt_fee,omitempty"`
GtDiscount bool `json:"gt_discount,omitempty"`
RebatedFee string `json:"rebated_fee,omitempty"`
RebatedFeeCurrency string `json:"rebated_fee_currency,omitempty"`
Event string `json:"event"`
CreateTime gateioTime `json:"create_time,omitempty"`
CreateTimeMs gateioTime `json:"create_time_ms,omitempty"`
UpdateTime gateioTime `json:"update_time,omitempty"`
UpdateTimeMs gateioTime `json:"update_time_ms,omitempty"`
}
// WsUserPersonalTrade represents a user's personal trade pushed through the websocket connection.

View File

@@ -3,7 +3,6 @@ package kucoin
import (
"encoding/json"
"fmt"
"strconv"
)
// UnmarshalJSON valid data to SubAccountsResponse of return nil if the data is empty list.
@@ -25,43 +24,3 @@ func (a *SubAccountsResponse) UnmarshalJSON(data []byte) error {
}
return fmt.Errorf("%w can not unmarshal to SubAccountsResponse", errMalformedData)
}
// kucoinNumber unmarshals and extract numeric value from a byte slice.
type kucoinNumber float64
// Float64 returns an float64 value from kucoinNumeric instance
func (a *kucoinNumber) Float64() float64 {
return float64(*a)
}
// UnmarshalJSON decerializes integer and string data having an integer value to int64
func (a *kucoinNumber) UnmarshalJSON(data []byte) error {
var value interface{}
err := json.Unmarshal(data, &value)
if err != nil {
return err
}
switch val := value.(type) {
case float64:
*a = kucoinNumber(val)
case float32:
*a = kucoinNumber(val)
case string:
if val == "" {
*a = kucoinNumber(0) // setting empty string value to zero to reset previous value if exist.
return nil
}
value, err := strconv.ParseFloat(val, 64)
if err != nil {
return err
}
*a = kucoinNumber(value)
case int64:
*a = kucoinNumber(val)
case int32:
*a = kucoinNumber(val)
default:
return fmt.Errorf("unsupported input numeric type %T", value)
}
return nil
}

View File

@@ -2315,62 +2315,6 @@ func TestFetchAccountInfo(t *testing.T) {
}
}
func TestKucoinNumberUnmarshal(t *testing.T) {
t.Parallel()
data := &struct {
Number kucoinNumber `json:"number"`
}{}
data1 := `{"number": 123.33}`
err := json.Unmarshal([]byte(data1), &data)
if err != nil {
t.Fatal(err)
} else if data.Number.Float64() != 123.33 {
t.Errorf("expecting %.2f, got %.2f", 123.33, data.Number)
}
data2 := `{"number": "123.33"}`
err = json.Unmarshal([]byte(data2), &data)
if err != nil {
t.Fatal(err)
} else if data.Number.Float64() != 123.33 {
t.Errorf("expecting %.2f, got %.2f", 123.33, data.Number)
}
data3 := `{"number": ""}`
err = json.Unmarshal([]byte(data3), &data)
if err != nil {
t.Fatal(err)
} else if data.Number.Float64() != 0 {
t.Errorf("expecting %d, got %.2f", 0, data.Number)
}
data4 := `{"number": "123"}`
err = json.Unmarshal([]byte(data4), &data)
if err != nil {
t.Fatal(err)
} else if data.Number.Float64() != 123 {
t.Errorf("expecting %d, got %.2f", 123, data.Number)
}
data5 := `{"number": 0}`
err = json.Unmarshal([]byte(data5), &data)
if err != nil {
t.Fatal(err)
} else if data.Number.Float64() != 0 {
t.Errorf("expecting %d, got %.2f", 0, data.Number)
}
data6 := `{"number": 123789}`
err = json.Unmarshal([]byte(data6), &data)
if err != nil {
t.Fatal(err)
} else if data.Number.Float64() != 123789 {
t.Errorf("expecting %d, got %.2f", 123789, data.Number)
}
data7 := `{"number": 12321312312312312}`
err = json.Unmarshal([]byte(data7), &data)
if err != nil {
t.Fatal(err)
} else if data.Number.Float64() != float64(12321312312312312) {
t.Errorf("expecting %.f, got %.2f", float64(12321312312312312), data.Number)
}
}
func TestUpdateAccountInfo(t *testing.T) {
t.Parallel()
sharedtestvalues.SkipTestIfCredentialsUnset(t, ku)

View File

@@ -11,6 +11,7 @@ import (
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-corp/gocryptotrader/types"
)
var (
@@ -810,15 +811,15 @@ type WsTicker struct {
Timestamp convert.ExchangeTime `json:"time"`
}
// WsSpotTicker represents a spot ticker push data.
type WsSpotTicker struct {
Sequence kucoinNumber `json:"sequence"`
Data WsSpotTickerDetail `json:"data"`
// WsSnapshot represents a spot ticker push data.
type WsSnapshot struct {
Sequence types.Number `json:"sequence"`
Data WsSnapshotDetail `json:"data"`
}
// WsSpotTickerDetail represents the detail of a spot ticker data.
// WsSnapshotDetail represents the detail of a spot ticker data.
// This represents all websocket ticker information pushed as a result of subscription to /market/snapshot:{symbol}, and /market/snapshot:{currency,market}
type WsSpotTickerDetail struct {
type WsSnapshotDetail struct {
AveragePrice float64 `json:"averagePrice"`
BaseCurrency string `json:"baseCurrency"`
Board int64 `json:"board"`
@@ -1070,8 +1071,8 @@ type WsFuturesTicker struct {
FilledSize float64 `json:"size"`
TradeID string `json:"tradeId"`
BestBidSize float64 `json:"bestBidSize"`
BestBidPrice kucoinNumber `json:"bestBidPrice"`
BestAskPrice kucoinNumber `json:"bestAskPrice"`
BestBidPrice types.Number `json:"bestBidPrice"`
BestAskPrice types.Number `json:"bestAskPrice"`
BestAskSize float64 `json:"bestAskSize"`
FilledTime convert.ExchangeTime `json:"ts"`
}
@@ -1112,8 +1113,8 @@ type WsOrderbookLevel5 struct {
type WsOrderbookLevel5Response struct {
Timestamp convert.ExchangeTime `json:"timestamp"`
Sequence int64 `json:"sequence"`
Bids [][2]kucoinNumber `json:"bids"`
Asks [][2]kucoinNumber `json:"asks"`
Bids [][2]types.Number `json:"bids"`
Asks [][2]types.Number `json:"asks"`
PushTimestamp convert.ExchangeTime `json:"ts"`
}

View File

@@ -888,7 +888,7 @@ func (ku *Kucoin) processOrderbook(respData []byte, symbol string) error {
}
func (ku *Kucoin) processMarketSnapshot(respData []byte) error {
response := WsSpotTicker{}
response := WsSnapshot{}
err := json.Unmarshal(respData, &response)
if err != nil {
return err

View File

@@ -48,42 +48,3 @@ func (o *okcoinTime) UnmarshalJSON(data []byte) error {
func (o *okcoinTime) Time() time.Time {
return time.Time(*o)
}
type okcoinNumber float64
// UnmarshalJSON a custom JSON deserialization function for numeric values to okcoinNumber instance.
func (a *okcoinNumber) UnmarshalJSON(data []byte) error {
var value interface{}
err := json.Unmarshal(data, &value)
if err != nil {
return err
}
switch val := value.(type) {
case string:
if val == "" {
*a = okcoinNumber(0)
return nil
}
floatValue, err := strconv.ParseFloat(val, 64)
if err != nil {
return err
}
*a = okcoinNumber(floatValue)
case float64:
*a = okcoinNumber(val)
case int64:
*a = okcoinNumber(val)
case int32:
*a = okcoinNumber(int64(val))
}
return nil
}
// Float64 returns a float64 value from okcoinNumber instance.
func (a okcoinNumber) Float64() float64 { return float64(a) }
// Int64 returns a int64 value from okcoinNumber instance.
func (a okcoinNumber) Int64() int64 { return int64(a) }
// String returns string wrapped float64 value from okcoinNumber instance.
func (a okcoinNumber) String() string { return strconv.FormatFloat(float64(a), 'f', -1, 64) }

View File

@@ -2,7 +2,6 @@ package okcoin
import (
"context"
"encoding/json"
"errors"
"log"
"os"
@@ -1768,27 +1767,6 @@ func (o *Okcoin) populateTradablePairs(ctx context.Context) error {
return nil
}
func TestOKCOINNumberUnmarshal(t *testing.T) {
type testNumberHolder struct {
Numb okcoinNumber `json:"numb"`
}
var val testNumberHolder
data1 := `{ "numb":"12345.65" }`
err := json.Unmarshal([]byte(data1), &val)
if err != nil {
t.Error(err)
} else if val.Numb.Float64() != 12345.65 {
t.Errorf("found %.2f, but found %.2f", val.Numb.Float64(), 12345.65)
}
data2 := `{ "numb":"" }`
err = json.Unmarshal([]byte(data2), &val)
if err != nil {
t.Error(err)
} else if val.Numb.Float64() != 0 {
t.Errorf("found %.2f, but found %d", val.Numb.Float64(), 0)
}
}
func TestGetSubAccounts(t *testing.T) {
t.Parallel()
sharedtestvalues.SkipTestIfCredentialsUnset(t, o)

View File

@@ -160,13 +160,13 @@ type WebsocketOrderbookResponse struct {
// WebsocketOrderBook holds orderbook data
type WebsocketOrderBook struct {
Checksum int64 `json:"checksum"`
Asks [][2]okcoinNumber `json:"asks"` // [ Price, Quantity, depreciated, number of orders at the price ]
Bids [][2]okcoinNumber `json:"bids"` // [ Price, Quantity, depreciated, number of orders at the price ]
Asks [][2]types.Number `json:"asks"` // [ Price, Quantity, depreciated, number of orders at the price ]
Bids [][2]types.Number `json:"bids"` // [ Price, Quantity, depreciated, number of orders at the price ]
Timestamp okcoinTime `json:"ts"`
}
func (a *WebsocketOrderBook) prepareOrderbook() {
asks := [][2]okcoinNumber{}
asks := [][2]types.Number{}
for x := range a.Asks {
if len(asks) > 0 && asks[len(asks)-1][0].Float64() == a.Asks[x][0].Float64() {
if a.Asks[x][1].Float64() != 0 {
@@ -180,7 +180,7 @@ func (a *WebsocketOrderBook) prepareOrderbook() {
asks = append(asks, a.Asks[x])
}
a.Asks = asks
bids := [][2]okcoinNumber{}
bids := [][2]types.Number{}
for x := range a.Bids {
if len(bids) > 0 && bids[len(bids)-1][0].Float64() == a.Bids[x][0].Float64() {
if a.Bids[x][1].Float64() != 0 {
@@ -248,7 +248,7 @@ type WebsocketAccount struct {
Data []struct {
AdjustedEquity string `json:"adjEq"`
Details []struct {
AvailableBalance okcoinNumber `json:"availBal"`
AvailableBalance types.Number `json:"availBal"`
AvailableEquity types.Number `json:"availEq"`
CashBalance types.Number `json:"cashBal"`
Currency string `json:"ccy"`
@@ -411,8 +411,8 @@ type WebsocketAdvancedAlgoOrder struct {
PushTime okcoinTime `json:"pTime"`
PosSide string `json:"posSide"`
PriceLimit types.Number `json:"pxLimit"`
PriceSpread okcoinNumber `json:"pxSpread"`
PriceVar okcoinNumber `json:"pxVar"`
PriceSpread types.Number `json:"pxSpread"`
PriceVar types.Number `json:"pxVar"`
Side string `json:"side"`
StopLossOrdPrice string `json:"slOrdPx"`
StopLossTriggerPrice string `json:"slTriggerPx"`
@@ -559,19 +559,19 @@ type Instrument struct {
Leverage types.Number `json:"lever"`
ListTime okcoinTime `json:"listTime"`
LotSize types.Number `json:"lotSz"`
MaxIcebergSz okcoinNumber `json:"maxIcebergSz"`
MaxLimitSize okcoinNumber `json:"maxLmtSz"`
MaxMarketSize okcoinNumber `json:"maxMktSz"`
MaxStopSize okcoinNumber `json:"maxStopSz"`
MaxTwapSize okcoinNumber `json:"maxTwapSz"`
MaxTriggerSize okcoinNumber `json:"maxTriggerSz"`
MinSize okcoinNumber `json:"minSz"` // Minimum order size
MaxIcebergSz types.Number `json:"maxIcebergSz"`
MaxLimitSize types.Number `json:"maxLmtSz"`
MaxMarketSize types.Number `json:"maxMktSz"`
MaxStopSize types.Number `json:"maxStopSz"`
MaxTwapSize types.Number `json:"maxTwapSz"`
MaxTriggerSize types.Number `json:"maxTriggerSz"`
MinSize types.Number `json:"minSz"` // Minimum order size
QuoteCurrency string `json:"quoteCcy"`
OptionType string `json:"optType"`
SettleCurrency string `json:"settleCcy"`
State string `json:"state"`
StrikePrice okcoinNumber `json:"stk"`
TickSize okcoinNumber `json:"tickSz"`
StrikePrice types.Number `json:"stk"`
TickSize types.Number `json:"tickSz"`
Underlying string `json:"uly"`
}
@@ -812,7 +812,7 @@ type WithdrawalRequest struct {
// WithdrawalResponse represents withdrawal of tokens response.
type WithdrawalResponse struct {
Amt okcoinNumber `json:"amt"`
Amt types.Number `json:"amt"`
WdID string `json:"wdId"`
Currency string `json:"ccy"`
ClientID string `json:"clientId"`
@@ -860,26 +860,26 @@ type WithdrawalOrderItem struct {
type AccountBalanceInformation struct {
AdjustedEquity string `json:"adjEq"` // Adjusted / Effective equity in USD . Not enabled. Please disregard.
Details []struct {
AvailableBalance okcoinNumber `json:"availBal"`
AvailableBalance types.Number `json:"availBal"`
AvailableEquity types.Number `json:"availEq"`
CashBalance types.Number `json:"cashBal"`
Currency string `json:"ccy"`
CrossLiability string `json:"crossLiab"`
DiscountEquity string `json:"disEq"`
Equity okcoinNumber `json:"eq"`
EquityUsd okcoinNumber `json:"eqUsd"`
FixedBalance okcoinNumber `json:"fixedBal"`
FrozenBalance okcoinNumber `json:"frozenBal"`
Interest okcoinNumber `json:"interest"`
IsolatedEquity okcoinNumber `json:"isoEq"`
IsolatedLiability okcoinNumber `json:"isoLiab"`
Equity types.Number `json:"eq"`
EquityUsd types.Number `json:"eqUsd"`
FixedBalance types.Number `json:"fixedBal"`
FrozenBalance types.Number `json:"frozenBal"`
Interest types.Number `json:"interest"`
IsolatedEquity types.Number `json:"isoEq"`
IsolatedLiability types.Number `json:"isoLiab"`
IsolatedUpl string `json:"isoUpl"` // Isolated unrealized profit and loss of the currency. Not enabled. Please disregard.
Liability okcoinNumber `json:"liab"`
MaxLoan okcoinNumber `json:"maxLoan"`
MarginRatio okcoinNumber `json:"mgnRatio"`
NotionalLever okcoinNumber `json:"notionalLever"`
OrderFrozen okcoinNumber `json:"ordFrozen"`
SpotInUseAmount okcoinNumber `json:"spotInUseAmt"`
Liability types.Number `json:"liab"`
MaxLoan types.Number `json:"maxLoan"`
MarginRatio types.Number `json:"mgnRatio"`
NotionalLever types.Number `json:"notionalLever"`
OrderFrozen types.Number `json:"ordFrozen"`
SpotInUseAmount types.Number `json:"spotInUseAmt"`
StrategyEquity string `json:"stgyEq"`
Twap string `json:"twap"`
UpdateTime okcoinTime `json:"uTime"`
@@ -888,7 +888,7 @@ type AccountBalanceInformation struct {
} `json:"details"`
IMR string `json:"imr"` // Frozen equity for open positions and pending orders in USD.
IsolatedEquity string `json:"isoEq"`
MarginRatio okcoinNumber `json:"mgnRatio"`
MarginRatio types.Number `json:"mgnRatio"`
Mmr string `json:"mmr"` // Maintenance margin requirement in USD.
NotionalUsd types.Number `json:"notionalUsd"`
OrdFroz string `json:"ordFroz"`
@@ -903,7 +903,7 @@ type BillsDetail struct {
BillID string `json:"billId"`
Currency string `json:"ccy"`
ExecType string `json:"execType"`
Fee okcoinNumber `json:"fee"`
Fee types.Number `json:"fee"`
From string `json:"from"`
InstrumentID string `json:"instId"`
InstrumentType string `json:"instType"`
@@ -979,11 +979,11 @@ type AvailableRFQPair struct {
Instruments []struct {
BaseCurrency string `json:"baseCcy"`
BaseCurrencyIcon string `json:"baseCcyIcon"`
BaseSingleMin okcoinNumber `json:"baseSingleMin"`
BaseSingleMin types.Number `json:"baseSingleMin"`
InstrumentID string `json:"instId"`
QuoteCurrency string `json:"quoteCcy"`
QuoteCurrencyIcon string `json:"quoteCcyIcon"`
QuoteSingleMin okcoinNumber `json:"quoteSingleMin"`
QuoteSingleMin types.Number `json:"quoteSingleMin"`
} `json:"instruments"`
Timestamp okcoinTime `json:"ts"`
}
@@ -1151,11 +1151,11 @@ type ChannelInfo struct {
ChannelID string `json:"chanId"`
Currency string `json:"ccy"`
DepositQuota string `json:"depQuota"`
MinDeposit okcoinNumber `json:"minDep"`
WithdrawalQuota okcoinNumber `json:"wdQuota"`
MinWithdrawal okcoinNumber `json:"minWd"`
UsedWithdrawalQuota okcoinNumber `json:"usedWdQuota"`
ValidWithdrawalQuota okcoinNumber `json:"validWdQuota"`
MinDeposit types.Number `json:"minDep"`
WithdrawalQuota types.Number `json:"wdQuota"`
MinWithdrawal types.Number `json:"minWd"`
UsedWithdrawalQuota types.Number `json:"usedWdQuota"`
ValidWithdrawalQuota types.Number `json:"validWdQuota"`
BankAccountInfo []struct {
BankAccountName string `json:"bankAcctName"`
BankAccountNumber string `json:"bankAcctNum"`
@@ -1237,25 +1237,25 @@ type TradeOrder struct {
Category string `json:"category"`
Currency string `json:"ccy"`
ClientOrdID string `json:"clOrdId"`
Fee okcoinNumber `json:"fee"`
Fee types.Number `json:"fee"`
FeeCurrency string `json:"feeCcy"`
FillPrice types.Number `json:"fillPx"`
FillSize types.Number `json:"fillSz"`
FillTime okcoinTime `json:"fillTime"`
InstrumentID string `json:"instId"`
InstrumentType string `json:"instType"`
Leverage okcoinNumber `json:"lever"`
Leverage types.Number `json:"lever"`
OrderID string `json:"ordId"`
OrderType string `json:"ordType"`
ProfitAndLoss types.Number `json:"pnl"`
PosSide string `json:"posSide"`
Price types.Number `json:"px"`
Rebate okcoinNumber `json:"rebate"`
Rebate types.Number `json:"rebate"`
RebateCurrency string `json:"rebateCcy"`
ReduceOnly bool `json:"reduceOnly,string"`
Side string `json:"side"`
StopLossOrdPrice okcoinNumber `json:"slOrdPx"`
StopLossTriggerPrice okcoinNumber `json:"slTriggerPx"`
StopLossOrdPrice types.Number `json:"slOrdPx"`
StopLossTriggerPrice types.Number `json:"slTriggerPx"`
StopLossTriggerPriceType string `json:"slTriggerPxType"`
Source string `json:"source"`
State string `json:"state"`
@@ -1263,8 +1263,8 @@ type TradeOrder struct {
Tag string `json:"tag"`
TradeMode string `json:"tdMode"`
TargetCurrency string `json:"tgtCcy"`
TakeProfitOrderPrice okcoinNumber `json:"tpOrdPx"`
TakeProfitTriggerPrice okcoinNumber `json:"tpTriggerPx"`
TakeProfitOrderPrice types.Number `json:"tpOrdPx"`
TakeProfitTriggerPrice types.Number `json:"tpTriggerPx"`
TakeProfitTriggerPriceType string `json:"tpTriggerPxType"`
TradeID string `json:"tradeId"`
UpdateTime okcoinTime `json:"uTime"`
@@ -1285,7 +1285,7 @@ type TransactionFillItem struct {
PosSide string `json:"posSide"`
ExecType string `json:"execType"`
FeeCurrency string `json:"feeCcy"`
Fee okcoinNumber `json:"fee"`
Fee types.Number `json:"fee"`
Timestamp okcoinTime `json:"ts"`
}
@@ -1341,42 +1341,42 @@ type CancelAlgoOrderRequestParam struct {
// AlgoOrderDetail represents an algo-order detailed information
type AlgoOrderDetail struct {
ActivePrice okcoinNumber `json:"activePx"`
ActualPrice okcoinNumber `json:"actualPx"`
ActivePrice types.Number `json:"activePx"`
ActualPrice types.Number `json:"actualPx"`
ActualSide string `json:"actualSide"`
ActualSize okcoinNumber `json:"actualSz"`
ActualSize types.Number `json:"actualSz"`
AlgoID string `json:"algoId"`
CreateTime okcoinTime `json:"cTime"`
CallbackRatio okcoinNumber `json:"callbackRatio"`
CallbackRatio types.Number `json:"callbackRatio"`
CallbackSpread string `json:"callbackSpread"`
Currency string `json:"ccy"`
ClientOrderID string `json:"clOrdId"`
InstrumentID string `json:"instId"`
InstrumentType string `json:"instType"`
Leverage types.Number `json:"lever"`
MoveTriggerPrice okcoinNumber `json:"moveTriggerPx"`
MoveTriggerPrice types.Number `json:"moveTriggerPx"`
OrderID string `json:"ordId"`
OrdPrice okcoinNumber `json:"ordPx"`
OrdPrice types.Number `json:"ordPx"`
OrderType string `json:"ordType"`
PosSide string `json:"posSide"`
PriceLimit okcoinNumber `json:"pxLimit"`
PriceSpread okcoinNumber `json:"pxSpread"`
PriceVar okcoinNumber `json:"pxVar"`
PriceLimit types.Number `json:"pxLimit"`
PriceSpread types.Number `json:"pxSpread"`
PriceVar types.Number `json:"pxVar"`
Side string `json:"side"`
StopLossOrdPrice okcoinNumber `json:"slOrdPx"`
StopLossTriggerPrice okcoinNumber `json:"slTriggerPx"`
StopLossOrdPrice types.Number `json:"slOrdPx"`
StopLossTriggerPrice types.Number `json:"slTriggerPx"`
StopLossTriggerPriceType string `json:"slTriggerPxType"`
State string `json:"state"`
Size okcoinNumber `json:"sz"`
SizeLimit okcoinNumber `json:"szLimit"`
Size types.Number `json:"sz"`
SizeLimit types.Number `json:"szLimit"`
Tag string `json:"tag"`
TdMode string `json:"tdMode"`
TgtCcy string `json:"tgtCcy"`
TimeInterval string `json:"timeInterval"`
TpOrdPrice okcoinNumber `json:"tpOrdPx"`
TpTriggerPrice okcoinNumber `json:"tpTriggerPx"`
TpOrdPrice types.Number `json:"tpOrdPx"`
TpTriggerPrice types.Number `json:"tpTriggerPx"`
TpTriggerPriceType string `json:"tpTriggerPxType"`
TriggerPrice okcoinNumber `json:"triggerPx"`
TriggerPrice types.Number `json:"triggerPx"`
TriggerPriceType string `json:"triggerPxType"`
TriggerTime okcoinTime `json:"triggerTime"`
}

View File

@@ -24,6 +24,7 @@ import (
"github.com/thrasher-corp/gocryptotrader/exchanges/ticker"
"github.com/thrasher-corp/gocryptotrader/exchanges/trade"
"github.com/thrasher-corp/gocryptotrader/log"
"github.com/thrasher-corp/gocryptotrader/types"
)
const (
@@ -695,7 +696,7 @@ func (o *Okcoin) wsProcessCandles(respRaw []byte) error {
// AppendWsOrderbookItems adds websocket orderbook data bid/asks into an
// orderbook item array
func (o *Okcoin) AppendWsOrderbookItems(entries [][2]okcoinNumber) ([]orderbook.Item, error) {
func (o *Okcoin) AppendWsOrderbookItems(entries [][2]types.Number) ([]orderbook.Item, error) {
items := make([]orderbook.Item, len(entries))
for j := range entries {
amount := entries[j][1].Float64()

View File

@@ -9,35 +9,6 @@ import (
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
)
type okxNumericalValue float64
// UnmarshalJSON is custom type json unmarshaller for okxNumericalValue
func (a *okxNumericalValue) UnmarshalJSON(data []byte) error {
var num interface{}
err := json.Unmarshal(data, &num)
if err != nil {
return err
}
switch d := num.(type) {
case float64:
*a = okxNumericalValue(d)
case string:
if d == "" {
return nil
}
convNum, err := strconv.ParseFloat(d, 64)
if err != nil {
return err
}
*a = okxNumericalValue(convNum)
}
return nil
}
// Float64 returns a float64 value for okxNumericalValue
func (a *okxNumericalValue) Float64() float64 { return float64(*a) }
type okxUnixMilliTime int64
// UnmarshalJSON deserializes byte data to okxunixMilliTime instance.

View File

@@ -76,19 +76,19 @@ var testNetVal = testNetKey("testnet")
// TickerResponse represents the market data endpoint ticker detail
type TickerResponse struct {
InstrumentType string `json:"instType"`
InstrumentID string `json:"instId"`
LastTradePrice okxNumericalValue `json:"last"`
LastTradeSize okxNumericalValue `json:"lastSz"`
BestAskPrice okxNumericalValue `json:"askPx"`
BestAskSize okxNumericalValue `json:"askSz"`
BestBidPrice okxNumericalValue `json:"bidPx"`
BestBidSize okxNumericalValue `json:"bidSz"`
Open24H okxNumericalValue `json:"open24h"`
High24H okxNumericalValue `json:"high24h"`
Low24H okxNumericalValue `json:"low24h"`
VolCcy24H okxNumericalValue `json:"volCcy24h"`
Vol24H okxNumericalValue `json:"vol24h"`
InstrumentType string `json:"instType"`
InstrumentID string `json:"instId"`
LastTradePrice types.Number `json:"last"`
LastTradeSize types.Number `json:"lastSz"`
BestAskPrice types.Number `json:"askPx"`
BestAskSize types.Number `json:"askSz"`
BestBidPrice types.Number `json:"bidPx"`
BestBidSize types.Number `json:"bidSz"`
Open24H types.Number `json:"open24h"`
High24H types.Number `json:"high24h"`
Low24H types.Number `json:"low24h"`
VolCcy24H types.Number `json:"volCcy24h"`
Vol24H types.Number `json:"vol24h"`
OpenPriceInUTC0 string `json:"sodUtc0"`
OpenPriceInUTC8 string `json:"sodUtc8"`
@@ -237,11 +237,11 @@ type TradeResponse struct {
// TradingVolumeIn24HR response model.
type TradingVolumeIn24HR struct {
BlockVolumeInCNY okxNumericalValue `json:"blockVolCny"`
BlockVolumeInUSD okxNumericalValue `json:"blockVolUsd"`
TradingVolumeInUSD types.Number `json:"volUsd"`
TradingVolumeInCny types.Number `json:"volCny"`
Timestamp okxUnixMilliTime `json:"ts"`
BlockVolumeInCNY types.Number `json:"blockVolCny"`
BlockVolumeInUSD types.Number `json:"blockVolUsd"`
TradingVolumeInUSD types.Number `json:"volUsd"`
TradingVolumeInCny types.Number `json:"volCny"`
Timestamp okxUnixMilliTime `json:"ts"`
}
// OracleSmartContractResponse returns the crypto price of signing using Open Oracle smart contract.
@@ -395,9 +395,9 @@ type DiscountRate struct {
// DiscountRateInfoItem represents discount info list item for discount rate response
type DiscountRateInfoItem struct {
DiscountRate string `json:"discountRate"`
MaxAmount okxNumericalValue `json:"maxAmt"`
MinAmount okxNumericalValue `json:"minAmt"`
DiscountRate string `json:"discountRate"`
MaxAmount types.Number `json:"maxAmt"`
MinAmount types.Number `json:"minAmt"`
}
// ServerTime returning the server time instance.
@@ -658,42 +658,42 @@ type OrderDetailRequestParam struct {
// OrderDetail returns a order detail information
type OrderDetail struct {
InstrumentType string `json:"instType"`
InstrumentID string `json:"instId"`
Currency string `json:"ccy"`
OrderID string `json:"ordId"`
ClientOrderID string `json:"clOrdId"`
Tag string `json:"tag"`
ProfitAndLoss string `json:"pnl"`
OrderType string `json:"ordType"`
Side order.Side `json:"side"`
PositionSide string `json:"posSide"`
TradeMode string `json:"tdMode"`
TradeID string `json:"tradeId"`
FillTime time.Time `json:"fillTime"`
Source string `json:"source"`
State string `json:"state"`
TakeProfitTriggerPriceType string `json:"tpTriggerPxType"`
StopLossTriggerPriceType string `json:"slTriggerPxType"`
StopLossOrdPx string `json:"slOrdPx"`
RebateCurrency string `json:"rebateCcy"`
QuantityType string `json:"tgtCcy"` // base_ccy and quote_ccy
Category string `json:"category"` // normal, twap, adl, full_liquidation, partial_liquidation, delivery, ddh
AccumulatedFillSize okxNumericalValue `json:"accFillSz"`
FillPrice okxNumericalValue `json:"fillPx"`
FillSize okxNumericalValue `json:"fillSz"`
RebateAmount okxNumericalValue `json:"rebate"`
FeeCurrency string `json:"feeCcy"`
TransactionFee okxNumericalValue `json:"fee"`
AveragePrice okxNumericalValue `json:"avgPx"`
Leverage okxNumericalValue `json:"lever"`
Price okxNumericalValue `json:"px"`
Size okxNumericalValue `json:"sz"`
TakeProfitTriggerPrice okxNumericalValue `json:"tpTriggerPx"`
TakeProfitOrderPrice okxNumericalValue `json:"tpOrdPx"`
StopLossTriggerPrice okxNumericalValue `json:"slTriggerPx"`
UpdateTime time.Time `json:"uTime"`
CreationTime time.Time `json:"cTime"`
InstrumentType string `json:"instType"`
InstrumentID string `json:"instId"`
Currency string `json:"ccy"`
OrderID string `json:"ordId"`
ClientOrderID string `json:"clOrdId"`
Tag string `json:"tag"`
ProfitAndLoss string `json:"pnl"`
OrderType string `json:"ordType"`
Side order.Side `json:"side"`
PositionSide string `json:"posSide"`
TradeMode string `json:"tdMode"`
TradeID string `json:"tradeId"`
FillTime time.Time `json:"fillTime"`
Source string `json:"source"`
State string `json:"state"`
TakeProfitTriggerPriceType string `json:"tpTriggerPxType"`
StopLossTriggerPriceType string `json:"slTriggerPxType"`
StopLossOrdPx string `json:"slOrdPx"`
RebateCurrency string `json:"rebateCcy"`
QuantityType string `json:"tgtCcy"` // base_ccy and quote_ccy
Category string `json:"category"` // normal, twap, adl, full_liquidation, partial_liquidation, delivery, ddh
AccumulatedFillSize types.Number `json:"accFillSz"`
FillPrice types.Number `json:"fillPx"`
FillSize types.Number `json:"fillSz"`
RebateAmount types.Number `json:"rebate"`
FeeCurrency string `json:"feeCcy"`
TransactionFee types.Number `json:"fee"`
AveragePrice types.Number `json:"avgPx"`
Leverage types.Number `json:"lever"`
Price types.Number `json:"px"`
Size types.Number `json:"sz"`
TakeProfitTriggerPrice types.Number `json:"tpTriggerPx"`
TakeProfitOrderPrice types.Number `json:"tpOrdPx"`
StopLossTriggerPrice types.Number `json:"slTriggerPx"`
UpdateTime time.Time `json:"uTime"`
CreationTime time.Time `json:"cTime"`
}
// OrderListRequestParams represents order list requesting parameters.
@@ -1118,12 +1118,12 @@ type LendingHistory struct {
// PublicBorrowInfo holds a currency's borrow info.
type PublicBorrowInfo struct {
Currency string `json:"ccy"`
AverageAmount okxNumericalValue `json:"avgAmt"`
AverageAmountUSD okxNumericalValue `json:"avgAmtUsd"`
AverageRate okxNumericalValue `json:"avgRate"`
PreviousRate okxNumericalValue `json:"preRate"`
EstimatedRate okxNumericalValue `json:"estRate"`
Currency string `json:"ccy"`
AverageAmount types.Number `json:"avgAmt"`
AverageAmountUSD types.Number `json:"avgAmtUsd"`
AverageRate types.Number `json:"avgRate"`
PreviousRate types.Number `json:"preRate"`
EstimatedRate types.Number `json:"estRate"`
}
// PublicBorrowHistory holds a currencies borrow history.
@@ -1136,9 +1136,9 @@ type PublicBorrowHistory struct {
// ConvertCurrency represents currency conversion detailed data.
type ConvertCurrency struct {
Currency string `json:"currency"`
Min okxNumericalValue `json:"min"`
Max okxNumericalValue `json:"max"`
Currency string `json:"currency"`
Min types.Number `json:"min"`
Max types.Number `json:"max"`
}
// ConvertCurrencyPair holds information related to conversion between two pairs.
@@ -1224,16 +1224,16 @@ type ConvertHistory struct {
// Account holds currency account balance and related information
type Account struct {
AdjEq okxNumericalValue `json:"adjEq"`
Details []AccountDetail `json:"details"`
Imr okxNumericalValue `json:"imr"` // Frozen equity for open positions and pending orders in USD level Applicable to Multi-currency margin and Portfolio margin
IsoEq okxNumericalValue `json:"isoEq"`
MgnRatio okxNumericalValue `json:"mgnRatio"`
Mmr okxNumericalValue `json:"mmr"` // Maintenance margin requirement in USD level Applicable to Multi-currency margin and Portfolio margin
NotionalUsd okxNumericalValue `json:"notionalUsd"`
OrdFroz okxNumericalValue `json:"ordFroz"` // Margin frozen for pending orders in USD level Applicable to Multi-currency margin and Portfolio margin
TotalEquity okxNumericalValue `json:"totalEq"` // Total Equity in USD level
UpdateTime okxUnixMilliTime `json:"uTime"` // UpdateTime
AdjEq types.Number `json:"adjEq"`
Details []AccountDetail `json:"details"`
Imr types.Number `json:"imr"` // Frozen equity for open positions and pending orders in USD level Applicable to Multi-currency margin and Portfolio margin
IsoEq types.Number `json:"isoEq"`
MgnRatio types.Number `json:"mgnRatio"`
Mmr types.Number `json:"mmr"` // Maintenance margin requirement in USD level Applicable to Multi-currency margin and Portfolio margin
NotionalUsd types.Number `json:"notionalUsd"`
OrdFroz types.Number `json:"ordFroz"` // Margin frozen for pending orders in USD level Applicable to Multi-currency margin and Portfolio margin
TotalEquity types.Number `json:"totalEq"` // Total Equity in USD level
UpdateTime okxUnixMilliTime `json:"uTime"` // UpdateTime
}
// AccountDetail account detail information.
@@ -1380,26 +1380,26 @@ type BillsDetailQueryParameter struct {
// BillsDetailResponse represents account bills information.
type BillsDetailResponse struct {
Balance okxNumericalValue `json:"bal"`
BalanceChange string `json:"balChg"`
BillID string `json:"billId"`
Currency string `json:"ccy"`
ExecType string `json:"execType"` // Order flow type, Ttaker Mmaker
Fee types.Number `json:"fee"` // Fee Negative number represents the user transaction fee charged by the platform. Positive number represents rebate.
From string `json:"from"` // The remitting account 6: FUNDING 18: Trading account When bill type is not transfer, the field returns "".
InstrumentID string `json:"instId"`
InstrumentType asset.Item `json:"instType"`
MarginMode string `json:"mgnMode"`
Notes string `json:"notes"` // notes When bill type is not transfer, the field returns "".
OrderID string `json:"ordId"`
ProfitAndLoss types.Number `json:"pnl"`
PositionLevelBalance types.Number `json:"posBal"`
PositionLevelBalanceChange types.Number `json:"posBalChg"`
SubType string `json:"subType"`
Size types.Number `json:"sz"`
To string `json:"to"`
Timestamp okxUnixMilliTime `json:"ts"`
Type string `json:"type"`
Balance types.Number `json:"bal"`
BalanceChange string `json:"balChg"`
BillID string `json:"billId"`
Currency string `json:"ccy"`
ExecType string `json:"execType"` // Order flow type, Ttaker Mmaker
Fee types.Number `json:"fee"` // Fee Negative number represents the user transaction fee charged by the platform. Positive number represents rebate.
From string `json:"from"` // The remitting account 6: FUNDING 18: Trading account When bill type is not transfer, the field returns "".
InstrumentID string `json:"instId"`
InstrumentType asset.Item `json:"instType"`
MarginMode string `json:"mgnMode"`
Notes string `json:"notes"` // notes When bill type is not transfer, the field returns "".
OrderID string `json:"ordId"`
ProfitAndLoss types.Number `json:"pnl"`
PositionLevelBalance types.Number `json:"posBal"`
PositionLevelBalanceChange types.Number `json:"posBalChg"`
SubType string `json:"subType"`
Size types.Number `json:"sz"`
To string `json:"to"`
Timestamp okxUnixMilliTime `json:"ts"`
Type string `json:"type"`
}
// AccountConfigurationResponse represents account configuration response.
@@ -1431,10 +1431,10 @@ type SetLeverageInput struct {
// SetLeverageResponse represents set leverage response
type SetLeverageResponse struct {
Leverage okxNumericalValue `json:"lever"`
MarginMode string `json:"mgnMode"` // Margin Mode "cross" and "isolated"
InstrumentID string `json:"instId"`
PositionSide string `json:"posSide"` // "long", "short", and "net"
Leverage types.Number `json:"lever"`
MarginMode string `json:"mgnMode"` // Margin Mode "cross" and "isolated"
InstrumentID string `json:"instId"`
PositionSide string `json:"posSide"` // "long", "short", and "net"
}
// MaximumBuyAndSell get maximum buy , sell amount or open amount
@@ -1465,20 +1465,20 @@ type IncreaseDecreaseMarginInput struct {
// IncreaseDecreaseMargin represents increase or decrease the margin of the isolated position response
type IncreaseDecreaseMargin struct {
Amount okxNumericalValue `json:"amt"`
Ccy string `json:"ccy"`
InstrumentID string `json:"instId"`
Leverage okxNumericalValue `json:"leverage"`
PosSide string `json:"posSide"`
Type string `json:"type"`
Amount types.Number `json:"amt"`
Ccy string `json:"ccy"`
InstrumentID string `json:"instId"`
Leverage types.Number `json:"leverage"`
PosSide string `json:"posSide"`
Type string `json:"type"`
}
// LeverageResponse instrument id leverage response.
type LeverageResponse struct {
InstrumentID string `json:"instId"`
MarginMode string `json:"mgnMode"`
PositionSide string `json:"posSide"`
Leverage okxNumericalValue `json:"lever"`
InstrumentID string `json:"instId"`
MarginMode string `json:"mgnMode"`
PositionSide string `json:"posSide"`
Leverage types.Number `json:"lever"`
}
// MaximumLoanInstrument represents maximum loan of an instrument id.
@@ -2991,13 +2991,13 @@ type TradeOneClickRepayParam struct {
// CurrencyOneClickRepay represents one click repay currency
type CurrencyOneClickRepay struct {
DebtCurrency string `json:"debtCcy"`
FillFromSize okxNumericalValue `json:"fillFromSz"`
FillRepaySize okxNumericalValue `json:"fillRepaySz"`
FillToSize types.Number `json:"fillToSz"`
RepayCurrency string `json:"repayCcy"`
Status string `json:"status"`
UpdateTime time.Time `json:"uTime"`
DebtCurrency string `json:"debtCcy"`
FillFromSize types.Number `json:"fillFromSz"`
FillRepaySize types.Number `json:"fillRepaySz"`
FillToSize types.Number `json:"fillToSz"`
RepayCurrency string `json:"repayCcy"`
Status string `json:"status"`
UpdateTime time.Time `json:"uTime"`
}
// SetQuoteProductParam represents set quote product request param
@@ -3084,7 +3084,7 @@ type Offer struct {
ProtocolType string `json:"protocolType"`
EarningCcy []string `json:"earningCcy"`
Term string `json:"term"`
Apy okxNumericalValue `json:"apy"`
Apy types.Number `json:"apy"`
EarlyRedeem bool `json:"earlyRedeem"`
InvestData []OfferInvestData `json:"investData"`
EarningData []struct {
@@ -3095,10 +3095,10 @@ type Offer struct {
// OfferInvestData represents currencies invest data information for an offer
type OfferInvestData struct {
Currency string `json:"ccy"`
Balance okxNumericalValue `json:"bal"`
MinimumAmount okxNumericalValue `json:"minAmt"`
MaximumAmount okxNumericalValue `json:"maxAmt"`
Currency string `json:"ccy"`
Balance types.Number `json:"bal"`
MinimumAmount types.Number `json:"minAmt"`
MaximumAmount types.Number `json:"maxAmt"`
}
// PurchaseRequestParam represents purchase request param specific product

View File

@@ -71,3 +71,8 @@ func (f Number) Int64() int64 {
func (f Number) Decimal() decimal.Decimal {
return decimal.NewFromFloat(float64(f))
}
// String returns a string representation of the number
func (f Number) String() string {
return strconv.FormatFloat(float64(f), 'f', -1, 64)
}