Types: Switch convert.StringToFloat64 to types.Number (#1415)

* Types: Add Number type

* Types: Switch StringToFloat64 for Number

This change mostly just renames the type.
convert package and StringToFloat64 represent actions, not types,
and make it misleading to use outside of the API context,
especially when using it for a Float64ToString operation.

* Common: Remove StringToFloat64

Replaced by types.Number

* fixup! Types: Switch StringToFloat64 for Number

Second pass at Okx

* Spellcheck: Fix whitespace handling for okx line
This commit is contained in:
Gareth Kirwan
2023-12-20 03:01:27 +01:00
committed by GitHub
parent 5042bf9790
commit f05f24da8b
21 changed files with 3158 additions and 3140 deletions

View File

@@ -1,9 +1,7 @@
package convert
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
"strconv"
@@ -13,10 +11,6 @@ import (
"github.com/shopspring/decimal"
)
const jsonStringIdent = `"` // immutable byte sequence
var errUnhandledType = errors.New("unhandled type")
// FloatFromString format
func FloatFromString(raw interface{}) (float64, error) {
str, ok := raw.(string)
@@ -195,55 +189,6 @@ func InterfaceToStringOrZeroValue(r interface{}) string {
return ""
}
// StringToFloat64 is a float64 that unmarshals from a string. This is useful
// for APIs that return numbers as strings and return an empty string instead of
// 0.
type StringToFloat64 float64
// UnmarshalJSON implements the json.Unmarshaler interface.
// This implementation is slightly more performant than calling json.Unmarshal
// again.
func (f *StringToFloat64) UnmarshalJSON(data []byte) error {
if !bytes.HasPrefix(data, []byte(jsonStringIdent)) {
return fmt.Errorf("%w: %s", errUnhandledType, string(data))
}
data = data[1 : len(data)-1] // Remove quotes
if len(data) == 0 {
*f = StringToFloat64(0)
return nil
}
val, err := strconv.ParseFloat(string(data), 64)
if err != nil {
return err
}
*f = StringToFloat64(val)
return nil
}
// MarshalJSON implements the json.Marshaler interface.
func (f StringToFloat64) MarshalJSON() ([]byte, error) {
if f == 0 {
return []byte(jsonStringIdent + jsonStringIdent), nil
}
val := strconv.FormatFloat(float64(f), 'f', -1, 64)
return []byte(jsonStringIdent + val + jsonStringIdent), nil
}
// Float64 returns the float64 value of the FloatString.
func (f StringToFloat64) Float64() float64 {
return float64(f)
}
// Decimal returns the decimal value of the FloatString
// Warning: this does not handle big numbers as the underlying
// is still a float
func (f StringToFloat64) Decimal() decimal.Decimal {
return decimal.NewFromFloat(float64(f))
}
// ExchangeTime provides timestamp to time conversion method.
type ExchangeTime time.Time

View File

@@ -2,7 +2,6 @@ package convert
import (
"encoding/json"
"errors"
"strings"
"testing"
"time"
@@ -318,89 +317,6 @@ func TestInterfaceToStringOrZeroValue(t *testing.T) {
}
}
func TestStringToFloat64(t *testing.T) {
t.Parallel()
resp := struct {
Data StringToFloat64 `json:"data"`
}{}
err := json.Unmarshal([]byte(`{"data":"0.00000001"}`), &resp)
if err != nil {
t.Fatal(err)
}
if resp.Data.Float64() != 1e-8 {
t.Fatalf("expected 1e-8, got %v", resp.Data.Float64())
}
err = json.Unmarshal([]byte(`{"data":""}`), &resp)
if err != nil {
t.Fatal(err)
}
err = json.Unmarshal([]byte(`{"data":1337.37}`), &resp)
if !errors.Is(err, errUnhandledType) {
t.Fatalf("received %v but expected %v", err, errUnhandledType)
}
// Demonstrates that a suffix check is not needed.
err = json.Unmarshal([]byte(`{"data":"1337.37}`), &resp)
if err == nil {
t.Fatal("error cannot be nil")
}
err = json.Unmarshal([]byte(`{"data":"MEOW"}`), &resp)
if err == nil {
t.Fatal("error cannot be nil")
}
data, err := json.Marshal(StringToFloat64(0))
if err != nil {
t.Fatal(err)
}
if string(data) != `""` {
t.Fatalf("expected empty string, got %v", string(data))
}
data, err = json.Marshal(StringToFloat64(1337.1337))
if err != nil {
t.Fatal(err)
}
if string(data) != `"1337.1337"` {
t.Fatalf("expected \"1337.1337\" string, got %v", string(data))
}
}
func TestStringToFloat64Decimal(t *testing.T) {
t.Parallel()
resp := struct {
Data StringToFloat64 `json:"data"`
}{}
err := json.Unmarshal([]byte(`{"data":"0.00000001"}`), &resp)
if err != nil {
t.Fatal(err)
}
if !resp.Data.Decimal().Equal(decimal.NewFromFloat(0.00000001)) {
t.Errorf("received '%v' expected '%v'", resp.Data.Decimal(), 0.00000001)
}
}
// 2677173 428.9 ns/op 240 B/op 5 allocs/op
func BenchmarkStringToFloat64(b *testing.B) {
resp := struct {
Data StringToFloat64 `json:"data"`
}{}
for i := 0; i < b.N; i++ {
err := json.Unmarshal([]byte(`{"data":"0.00000001"}`), &resp)
if err != nil {
b.Fatal(err)
}
}
}
func TestExchangeTimeUnmarshalJSON(t *testing.T) {
t.Parallel()
unmarshaledResult := &struct {

View File

@@ -5,7 +5,6 @@
if errOt != nil {
return order.Detail{}, fmt.Errorf("error parsing order type: %s", errOt)
currency.CANN: 0.2,
InstrumentID string `json:"insId"`
currency.DOTA: 0.01,
currency.SCRPT: 0.01,
currency.NOO: 0.002,
@@ -22,4 +21,3 @@
currency.MIS: 0.002,
SHFT = NewCode("SHFT")
currency.SHFT: 84,
InstrumentID string `json:"insId"`

View File

@@ -3,4 +3,5 @@ datas
prevend
flate
freez
zar
zar
insid

View File

@@ -5,9 +5,9 @@ import (
"time"
"github.com/shopspring/decimal"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/types"
)
const wsRateLimitMilliseconds = 250
@@ -295,14 +295,14 @@ type AggregatedTrade struct {
// IndexMarkPrice stores data for index and mark prices
type IndexMarkPrice struct {
Symbol string `json:"symbol"`
Pair string `json:"pair"`
MarkPrice convert.StringToFloat64 `json:"markPrice"`
IndexPrice convert.StringToFloat64 `json:"indexPrice"`
EstimatedSettlePrice convert.StringToFloat64 `json:"estimatedSettlePrice"`
LastFundingRate convert.StringToFloat64 `json:"lastFundingRate"`
NextFundingTime int64 `json:"nextFundingTime"`
Time int64 `json:"time"`
Symbol string `json:"symbol"`
Pair string `json:"pair"`
MarkPrice types.Number `json:"markPrice"`
IndexPrice types.Number `json:"indexPrice"`
EstimatedSettlePrice types.Number `json:"estimatedSettlePrice"`
LastFundingRate types.Number `json:"lastFundingRate"`
NextFundingTime int64 `json:"nextFundingTime"`
Time int64 `json:"time"`
}
// CandleStick holds kline data

View File

@@ -3,8 +3,8 @@ package binance
import (
"time"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/types"
)
var (
@@ -84,11 +84,11 @@ type UMarkPrice struct {
// FundingRateInfoResponse stores funding rate info
type FundingRateInfoResponse struct {
Symbol string `json:"symbol"`
AdjustedFundingRateCap convert.StringToFloat64 `json:"adjustedFundingRateCap"`
AdjustedFundingRateFloor convert.StringToFloat64 `json:"adjustedFundingRateFloor"`
FundingIntervalHours int64 `json:"fundingIntervalHours"`
Disclaimer bool `json:"disclaimer"`
Symbol string `json:"symbol"`
AdjustedFundingRateCap types.Number `json:"adjustedFundingRateCap"`
AdjustedFundingRateFloor types.Number `json:"adjustedFundingRateFloor"`
FundingIntervalHours int64 `json:"fundingIntervalHours"`
Disclaimer bool `json:"disclaimer"`
}
// FundingRateHistory stores funding rate history

View File

@@ -14,12 +14,12 @@ import (
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/common/crypto"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
"github.com/thrasher-corp/gocryptotrader/types"
)
// Bybit is the overarching type across this package
@@ -164,10 +164,10 @@ func (by *Bybit) GetMergedOrderBook(ctx context.Context, symbol string, scale, d
func (by *Bybit) GetTrades(ctx context.Context, symbol string, limit int64) ([]TradeItem, error) {
resp := struct {
Data []struct {
Price convert.StringToFloat64 `json:"price"`
Time bybitTimeMilliSec `json:"time"`
Quantity convert.StringToFloat64 `json:"qty"`
IsBuyerMaker bool `json:"isBuyerMaker"`
Price types.Number `json:"price"`
Time bybitTimeMilliSec `json:"time"`
Quantity types.Number `json:"qty"`
IsBuyerMaker bool `json:"isBuyerMaker"`
} `json:"result"`
Error
}{}

View File

@@ -10,11 +10,11 @@ import (
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-corp/gocryptotrader/types"
)
const (
@@ -394,7 +394,7 @@ func (by *Bybit) GetLastFundingRate(ctx context.Context, symbol currency.Pair) (
// GetFuturesServerTime returns Bybit server time in seconds
func (by *Bybit) GetFuturesServerTime(ctx context.Context) (time.Time, error) {
resp := struct {
TimeNow convert.StringToFloat64 `json:"time_now"`
TimeNow types.Number `json:"time_now"`
Error
}{}

View File

@@ -3480,7 +3480,7 @@ func TestForceFileStandard(t *testing.T) {
t.Error(err)
}
if t.Failed() {
t.Fatal("Please use convert.StringToFloat64 type instead of `float64` and remove `,string` as strings can be empty in unmarshal process. Then call the Float64() method.")
t.Fatal("Please use types.Number type instead of `float64` and remove `,string` as strings can be empty in unmarshal process. Then call the Float64() method.")
}
}

View File

@@ -6,8 +6,8 @@ import (
"strconv"
"time"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-corp/gocryptotrader/types"
)
var (
@@ -158,19 +158,19 @@ type UnmarshalTo interface {
// PairData stores pair data
type PairData struct {
Name string `json:"name"`
Alias string `json:"alias"`
BaseCurrency string `json:"baseCurrency"`
QuoteCurrency string `json:"quoteCurrency"`
BasePrecision convert.StringToFloat64 `json:"basePrecision"`
QuotePrecision convert.StringToFloat64 `json:"quotePrecision"`
MinTradeQuantity convert.StringToFloat64 `json:"minTradeQuantity"`
MinTradeAmount convert.StringToFloat64 `json:"minTradeAmount"`
MinPricePrecision convert.StringToFloat64 `json:"minPricePrecision"`
MaxTradeQuantity convert.StringToFloat64 `json:"maxTradeQuantity"`
MaxTradeAmount convert.StringToFloat64 `json:"maxTradeAmount"`
Category int64 `json:"category"`
ShowStatus bool `json:"showStatus"`
Name string `json:"name"`
Alias string `json:"alias"`
BaseCurrency string `json:"baseCurrency"`
QuoteCurrency string `json:"quoteCurrency"`
BasePrecision types.Number `json:"basePrecision"`
QuotePrecision types.Number `json:"quotePrecision"`
MinTradeQuantity types.Number `json:"minTradeQuantity"`
MinTradeAmount types.Number `json:"minTradeAmount"`
MinPricePrecision types.Number `json:"minPricePrecision"`
MaxTradeQuantity types.Number `json:"maxTradeQuantity"`
MaxTradeAmount types.Number `json:"maxTradeAmount"`
Category int64 `json:"category"`
ShowStatus bool `json:"showStatus"`
}
// Orderbook stores the orderbook data
@@ -207,32 +207,32 @@ type KlineItem struct {
// PriceChangeStats contains statistics for the last 24 hours trade
type PriceChangeStats struct {
Time bybitTimeMilliSec `json:"time"`
Symbol string `json:"symbol"`
BestBidPrice convert.StringToFloat64 `json:"bestBidPrice"`
BestAskPrice convert.StringToFloat64 `json:"bestAskPrice"`
LastPrice convert.StringToFloat64 `json:"lastPrice"`
OpenPrice convert.StringToFloat64 `json:"openPrice"`
HighPrice convert.StringToFloat64 `json:"highPrice"`
LowPrice convert.StringToFloat64 `json:"lowPrice"`
Volume convert.StringToFloat64 `json:"volume"`
QuoteVolume convert.StringToFloat64 `json:"quoteVolume"`
Time bybitTimeMilliSec `json:"time"`
Symbol string `json:"symbol"`
BestBidPrice types.Number `json:"bestBidPrice"`
BestAskPrice types.Number `json:"bestAskPrice"`
LastPrice types.Number `json:"lastPrice"`
OpenPrice types.Number `json:"openPrice"`
HighPrice types.Number `json:"highPrice"`
LowPrice types.Number `json:"lowPrice"`
Volume types.Number `json:"volume"`
QuoteVolume types.Number `json:"quoteVolume"`
}
// LastTradePrice contains price for last trade
type LastTradePrice struct {
Symbol string `json:"symbol"`
Price convert.StringToFloat64 `json:"price"`
Symbol string `json:"symbol"`
Price types.Number `json:"price"`
}
// TickerData stores ticker data
type TickerData struct {
Symbol string `json:"symbol"`
BidPrice convert.StringToFloat64 `json:"bidPrice"`
BidQuantity convert.StringToFloat64 `json:"bidQty"`
AskPrice convert.StringToFloat64 `json:"askPrice"`
AskQuantity convert.StringToFloat64 `json:"askQty"`
Time bybitTimeMilliSec `json:"time"`
Symbol string `json:"symbol"`
BidPrice types.Number `json:"bidPrice"`
BidQuantity types.Number `json:"bidQty"`
AskPrice types.Number `json:"askPrice"`
AskQuantity types.Number `json:"askQty"`
Time bybitTimeMilliSec `json:"time"`
}
var (
@@ -270,97 +270,97 @@ type PlaceOrderRequest struct {
// PlaceOrderResponse store new order response type
type PlaceOrderResponse struct {
OrderID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Symbol string `json:"symbol"`
Time bybitTimeMilliSecStr `json:"transactTime"`
Price convert.StringToFloat64 `json:"price"`
Quantity convert.StringToFloat64 `json:"origQty"`
TradeType string `json:"type"`
Side string `json:"side"`
Status string `json:"status"`
TimeInForce string `json:"timeInForce"`
AccountID string `json:"accountId"`
SymbolName string `json:"symbolName"`
ExecutedQty convert.StringToFloat64 `json:"executedQty"`
OrderID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Symbol string `json:"symbol"`
Time bybitTimeMilliSecStr `json:"transactTime"`
Price types.Number `json:"price"`
Quantity types.Number `json:"origQty"`
TradeType string `json:"type"`
Side string `json:"side"`
Status string `json:"status"`
TimeInForce string `json:"timeInForce"`
AccountID string `json:"accountId"`
SymbolName string `json:"symbolName"`
ExecutedQty types.Number `json:"executedQty"`
}
// QueryOrderResponse holds query order data
type QueryOrderResponse struct {
AccountID string `json:"accountId"`
ExchangeID string `json:"exchangeId"`
Symbol string `json:"symbol"`
SymbolName string `json:"symbolName"`
OrderLinkID string `json:"orderLinkId"`
OrderID string `json:"orderId"`
Price convert.StringToFloat64 `json:"price"`
Quantity convert.StringToFloat64 `json:"origQty"`
ExecutedQty convert.StringToFloat64 `json:"executedQty"`
CummulativeQuoteQty convert.StringToFloat64 `json:"cummulativeQuoteQty"`
AveragePrice convert.StringToFloat64 `json:"avgPrice"`
Status string `json:"status"`
TimeInForce string `json:"timeInForce"`
TradeType string `json:"type"`
Side string `json:"side"`
StopPrice convert.StringToFloat64 `json:"stopPrice"`
IcebergQty convert.StringToFloat64 `json:"icebergQty"`
Time bybitTimeMilliSecStr `json:"time"`
UpdateTime bybitTimeMilliSecStr `json:"updateTime"`
IsWorking bool `json:"isWorking"`
AccountID string `json:"accountId"`
ExchangeID string `json:"exchangeId"`
Symbol string `json:"symbol"`
SymbolName string `json:"symbolName"`
OrderLinkID string `json:"orderLinkId"`
OrderID string `json:"orderId"`
Price types.Number `json:"price"`
Quantity types.Number `json:"origQty"`
ExecutedQty types.Number `json:"executedQty"`
CummulativeQuoteQty types.Number `json:"cummulativeQuoteQty"`
AveragePrice types.Number `json:"avgPrice"`
Status string `json:"status"`
TimeInForce string `json:"timeInForce"`
TradeType string `json:"type"`
Side string `json:"side"`
StopPrice types.Number `json:"stopPrice"`
IcebergQty types.Number `json:"icebergQty"`
Time bybitTimeMilliSecStr `json:"time"`
UpdateTime bybitTimeMilliSecStr `json:"updateTime"`
IsWorking bool `json:"isWorking"`
}
// CancelOrderResponse is the return structured response from the exchange
type CancelOrderResponse struct {
OrderID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Symbol string `json:"symbol"`
Status string `json:"status"`
AccountID string `json:"accountId"`
Time bybitTimeMilliSecStr `json:"transactTime"`
Price convert.StringToFloat64 `json:"price"`
Quantity convert.StringToFloat64 `json:"origQty"`
ExecutedQty convert.StringToFloat64 `json:"executedQty"`
TimeInForce string `json:"timeInForce"`
TradeType string `json:"type"`
Side string `json:"side"`
OrderID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Symbol string `json:"symbol"`
Status string `json:"status"`
AccountID string `json:"accountId"`
Time bybitTimeMilliSecStr `json:"transactTime"`
Price types.Number `json:"price"`
Quantity types.Number `json:"origQty"`
ExecutedQty types.Number `json:"executedQty"`
TimeInForce string `json:"timeInForce"`
TradeType string `json:"type"`
Side string `json:"side"`
}
// HistoricalTrade holds recent trade data
type HistoricalTrade struct {
Symbol string `json:"symbol"`
ID string `json:"id"`
OrderID string `json:"orderId"`
TicketID string `json:"ticketId"`
Price convert.StringToFloat64 `json:"price"`
Quantity convert.StringToFloat64 `json:"qty"`
Commission convert.StringToFloat64 `json:"commission"`
CommissionAsset convert.StringToFloat64 `json:"commissionAsset"`
Time bybitTimeMilliSecStr `json:"time"`
IsBuyer bool `json:"isBuyer"`
IsMaker bool `json:"isMaker"`
SymbolName string `json:"symbolName"`
MatchOrderID string `json:"matchOrderId"`
Fee FeeData `json:"fee"`
FeeTokenID string `json:"feeTokenId"`
FeeAmount convert.StringToFloat64 `json:"feeAmount"`
MakerRebate convert.StringToFloat64 `json:"makerRebate"`
Symbol string `json:"symbol"`
ID string `json:"id"`
OrderID string `json:"orderId"`
TicketID string `json:"ticketId"`
Price types.Number `json:"price"`
Quantity types.Number `json:"qty"`
Commission types.Number `json:"commission"`
CommissionAsset types.Number `json:"commissionAsset"`
Time bybitTimeMilliSecStr `json:"time"`
IsBuyer bool `json:"isBuyer"`
IsMaker bool `json:"isMaker"`
SymbolName string `json:"symbolName"`
MatchOrderID string `json:"matchOrderId"`
Fee FeeData `json:"fee"`
FeeTokenID string `json:"feeTokenId"`
FeeAmount types.Number `json:"feeAmount"`
MakerRebate types.Number `json:"makerRebate"`
}
// FeeData store fees data
type FeeData struct {
FeeTokenID int64 `json:"feeTokenId"`
FeeTokenName string `json:"feeTokenName"`
Fee convert.StringToFloat64 `json:"fee"`
FeeTokenID int64 `json:"feeTokenId"`
FeeTokenName string `json:"feeTokenName"`
Fee types.Number `json:"fee"`
}
// Balance holds wallet balance
type Balance struct {
Coin string `json:"coin"`
CoinID string `json:"coinId"`
CoinName string `json:"coinName"`
Total convert.StringToFloat64 `json:"total"`
Free convert.StringToFloat64 `json:"free"`
Locked convert.StringToFloat64 `json:"locked"`
Coin string `json:"coin"`
CoinID string `json:"coinId"`
CoinName string `json:"coinName"`
Total types.Number `json:"total"`
Free types.Number `json:"free"`
Locked types.Number `json:"locked"`
}
type orderbookResponse struct {
@@ -417,12 +417,12 @@ type WsParams struct {
// WsSpotTickerData stores ws ticker data
type WsSpotTickerData struct {
Symbol string `json:"symbol"`
Bid convert.StringToFloat64 `json:"bidPrice"`
Ask convert.StringToFloat64 `json:"askPrice"`
BidSize convert.StringToFloat64 `json:"bidQty"`
AskSize convert.StringToFloat64 `json:"askQty"`
Time bybitTimeMilliSec `json:"time"`
Symbol string `json:"symbol"`
Bid types.Number `json:"bidPrice"`
Ask types.Number `json:"askPrice"`
BidSize types.Number `json:"bidQty"`
AskSize types.Number `json:"askQty"`
Time bybitTimeMilliSec `json:"time"`
}
// WsSpotTicker stores ws ticker data
@@ -434,13 +434,13 @@ type WsSpotTicker struct {
// KlineStreamData stores ws kline stream data
type KlineStreamData struct {
StartTime bybitTimeMilliSec `json:"t"`
Symbol string `json:"s"`
ClosePrice convert.StringToFloat64 `json:"c"`
HighPrice convert.StringToFloat64 `json:"h"`
LowPrice convert.StringToFloat64 `json:"l"`
OpenPrice convert.StringToFloat64 `json:"o"`
Volume convert.StringToFloat64 `json:"v"`
StartTime bybitTimeMilliSec `json:"t"`
Symbol string `json:"s"`
ClosePrice types.Number `json:"c"`
HighPrice types.Number `json:"h"`
LowPrice types.Number `json:"l"`
OpenPrice types.Number `json:"o"`
Volume types.Number `json:"v"`
}
// KlineStream holds the kline stream data
@@ -468,11 +468,11 @@ type WsOrderbook struct {
// WsTradeData stores ws trade data
type WsTradeData struct {
Time bybitTimeMilliSec `json:"t"`
ID string `json:"v"`
Price convert.StringToFloat64 `json:"p"`
Size convert.StringToFloat64 `json:"q"`
Side bool `json:"m"`
Time bybitTimeMilliSec `json:"t"`
ID string `json:"v"`
Price types.Number `json:"p"`
Size types.Number `json:"q"`
Side bool `json:"m"`
}
// WsTrade stores ws trades data
@@ -494,65 +494,65 @@ type wsAccount struct {
// Currencies stores currencies data
type Currencies struct {
Asset string `json:"a"`
Available convert.StringToFloat64 `json:"f"`
Locked convert.StringToFloat64 `json:"l"`
Asset string `json:"a"`
Available types.Number `json:"f"`
Locked types.Number `json:"l"`
}
// wsOrderUpdate defines websocket account order update data
type wsOrderUpdate struct {
EventType string `json:"e"`
EventTime string `json:"E"`
Symbol string `json:"s"`
ClientOrderID string `json:"c"`
Side string `json:"S"`
OrderType string `json:"o"`
TimeInForce string `json:"f"`
Quantity convert.StringToFloat64 `json:"q"`
Price convert.StringToFloat64 `json:"p"`
OrderStatus string `json:"X"`
OrderID string `json:"i"`
OpponentOrderID string `json:"M"`
LastExecutedQuantity convert.StringToFloat64 `json:"l"`
CumulativeFilledQuantity convert.StringToFloat64 `json:"z"`
LastExecutedPrice convert.StringToFloat64 `json:"L"`
Commission convert.StringToFloat64 `json:"n"`
CommissionAsset string `json:"N"`
IsNormal bool `json:"u"`
IsOnOrderBook bool `json:"w"`
IsLimitMaker bool `json:"m"`
OrderCreationTime bybitTimeMilliSecStr `json:"O"`
CumulativeQuoteTransactedQuantity convert.StringToFloat64 `json:"Z"`
AccountID string `json:"A"`
IsClose bool `json:"C"`
Leverage convert.StringToFloat64 `json:"v"`
EventType string `json:"e"`
EventTime string `json:"E"`
Symbol string `json:"s"`
ClientOrderID string `json:"c"`
Side string `json:"S"`
OrderType string `json:"o"`
TimeInForce string `json:"f"`
Quantity types.Number `json:"q"`
Price types.Number `json:"p"`
OrderStatus string `json:"X"`
OrderID string `json:"i"`
OpponentOrderID string `json:"M"`
LastExecutedQuantity types.Number `json:"l"`
CumulativeFilledQuantity types.Number `json:"z"`
LastExecutedPrice types.Number `json:"L"`
Commission types.Number `json:"n"`
CommissionAsset string `json:"N"`
IsNormal bool `json:"u"`
IsOnOrderBook bool `json:"w"`
IsLimitMaker bool `json:"m"`
OrderCreationTime bybitTimeMilliSecStr `json:"O"`
CumulativeQuoteTransactedQuantity types.Number `json:"Z"`
AccountID string `json:"A"`
IsClose bool `json:"C"`
Leverage types.Number `json:"v"`
}
// wsOrderFilled defines websocket account order filled data
type wsOrderFilled struct {
EventType string `json:"e"`
EventTime string `json:"E"`
Symbol string `json:"s"`
Quantity convert.StringToFloat64 `json:"q"`
Timestamp bybitTimeMilliSecStr `json:"t"`
Price convert.StringToFloat64 `json:"p"`
TradeID string `json:"T"`
OrderID string `json:"o"`
UserGenOrderID string `json:"c"`
OpponentOrderID string `json:"O"`
AccountID string `json:"a"`
OpponentAccountID string `json:"A"`
IsMaker bool `json:"m"`
Side string `json:"S"`
EventType string `json:"e"`
EventTime string `json:"E"`
Symbol string `json:"s"`
Quantity types.Number `json:"q"`
Timestamp bybitTimeMilliSecStr `json:"t"`
Price types.Number `json:"p"`
TradeID string `json:"T"`
OrderID string `json:"o"`
UserGenOrderID string `json:"c"`
OpponentOrderID string `json:"O"`
AccountID string `json:"a"`
OpponentAccountID string `json:"A"`
IsMaker bool `json:"m"`
Side string `json:"S"`
}
// WsFuturesOrderbookData stores ws futures orderbook data
type WsFuturesOrderbookData struct {
Price convert.StringToFloat64 `json:"price"`
Symbol string `json:"symbol"`
ID int64 `json:"id"`
Side string `json:"side"`
Size float64 `json:"size"`
Price types.Number `json:"price"`
Symbol string `json:"symbol"`
ID int64 `json:"id"`
Side string `json:"side"`
Size float64 `json:"size"`
}
// WsFuturesOrderbook stores ws futures orderbook
@@ -635,32 +635,32 @@ type WsInsurance struct {
// WsTickerData stores ws ticker data
type WsTickerData struct {
ID string `json:"id"`
Symbol string `json:"symbol"`
LastPrice convert.StringToFloat64 `json:"last_price"`
BidPrice float64 `json:"bid1_price"`
AskPrice float64 `json:"ask1_price"`
LastDirection string `json:"last_tick_direction"`
PrevPrice24h convert.StringToFloat64 `json:"prev_price_24h"`
Price24hPercentChange float64 `json:"price_24h_pcnt_e6"`
Price1hPercentChange float64 `json:"price_1h_pcnt_e6"`
HighPrice24h convert.StringToFloat64 `json:"high_price_24h"`
LowPrice24h convert.StringToFloat64 `json:"low_price_24h"`
PrevPrice1h convert.StringToFloat64 `json:"prev_price_1h"`
MarkPrice convert.StringToFloat64 `json:"mark_price"`
IndexPrice convert.StringToFloat64 `json:"index_price"`
OpenInterest float64 `json:"open_interest"`
OpenValue float64 `json:"open_value_e8"`
TotalTurnOver float64 `json:"total_turnover_e8"`
TurnOver24h float64 `json:"turnover_24h_e8"`
TotalVolume float64 `json:"total_volume"`
Volume24h float64 `json:"volume_24h"`
FundingRate int64 `json:"funding_rate_e6"`
PredictedFundingRate float64 `json:"predicted_funding_rate_e6"`
CreatedAt time.Time `json:"created_at"`
UpdateAt time.Time `json:"updated_at"`
NextFundingAt time.Time `json:"next_funding_time"`
CountDownHour int64 `json:"countdown_hour"`
ID string `json:"id"`
Symbol string `json:"symbol"`
LastPrice types.Number `json:"last_price"`
BidPrice float64 `json:"bid1_price"`
AskPrice float64 `json:"ask1_price"`
LastDirection string `json:"last_tick_direction"`
PrevPrice24h types.Number `json:"prev_price_24h"`
Price24hPercentChange float64 `json:"price_24h_pcnt_e6"`
Price1hPercentChange float64 `json:"price_1h_pcnt_e6"`
HighPrice24h types.Number `json:"high_price_24h"`
LowPrice24h types.Number `json:"low_price_24h"`
PrevPrice1h types.Number `json:"prev_price_1h"`
MarkPrice types.Number `json:"mark_price"`
IndexPrice types.Number `json:"index_price"`
OpenInterest float64 `json:"open_interest"`
OpenValue float64 `json:"open_value_e8"`
TotalTurnOver float64 `json:"total_turnover_e8"`
TurnOver24h float64 `json:"turnover_24h_e8"`
TotalVolume float64 `json:"total_volume"`
Volume24h float64 `json:"volume_24h"`
FundingRate int64 `json:"funding_rate_e6"`
PredictedFundingRate float64 `json:"predicted_funding_rate_e6"`
CreatedAt time.Time `json:"created_at"`
UpdateAt time.Time `json:"updated_at"`
NextFundingAt time.Time `json:"next_funding_time"`
CountDownHour int64 `json:"countdown_hour"`
}
// WsTicker stores ws ticker
@@ -682,45 +682,45 @@ type WsDeltaTicker struct {
// WsFuturesTickerData stores ws future ticker data
type WsFuturesTickerData struct {
ID string `json:"id"`
Symbol string `json:"symbol"`
SymbolName string `json:"symbol_name"`
SymbolYear int64 `json:"symbol_year"`
ContractType string `json:"contract_type"`
Coin string `json:"coin"`
QuoteSymbol string `json:"quote_symbol"`
Mode string `json:"mode"`
IsUpBorrowable int64 `json:"is_up_borrowable"`
ImportTime bybitTimeNanoSec `json:"import_time_e9"`
StartTradingTime bybitTimeNanoSec `json:"start_trading_time_e9"`
TimeToSettle bybitTimeNanoSec `json:"settle_time_e9"`
SettleFeeRate int64 `json:"settle_fee_rate_e8"`
ContractStatus string `json:"contract_status"`
SystemSubsidy int64 `json:"system_subsidy_e8"`
LastPrice convert.StringToFloat64 `json:"last_price"`
BidPrice float64 `json:"bid1_price"`
AskPrice float64 `json:"ask1_price"`
LastDirection string `json:"last_tick_direction"`
PrevPrice24h convert.StringToFloat64 `json:"prev_price_24h"`
Price24hPercentChange float64 `json:"price_24h_pcnt_e6"`
Price1hPercentChange float64 `json:"price_1h_pcnt_e6"`
HighPrice24h convert.StringToFloat64 `json:"high_price_24h"`
LowPrice24h convert.StringToFloat64 `json:"low_price_24h"`
PrevPrice1h convert.StringToFloat64 `json:"prev_price_1h"`
MarkPrice convert.StringToFloat64 `json:"mark_price"`
IndexPrice convert.StringToFloat64 `json:"index_price"`
OpenInterest float64 `json:"open_interest"`
OpenValue float64 `json:"open_value_e8"`
TotalTurnOver float64 `json:"total_turnover_e8"`
TurnOver24h float64 `json:"turnover_24h_e8"`
TotalVolume float64 `json:"total_volume"`
Volume24h float64 `json:"volume_24h"`
FairBasis float64 `json:"fair_basis_e8"`
FairBasisRate float64 `json:"fair_basis_rate_e8"`
BasisInYear float64 `json:"basis_in_year_e8"`
ExpectPrice convert.StringToFloat64 `json:"expect_price"`
CreatedAt time.Time `json:"created_at"`
UpdateAt time.Time `json:"updated_at"`
ID string `json:"id"`
Symbol string `json:"symbol"`
SymbolName string `json:"symbol_name"`
SymbolYear int64 `json:"symbol_year"`
ContractType string `json:"contract_type"`
Coin string `json:"coin"`
QuoteSymbol string `json:"quote_symbol"`
Mode string `json:"mode"`
IsUpBorrowable int64 `json:"is_up_borrowable"`
ImportTime bybitTimeNanoSec `json:"import_time_e9"`
StartTradingTime bybitTimeNanoSec `json:"start_trading_time_e9"`
TimeToSettle bybitTimeNanoSec `json:"settle_time_e9"`
SettleFeeRate int64 `json:"settle_fee_rate_e8"`
ContractStatus string `json:"contract_status"`
SystemSubsidy int64 `json:"system_subsidy_e8"`
LastPrice types.Number `json:"last_price"`
BidPrice float64 `json:"bid1_price"`
AskPrice float64 `json:"ask1_price"`
LastDirection string `json:"last_tick_direction"`
PrevPrice24h types.Number `json:"prev_price_24h"`
Price24hPercentChange float64 `json:"price_24h_pcnt_e6"`
Price1hPercentChange float64 `json:"price_1h_pcnt_e6"`
HighPrice24h types.Number `json:"high_price_24h"`
LowPrice24h types.Number `json:"low_price_24h"`
PrevPrice1h types.Number `json:"prev_price_1h"`
MarkPrice types.Number `json:"mark_price"`
IndexPrice types.Number `json:"index_price"`
OpenInterest float64 `json:"open_interest"`
OpenValue float64 `json:"open_value_e8"`
TotalTurnOver float64 `json:"total_turnover_e8"`
TurnOver24h float64 `json:"turnover_24h_e8"`
TotalVolume float64 `json:"total_volume"`
Volume24h float64 `json:"volume_24h"`
FairBasis float64 `json:"fair_basis_e8"`
FairBasisRate float64 `json:"fair_basis_rate_e8"`
BasisInYear float64 `json:"basis_in_year_e8"`
ExpectPrice types.Number `json:"expect_price"`
CreatedAt time.Time `json:"created_at"`
UpdateAt time.Time `json:"updated_at"`
}
// WsFuturesTicker stores ws future ticker
@@ -742,11 +742,11 @@ type WsDeltaFuturesTicker struct {
// WsLiquidationData stores ws liquidation data
type WsLiquidationData struct {
Symbol string `json:"symbol"`
Side string `json:"side"`
Price convert.StringToFloat64 `json:"price"`
Qty float64 `json:"qty"`
Timestamp bybitTimeMilliSec `json:"time"`
Symbol string `json:"symbol"`
Side string `json:"side"`
Price types.Number `json:"price"`
Qty float64 `json:"qty"`
Timestamp bybitTimeMilliSec `json:"time"`
}
// WsFuturesLiquidation stores ws future liquidation
@@ -757,36 +757,36 @@ type WsFuturesLiquidation struct {
// WsFuturesPositionData stores ws future position data
type WsFuturesPositionData struct {
UserID int64 `json:"user_id"`
Symbol string `json:"symbol"`
Side string `json:"side"`
Size float64 `json:"size"`
PositionID int64 `json:"position_idx"` // present in Futures position struct only
Mode int64 `json:"mode"` // present in Futures position struct only
Isolated bool `json:"isolated"` // present in Futures position struct only
PositionValue convert.StringToFloat64 `json:"position_value"`
EntryPrice convert.StringToFloat64 `json:"entry_price"`
LiquidPrice convert.StringToFloat64 `json:"liq_price"`
BustPrice convert.StringToFloat64 `json:"bust_price"`
Leverage convert.StringToFloat64 `json:"leverage"`
OrderMargin convert.StringToFloat64 `json:"order_margin"`
PositionMargin convert.StringToFloat64 `json:"position_margin"`
AvailableBalance convert.StringToFloat64 `json:"available_balance"`
TakeProfit convert.StringToFloat64 `json:"take_profit"`
TakeProfitTriggerBy string `json:"tp_trigger_by"`
StopLoss convert.StringToFloat64 `json:"stop_loss"`
StopLossTriggerBy string `json:"sl_trigger_by"`
RealisedPNL convert.StringToFloat64 `json:"realised_pnl"`
TrailingStop convert.StringToFloat64 `json:"trailing_stop"`
TrailingActive convert.StringToFloat64 `json:"trailing_active"`
WalletBalance convert.StringToFloat64 `json:"wallet_balance"`
RiskID int64 `json:"risk_id"`
ClosingFee convert.StringToFloat64 `json:"occ_closing_fee"`
FundingFee convert.StringToFloat64 `json:"occ_funding_fee"`
AutoAddMargin int64 `json:"auto_add_margin"`
TotalPNL convert.StringToFloat64 `json:"cum_realised_pnl"`
Status string `json:"position_status"`
Version int64 `json:"position_seq"`
UserID int64 `json:"user_id"`
Symbol string `json:"symbol"`
Side string `json:"side"`
Size float64 `json:"size"`
PositionID int64 `json:"position_idx"` // present in Futures position struct only
Mode int64 `json:"mode"` // present in Futures position struct only
Isolated bool `json:"isolated"` // present in Futures position struct only
PositionValue types.Number `json:"position_value"`
EntryPrice types.Number `json:"entry_price"`
LiquidPrice types.Number `json:"liq_price"`
BustPrice types.Number `json:"bust_price"`
Leverage types.Number `json:"leverage"`
OrderMargin types.Number `json:"order_margin"`
PositionMargin types.Number `json:"position_margin"`
AvailableBalance types.Number `json:"available_balance"`
TakeProfit types.Number `json:"take_profit"`
TakeProfitTriggerBy string `json:"tp_trigger_by"`
StopLoss types.Number `json:"stop_loss"`
StopLossTriggerBy string `json:"sl_trigger_by"`
RealisedPNL types.Number `json:"realised_pnl"`
TrailingStop types.Number `json:"trailing_stop"`
TrailingActive types.Number `json:"trailing_active"`
WalletBalance types.Number `json:"wallet_balance"`
RiskID int64 `json:"risk_id"`
ClosingFee types.Number `json:"occ_closing_fee"`
FundingFee types.Number `json:"occ_funding_fee"`
AutoAddMargin int64 `json:"auto_add_margin"`
TotalPNL types.Number `json:"cum_realised_pnl"`
Status string `json:"position_status"`
Version int64 `json:"position_seq"`
}
// WsFuturesPosition stores ws future position
@@ -798,19 +798,19 @@ type WsFuturesPosition struct {
// WsFuturesExecutionData stores ws future execution data
type WsFuturesExecutionData struct {
Symbol string `json:"symbol"`
Side string `json:"side"`
OrderID string `json:"order_id"`
ExecutionID string `json:"exec_id"`
OrderLinkID string `json:"order_link_id"`
Price convert.StringToFloat64 `json:"price"`
OrderQty float64 `json:"order_qty"`
ExecutionType string `json:"exec_type"`
ExecutionQty float64 `json:"exec_qty"`
ExecutionFee convert.StringToFloat64 `json:"exec_fee"`
LeavesQty float64 `json:"leaves_qty"`
IsMaker bool `json:"is_maker"`
Time time.Time `json:"trade_time"`
Symbol string `json:"symbol"`
Side string `json:"side"`
OrderID string `json:"order_id"`
ExecutionID string `json:"exec_id"`
OrderLinkID string `json:"order_link_id"`
Price types.Number `json:"price"`
OrderQty float64 `json:"order_qty"`
ExecutionType string `json:"exec_type"`
ExecutionQty float64 `json:"exec_qty"`
ExecutionFee types.Number `json:"exec_fee"`
LeavesQty float64 `json:"leaves_qty"`
IsMaker bool `json:"is_maker"`
Time time.Time `json:"trade_time"`
}
// WsFuturesExecution stores ws future execution
@@ -821,31 +821,31 @@ type WsFuturesExecution struct {
// WsOrderData stores ws order data
type WsOrderData struct {
OrderID string `json:"order_id"`
OrderLinkID string `json:"order_link_id"`
Symbol string `json:"symbol"`
Side string `json:"side"`
OrderType string `json:"order_type"`
Price convert.StringToFloat64 `json:"price"`
OrderQty float64 `json:"qty"`
TimeInForce string `json:"time_in_force"`
CreateType string `json:"create_type"`
CancelType string `json:"cancel_type"`
OrderStatus string `json:"order_status"`
LeavesQty float64 `json:"leaves_qty"`
CummulativeExecQty float64 `json:"cum_exec_qty"`
CummulativeExecValue convert.StringToFloat64 `json:"cum_exec_value"`
CummulativeExecFee convert.StringToFloat64 `json:"cum_exec_fee"`
TakeProfit convert.StringToFloat64 `json:"take_profit"`
StopLoss convert.StringToFloat64 `json:"stop_loss"`
TrailingStop convert.StringToFloat64 `json:"trailing_stop"`
TrailingActive convert.StringToFloat64 `json:"trailing_active"`
LastExecPrice convert.StringToFloat64 `json:"last_exec_price"`
ReduceOnly bool `json:"reduce_only"`
CloseOnTrigger bool `json:"close_on_trigger"`
Time time.Time `json:"timestamp"` // present in CoinMarginedFutures and Futures only
CreateTime time.Time `json:"create_time"` // present in USDTMarginedFutures only
UpdateTime time.Time `json:"update_time"` // present in USDTMarginedFutures only
OrderID string `json:"order_id"`
OrderLinkID string `json:"order_link_id"`
Symbol string `json:"symbol"`
Side string `json:"side"`
OrderType string `json:"order_type"`
Price types.Number `json:"price"`
OrderQty float64 `json:"qty"`
TimeInForce string `json:"time_in_force"`
CreateType string `json:"create_type"`
CancelType string `json:"cancel_type"`
OrderStatus string `json:"order_status"`
LeavesQty float64 `json:"leaves_qty"`
CummulativeExecQty float64 `json:"cum_exec_qty"`
CummulativeExecValue types.Number `json:"cum_exec_value"`
CummulativeExecFee types.Number `json:"cum_exec_fee"`
TakeProfit types.Number `json:"take_profit"`
StopLoss types.Number `json:"stop_loss"`
TrailingStop types.Number `json:"trailing_stop"`
TrailingActive types.Number `json:"trailing_active"`
LastExecPrice types.Number `json:"last_exec_price"`
ReduceOnly bool `json:"reduce_only"`
CloseOnTrigger bool `json:"close_on_trigger"`
Time time.Time `json:"timestamp"` // present in CoinMarginedFutures and Futures only
CreateTime time.Time `json:"create_time"` // present in USDTMarginedFutures only
UpdateTime time.Time `json:"update_time"` // present in USDTMarginedFutures only
}
// WsOrder stores ws order
@@ -856,23 +856,23 @@ type WsOrder struct {
// WsStopOrderData stores ws stop order data
type WsStopOrderData struct {
OrderID string `json:"order_id"`
OrderLinkID string `json:"order_link_id"`
UserID int64 `json:"user_id"`
Symbol string `json:"symbol"`
Side string `json:"side"`
OrderType string `json:"order_type"`
Price convert.StringToFloat64 `json:"price"`
OrderQty float64 `json:"qty"`
TimeInForce string `json:"time_in_force"`
CreateType string `json:"create_type"`
CancelType string `json:"cancel_type"`
OrderStatus string `json:"order_status"`
StopOrderType string `json:"stop_order_type"`
TriggerBy string `json:"trigger_by"`
TriggerPrice convert.StringToFloat64 `json:"trigger_price"`
Time time.Time `json:"timestamp"`
CloseOnTrigger bool `json:"close_on_trigger"`
OrderID string `json:"order_id"`
OrderLinkID string `json:"order_link_id"`
UserID int64 `json:"user_id"`
Symbol string `json:"symbol"`
Side string `json:"side"`
OrderType string `json:"order_type"`
Price types.Number `json:"price"`
OrderQty float64 `json:"qty"`
TimeInForce string `json:"time_in_force"`
CreateType string `json:"create_type"`
CancelType string `json:"cancel_type"`
OrderStatus string `json:"order_status"`
StopOrderType string `json:"stop_order_type"`
TriggerBy string `json:"trigger_by"`
TriggerPrice types.Number `json:"trigger_price"`
Time time.Time `json:"timestamp"`
CloseOnTrigger bool `json:"close_on_trigger"`
}
// WsFuturesStopOrder stores ws future stop order
@@ -883,23 +883,23 @@ type WsFuturesStopOrder struct {
// WsUSDTStopOrderData stores ws USDT stop order data
type WsUSDTStopOrderData struct {
OrderID string `json:"stop_order_id"`
OrderLinkID string `json:"order_link_id"`
UserID int64 `json:"user_id"`
Symbol string `json:"symbol"`
Side string `json:"side"`
OrderType string `json:"order_type"`
Price convert.StringToFloat64 `json:"price"`
OrderQty float64 `json:"qty"`
TimeInForce string `json:"time_in_force"`
OrderStatus string `json:"order_status"`
StopOrderType string `json:"stop_order_type"`
TriggerBy string `json:"trigger_by"`
TriggerPrice convert.StringToFloat64 `json:"trigger_price"`
ReduceOnly bool `json:"reduce_only"`
CloseOnTrigger bool `json:"close_on_trigger"`
CreateTime time.Time `json:"create_time"`
UpdateTime time.Time `json:"update_time"`
OrderID string `json:"stop_order_id"`
OrderLinkID string `json:"order_link_id"`
UserID int64 `json:"user_id"`
Symbol string `json:"symbol"`
Side string `json:"side"`
OrderType string `json:"order_type"`
Price types.Number `json:"price"`
OrderQty float64 `json:"qty"`
TimeInForce string `json:"time_in_force"`
OrderStatus string `json:"order_status"`
StopOrderType string `json:"stop_order_type"`
TriggerBy string `json:"trigger_by"`
TriggerPrice types.Number `json:"trigger_price"`
ReduceOnly bool `json:"reduce_only"`
CloseOnTrigger bool `json:"close_on_trigger"`
CreateTime time.Time `json:"create_time"`
UpdateTime time.Time `json:"update_time"`
}
// WsUSDTFuturesStopOrder stores ws USDT stop order
@@ -923,54 +923,54 @@ type WsFuturesWallet struct {
// Ticker holds ticker information
type Ticker struct {
// Spot fields
Symbol string `json:"symbol"`
TopBidPrice convert.StringToFloat64 `json:"bid1Price"`
TopBidSize convert.StringToFloat64 `json:"bid1Size"`
TopAskPrice convert.StringToFloat64 `json:"ask1Price"`
TopAskSize convert.StringToFloat64 `json:"ask1Size"`
LastPrice convert.StringToFloat64 `json:"lastPrice"`
PreviousPrice24Hr convert.StringToFloat64 `json:"prevPrice24h"`
Price24HrPcnt convert.StringToFloat64 `json:"price24hPcnt"`
HighPrice24Hr convert.StringToFloat64 `json:"highPrice24h"`
LowPrice24Hr convert.StringToFloat64 `json:"lowPrice24h"`
Turnover24Hr convert.StringToFloat64 `json:"turnover24h"`
Volume24Hr convert.StringToFloat64 `json:"volume24h"`
USDIndexPrice convert.StringToFloat64 `json:"usdIndexPrice"`
Symbol string `json:"symbol"`
TopBidPrice types.Number `json:"bid1Price"`
TopBidSize types.Number `json:"bid1Size"`
TopAskPrice types.Number `json:"ask1Price"`
TopAskSize types.Number `json:"ask1Size"`
LastPrice types.Number `json:"lastPrice"`
PreviousPrice24Hr types.Number `json:"prevPrice24h"`
Price24HrPcnt types.Number `json:"price24hPcnt"`
HighPrice24Hr types.Number `json:"highPrice24h"`
LowPrice24Hr types.Number `json:"lowPrice24h"`
Turnover24Hr types.Number `json:"turnover24h"`
Volume24Hr types.Number `json:"volume24h"`
USDIndexPrice types.Number `json:"usdIndexPrice"`
// Option fields
TopBidImpliedVolatility convert.StringToFloat64 `json:"bid1Iv"`
TopAskImpliedVolatility convert.StringToFloat64 `json:"ask1Iv"`
MarkPrice convert.StringToFloat64 `json:"markPrice"`
IndexPrice convert.StringToFloat64 `json:"indexPrice"`
MarkImpliedVolatility convert.StringToFloat64 `json:"markIv"`
UnderlyingPrice convert.StringToFloat64 `json:"underlyingPrice"`
OpenInterest convert.StringToFloat64 `json:"openInterest"`
TotalVolume convert.StringToFloat64 `json:"totalVolume"`
TotalTurnover convert.StringToFloat64 `json:"totalTurnover"`
Delta convert.StringToFloat64 `json:"delta"`
Gamma convert.StringToFloat64 `json:"gamma"`
Vega convert.StringToFloat64 `json:"vega"`
Theta convert.StringToFloat64 `json:"theta"`
PredictedDeliveryPrice convert.StringToFloat64 `json:"predictedDeliveryPrice"`
Change24h convert.StringToFloat64 `json:"change24h"`
TopBidImpliedVolatility types.Number `json:"bid1Iv"`
TopAskImpliedVolatility types.Number `json:"ask1Iv"`
MarkPrice types.Number `json:"markPrice"`
IndexPrice types.Number `json:"indexPrice"`
MarkImpliedVolatility types.Number `json:"markIv"`
UnderlyingPrice types.Number `json:"underlyingPrice"`
OpenInterest types.Number `json:"openInterest"`
TotalVolume types.Number `json:"totalVolume"`
TotalTurnover types.Number `json:"totalTurnover"`
Delta types.Number `json:"delta"`
Gamma types.Number `json:"gamma"`
Vega types.Number `json:"vega"`
Theta types.Number `json:"theta"`
PredictedDeliveryPrice types.Number `json:"predictedDeliveryPrice"`
Change24h types.Number `json:"change24h"`
// Inverse/linear fields
PrevPrice1h convert.StringToFloat64 `json:"prevPrice1h"`
OpenInterestValue convert.StringToFloat64 `json:"openInterestValue"`
FundingRate convert.StringToFloat64 `json:"fundingRate"`
NextFundingTime convert.StringToFloat64 `json:"nextFundingTime"`
BasisRate convert.StringToFloat64 `json:"basisRate"`
DeliveryFeeRate convert.StringToFloat64 `json:"deliveryFeeRate"`
DeliveryTime convert.StringToFloat64 `json:"deliveryTime"`
Basis convert.StringToFloat64 `json:"basis"`
PrevPrice1h types.Number `json:"prevPrice1h"`
OpenInterestValue types.Number `json:"openInterestValue"`
FundingRate types.Number `json:"fundingRate"`
NextFundingTime types.Number `json:"nextFundingTime"`
BasisRate types.Number `json:"basisRate"`
DeliveryFeeRate types.Number `json:"deliveryFeeRate"`
DeliveryTime types.Number `json:"deliveryTime"`
Basis types.Number `json:"basis"`
}
// Fee holds fee information
type Fee struct {
BaseCoin string `json:"baseCoin"`
Symbol string `json:"symbol"`
Taker convert.StringToFloat64 `json:"takerFeeRate"`
Maker convert.StringToFloat64 `json:"makerFeeRate"`
BaseCoin string `json:"baseCoin"`
Symbol string `json:"symbol"`
Taker types.Number `json:"takerFeeRate"`
Maker types.Number `json:"makerFeeRate"`
}
// AccountFee holds account fee information
@@ -995,37 +995,37 @@ type GetInstrumentInfoResponse struct {
// InstrumentInfo holds all instrument info across
// spot, linear, option types
type InstrumentInfo struct {
Symbol string `json:"symbol"`
ContractType string `json:"contractType"`
Innovation string `json:"innovation"`
MarginTrading string `json:"marginTrading"`
Status string `json:"status"`
BaseCoin string `json:"baseCoin"`
QuoteCoin string `json:"quoteCoin"`
OptionsType string `json:"optionsType"`
LaunchTime convert.StringToFloat64 `json:"launchTime"`
DeliveryTime convert.StringToFloat64 `json:"deliveryTime"`
DeliveryFeeRate convert.StringToFloat64 `json:"deliveryFeeRate"`
PriceScale convert.StringToFloat64 `json:"priceScale"`
Symbol string `json:"symbol"`
ContractType string `json:"contractType"`
Innovation string `json:"innovation"`
MarginTrading string `json:"marginTrading"`
Status string `json:"status"`
BaseCoin string `json:"baseCoin"`
QuoteCoin string `json:"quoteCoin"`
OptionsType string `json:"optionsType"`
LaunchTime types.Number `json:"launchTime"`
DeliveryTime types.Number `json:"deliveryTime"`
DeliveryFeeRate types.Number `json:"deliveryFeeRate"`
PriceScale types.Number `json:"priceScale"`
LeverageFilter struct {
MinLeverage convert.StringToFloat64 `json:"minLeverage"`
MaxLeverage convert.StringToFloat64 `json:"maxLeverage"`
LeverageStep convert.StringToFloat64 `json:"leverageStep"`
MinLeverage types.Number `json:"minLeverage"`
MaxLeverage types.Number `json:"maxLeverage"`
LeverageStep types.Number `json:"leverageStep"`
} `json:"leverageFilter"`
PriceFilter struct {
MinPrice convert.StringToFloat64 `json:"minPrice"`
MaxPrice convert.StringToFloat64 `json:"maxPrice"`
TickSize convert.StringToFloat64 `json:"tickSize"`
MinPrice types.Number `json:"minPrice"`
MaxPrice types.Number `json:"maxPrice"`
TickSize types.Number `json:"tickSize"`
} `json:"priceFilter"`
LotSizeFilter struct {
MaxOrderQty convert.StringToFloat64 `json:"maxOrderQty"`
MinOrderQty convert.StringToFloat64 `json:"minOrderQty"`
QtyStep convert.StringToFloat64 `json:"qtyStep"`
PostOnlyMaxOrderQty convert.StringToFloat64 `json:"postOnlyMaxOrderQty"`
BasePrecision convert.StringToFloat64 `json:"basePrecision"`
QuotePrecision convert.StringToFloat64 `json:"quotePrecision"`
MinOrderAmt convert.StringToFloat64 `json:"minOrderAmt"`
MaxOrderAmt convert.StringToFloat64 `json:"maxOrderAmt"`
MaxOrderQty types.Number `json:"maxOrderQty"`
MinOrderQty types.Number `json:"minOrderQty"`
QtyStep types.Number `json:"qtyStep"`
PostOnlyMaxOrderQty types.Number `json:"postOnlyMaxOrderQty"`
BasePrecision types.Number `json:"basePrecision"`
QuotePrecision types.Number `json:"quotePrecision"`
MinOrderAmt types.Number `json:"minOrderAmt"`
MaxOrderAmt types.Number `json:"maxOrderAmt"`
} `json:"lotSizeFilter"`
UnifiedMarginTrade bool `json:"unifiedMarginTrade"`
FundingInterval int64 `json:"fundingInterval"`

View File

@@ -12,13 +12,13 @@ import (
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"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/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
"github.com/thrasher-corp/gocryptotrader/types"
)
const (
@@ -888,7 +888,7 @@ func (by *Bybit) GetUSDCPosition(ctx context.Context, symbol currency.Pair, cate
func (by *Bybit) SetUSDCLeverage(ctx context.Context, symbol currency.Pair, leverage float64) (float64, error) {
resp := struct {
Result struct {
Leverage convert.StringToFloat64 `json:"leverage"`
Leverage types.Number `json:"leverage"`
} `json:"result"`
USDCError
}{}
@@ -1019,8 +1019,8 @@ func (by *Bybit) GetUSDCLastFundingRate(ctx context.Context, symbol currency.Pai
func (by *Bybit) GetUSDCPredictedFundingRate(ctx context.Context, symbol currency.Pair) (predictedFundingRate, predictedFundingFee float64, err error) {
resp := struct {
Result struct {
PredictedFundingRate convert.StringToFloat64 `json:"predictedFundingRate"`
PredictedFundingFee convert.StringToFloat64 `json:"predictedFundingFee"`
PredictedFundingRate types.Number `json:"predictedFundingRate"`
PredictedFundingFee types.Number `json:"predictedFundingFee"`
} `json:"result"`
USDCError
}{}

View File

@@ -3,7 +3,7 @@ package bybit
import (
"time"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/types"
)
var (
@@ -19,10 +19,10 @@ var (
// OrderbookData stores ob data for cmargined futures
type OrderbookData struct {
Symbol string `json:"symbol"`
Price convert.StringToFloat64 `json:"price"`
Size float64 `json:"size"`
Side string `json:"side"`
Symbol string `json:"symbol"`
Price types.Number `json:"price"`
Size float64 `json:"size"`
Side string `json:"side"`
}
// FuturesCandleStick holds kline data
@@ -41,46 +41,46 @@ type FuturesCandleStick struct {
// FuturesCandleStickWithStringParam holds kline data
type FuturesCandleStickWithStringParam struct {
ID int64 `json:"id"`
Symbol string `json:"symbol"`
Interval string `json:"interval"`
OpenTime int64 `json:"open_time"`
Open convert.StringToFloat64 `json:"open"`
High convert.StringToFloat64 `json:"high"`
Low convert.StringToFloat64 `json:"low"`
Close convert.StringToFloat64 `json:"close"`
Volume convert.StringToFloat64 `json:"volume"`
TurnOver convert.StringToFloat64 `json:"turnover"`
ID int64 `json:"id"`
Symbol string `json:"symbol"`
Interval string `json:"interval"`
OpenTime int64 `json:"open_time"`
Open types.Number `json:"open"`
High types.Number `json:"high"`
Low types.Number `json:"low"`
Close types.Number `json:"close"`
Volume types.Number `json:"volume"`
TurnOver types.Number `json:"turnover"`
}
// SymbolPriceTicker stores ticker price stats
type SymbolPriceTicker struct {
Symbol string `json:"symbol"`
BidPrice convert.StringToFloat64 `json:"bid_price"`
AskPrice convert.StringToFloat64 `json:"ask_price"`
LastPrice convert.StringToFloat64 `json:"last_price"`
LastTickDirection string `json:"last_tick_direction"`
Price24hAgo convert.StringToFloat64 `json:"prev_price_24h"`
PricePcntChange24h convert.StringToFloat64 `json:"price_24h_pcnt"`
HighPrice24h convert.StringToFloat64 `json:"high_price_24h"`
LowPrice24h convert.StringToFloat64 `json:"low_price_24h"`
Price1hAgo convert.StringToFloat64 `json:"prev_price_1h"`
PricePcntChange1h convert.StringToFloat64 `json:"price_1h_pcnt"`
MarkPrice convert.StringToFloat64 `json:"mark_price"`
IndexPrice convert.StringToFloat64 `json:"index_price"`
OpenInterest float64 `json:"open_interest"`
OpenValue convert.StringToFloat64 `json:"open_value"`
TotalTurnover convert.StringToFloat64 `json:"total_turnover"`
Turnover24h convert.StringToFloat64 `json:"turnover_24h"`
TotalVolume float64 `json:"total_volume"`
Volume24h float64 `json:"volume_24h"`
FundingRate convert.StringToFloat64 `json:"funding_rate"`
PredictedFundingRate convert.StringToFloat64 `json:"predicted_funding_rate"`
NextFundingTime string `json:"next_funding_time"`
CountdownHour int64 `json:"countdown_hour"`
DeliveryFeeRate convert.StringToFloat64 `json:"delivery_fee_rate"`
PredictedDeliveryPrice convert.StringToFloat64 `json:"predicted_delivery_price"`
DeliveryTime string `json:"delivery_time"`
Symbol string `json:"symbol"`
BidPrice types.Number `json:"bid_price"`
AskPrice types.Number `json:"ask_price"`
LastPrice types.Number `json:"last_price"`
LastTickDirection string `json:"last_tick_direction"`
Price24hAgo types.Number `json:"prev_price_24h"`
PricePcntChange24h types.Number `json:"price_24h_pcnt"`
HighPrice24h types.Number `json:"high_price_24h"`
LowPrice24h types.Number `json:"low_price_24h"`
Price1hAgo types.Number `json:"prev_price_1h"`
PricePcntChange1h types.Number `json:"price_1h_pcnt"`
MarkPrice types.Number `json:"mark_price"`
IndexPrice types.Number `json:"index_price"`
OpenInterest float64 `json:"open_interest"`
OpenValue types.Number `json:"open_value"`
TotalTurnover types.Number `json:"total_turnover"`
Turnover24h types.Number `json:"turnover_24h"`
TotalVolume float64 `json:"total_volume"`
Volume24h float64 `json:"volume_24h"`
FundingRate types.Number `json:"funding_rate"`
PredictedFundingRate types.Number `json:"predicted_funding_rate"`
NextFundingTime string `json:"next_funding_time"`
CountdownHour int64 `json:"countdown_hour"`
DeliveryFeeRate types.Number `json:"delivery_fee_rate"`
PredictedDeliveryPrice types.Number `json:"predicted_delivery_price"`
DeliveryTime string `json:"delivery_time"`
}
// FuturesPublicTradesData stores recent public trades for futures
@@ -105,14 +105,14 @@ type SymbolInfo struct {
MakerFee string `json:"maker_fee"`
FundingFeeInterval int64 `json:"funding_interval"`
LeverageFilter struct {
MinLeverage float64 `json:"min_leverage"`
MaxLeverage float64 `json:"max_leverage"`
LeverageStep convert.StringToFloat64 `json:"leverage_step"`
MinLeverage float64 `json:"min_leverage"`
MaxLeverage float64 `json:"max_leverage"`
LeverageStep types.Number `json:"leverage_step"`
} `json:"leverage_filter"`
PriceFilter struct {
MinPrice convert.StringToFloat64 `json:"min_price"`
MaxPrice convert.StringToFloat64 `json:"max_price"`
TickSize convert.StringToFloat64 `json:"tick_size"`
MinPrice types.Number `json:"min_price"`
MaxPrice types.Number `json:"max_price"`
TickSize types.Number `json:"tick_size"`
} `json:"price_filter"`
LotSizeFilter struct {
MinTradeQty float64 `json:"min_trading_qty"`
@@ -135,13 +135,13 @@ type MarkPriceKlineData struct {
// IndexPriceKlineData stores index price kline data
type IndexPriceKlineData struct {
Symbol string `json:"symbol"`
Interval string `json:"period"`
StartAt int64 `json:"open_time"`
Open convert.StringToFloat64 `json:"open"`
High convert.StringToFloat64 `json:"high"`
Low convert.StringToFloat64 `json:"low"`
Close convert.StringToFloat64 `json:"close"`
Symbol string `json:"symbol"`
Interval string `json:"period"`
StartAt int64 `json:"open_time"`
Open types.Number `json:"open"`
High types.Number `json:"high"`
Low types.Number `json:"low"`
Close types.Number `json:"close"`
}
// OpenInterestData stores open interest data
@@ -246,35 +246,35 @@ type FuturesRealtimeOrderData struct {
// FuturesActiveRealtimeOrder stores future active realtime order
type FuturesActiveRealtimeOrder struct {
FuturesRealtimeOrderData
ExtensionField map[string]interface{} `json:"ext_fields"`
LastExecutionTime string `json:"last_exec_time"`
LastExecutionPrice float64 `json:"last_exec_price"`
LeavesQty float64 `json:"leaves_qty"`
LeaveValue convert.StringToFloat64 `json:"leaves_value"`
CumulativeQty convert.StringToFloat64 `json:"cum_exec_qty"`
CumulativeValue convert.StringToFloat64 `json:"cum_exec_value"`
CumulativeFee convert.StringToFloat64 `json:"cum_exec_fee"`
RejectReason string `json:"reject_reason"`
CancelType string `json:"cancel_type"`
CreatedAt time.Time `json:"create_at"`
UpdatedAt time.Time `json:"updated_at"`
OrderID string `json:"order_id"`
ExtensionField map[string]interface{} `json:"ext_fields"`
LastExecutionTime string `json:"last_exec_time"`
LastExecutionPrice float64 `json:"last_exec_price"`
LeavesQty float64 `json:"leaves_qty"`
LeaveValue types.Number `json:"leaves_value"`
CumulativeQty types.Number `json:"cum_exec_qty"`
CumulativeValue types.Number `json:"cum_exec_value"`
CumulativeFee types.Number `json:"cum_exec_fee"`
RejectReason string `json:"reject_reason"`
CancelType string `json:"cancel_type"`
CreatedAt time.Time `json:"create_at"`
UpdatedAt time.Time `json:"updated_at"`
OrderID string `json:"order_id"`
}
// CoinFuturesConditionalRealtimeOrder stores CMF future coinditional realtime order
type CoinFuturesConditionalRealtimeOrder struct {
FuturesRealtimeOrderData
ExtensionField map[string]interface{} `json:"ext_fields"`
LeavesQty float64 `json:"leaves_qty"`
LeaveValue convert.StringToFloat64 `json:"leaves_value"`
CumulativeQty convert.StringToFloat64 `json:"cum_exec_qty"`
CumulativeValue convert.StringToFloat64 `json:"cum_exec_value"`
CumulativeFee convert.StringToFloat64 `json:"cum_exec_fee"`
RejectReason string `json:"reject_reason"`
CancelType string `json:"cancel_type"`
CreatedAt string `json:"create_at"`
UpdatedAt string `json:"updated_at"`
OrderID string `json:"order_id"`
ExtensionField map[string]interface{} `json:"ext_fields"`
LeavesQty float64 `json:"leaves_qty"`
LeaveValue types.Number `json:"leaves_value"`
CumulativeQty types.Number `json:"cum_exec_qty"`
CumulativeValue types.Number `json:"cum_exec_value"`
CumulativeFee types.Number `json:"cum_exec_fee"`
RejectReason string `json:"reject_reason"`
CancelType string `json:"cancel_type"`
CreatedAt string `json:"create_at"`
UpdatedAt string `json:"updated_at"`
OrderID string `json:"order_id"`
}
// FuturesConditionalRealtimeOrder stores future conditional realtime order
@@ -379,10 +379,10 @@ type FuturesCancelOrderData struct {
// FuturesCancelOrderResp stores future cancel order response
type FuturesCancelOrderResp struct {
FuturesCancelOrderData
StopOrderType string `json:"stop_order_type"`
TriggerBy string `json:"trigger_by"`
BasePrice convert.StringToFloat64 `json:"base_price"`
ExpectedDirection string `json:"expected_direction"`
StopOrderType string `json:"stop_order_type"`
TriggerBy string `json:"trigger_by"`
BasePrice types.Number `json:"base_price"`
ExpectedDirection string `json:"expected_direction"`
}
// RiskInfo stores risk information
@@ -401,23 +401,23 @@ type RiskInfo struct {
// RiskInfoWithStringParam stores risk information where string params
type RiskInfoWithStringParam struct {
ID int64 `json:"id"`
Symbol string `json:"symbol"`
Limit int64 `json:"limit"`
MaintainMargin convert.StringToFloat64 `json:"maintain_margin"`
StartingMargin convert.StringToFloat64 `json:"starting_margin"`
Section []string `json:"section"`
IsLowestRisk int64 `json:"is_lowest_risk"`
CreatedAt string `json:"create_at"`
UpdateAt string `json:"updated_at"`
MaxLeverage convert.StringToFloat64 `json:"max_leverage"`
ID int64 `json:"id"`
Symbol string `json:"symbol"`
Limit int64 `json:"limit"`
MaintainMargin types.Number `json:"maintain_margin"`
StartingMargin types.Number `json:"starting_margin"`
Section []string `json:"section"`
IsLowestRisk int64 `json:"is_lowest_risk"`
CreatedAt string `json:"create_at"`
UpdateAt string `json:"updated_at"`
MaxLeverage types.Number `json:"max_leverage"`
}
// FundingInfo stores funding information
type FundingInfo struct {
Symbol string `json:"symbol"`
FundingRate convert.StringToFloat64 `json:"funding_rate"`
FundingRateTimestamp int64 `json:"funding_rate_timestamp"`
Symbol string `json:"symbol"`
FundingRate types.Number `json:"funding_rate"`
FundingRateTimestamp int64 `json:"funding_rate_timestamp"`
}
// USDTFundingInfo stores USDT funding information
@@ -455,19 +455,19 @@ type Position struct {
// PositionWithStringParam stores position with string params
type PositionWithStringParam struct {
UserID int64 `json:"user_id"`
Symbol string `json:"symbol"`
Side string `json:"side"`
Size float64 `json:"size"`
PositionValue convert.StringToFloat64 `json:"position_value"`
EntryPrice convert.StringToFloat64 `json:"entry_price"`
LiquidationPrice convert.StringToFloat64 `json:"liq_price"`
BankruptcyPrice convert.StringToFloat64 `json:"bust_price"`
Leverage convert.StringToFloat64 `json:"leverage"`
PositionMargin convert.StringToFloat64 `json:"position_margin"`
OccupiedClosingFee convert.StringToFloat64 `json:"occ_closing_fee"`
RealisedPNL convert.StringToFloat64 `json:"realised_pnl"`
AccumulatedRealisedPNL convert.StringToFloat64 `json:"cum_realised_pnl"`
UserID int64 `json:"user_id"`
Symbol string `json:"symbol"`
Side string `json:"side"`
Size float64 `json:"size"`
PositionValue types.Number `json:"position_value"`
EntryPrice types.Number `json:"entry_price"`
LiquidationPrice types.Number `json:"liq_price"`
BankruptcyPrice types.Number `json:"bust_price"`
Leverage types.Number `json:"leverage"`
PositionMargin types.Number `json:"position_margin"`
OccupiedClosingFee types.Number `json:"occ_closing_fee"`
RealisedPNL types.Number `json:"realised_pnl"`
AccumulatedRealisedPNL types.Number `json:"cum_realised_pnl"`
}
// PositionData stores position data
@@ -486,54 +486,54 @@ type PositionData struct {
// PositionDataWithStringParam stores position data with string params
type PositionDataWithStringParam struct {
PositionWithStringParam
IsIsolated bool `json:"is_isolated"`
AutoAddMargin int64 `json:"auto_add_margin"`
UnrealisedPNL float64 `json:"unrealised_pnl"`
DeleverageIndicator int64 `json:"deleverage_indicator"`
RiskID int64 `json:"risk_id"`
TakeProfit convert.StringToFloat64 `json:"take_profit"`
StopLoss convert.StringToFloat64 `json:"stop_loss"`
TrailingStop convert.StringToFloat64 `json:"trailing_stop"`
IsIsolated bool `json:"is_isolated"`
AutoAddMargin int64 `json:"auto_add_margin"`
UnrealisedPNL float64 `json:"unrealised_pnl"`
DeleverageIndicator int64 `json:"deleverage_indicator"`
RiskID int64 `json:"risk_id"`
TakeProfit types.Number `json:"take_profit"`
StopLoss types.Number `json:"stop_loss"`
TrailingStop types.Number `json:"trailing_stop"`
}
// PositionResp stores position response
type PositionResp struct {
PositionDataWithStringParam
PositionID int64 `json:"position_idx"`
Mode int64 `json:"mode"`
ID int64 `json:"id"`
EffectiveLeverage convert.StringToFloat64 `json:"effective_leverage"`
OccupiedFundingFee convert.StringToFloat64 `json:"occ_funding_fee"`
PositionStatus string `json:"position_status"`
CalculatedData string `json:"oc_calc_data"`
OrderMargin convert.StringToFloat64 `json:"order_margin"`
WalletBalance convert.StringToFloat64 `json:"wallet_balance"`
CrossSequence int64 `json:"cross_seq"`
PositionSequence int64 `json:"position_seq"`
TakeProfitStopLossMode string `json:"tp_sl_mode"`
CreatedAt string `json:"created_at"`
UpdateAt string `json:"updated_at"`
PositionID int64 `json:"position_idx"`
Mode int64 `json:"mode"`
ID int64 `json:"id"`
EffectiveLeverage types.Number `json:"effective_leverage"`
OccupiedFundingFee types.Number `json:"occ_funding_fee"`
PositionStatus string `json:"position_status"`
CalculatedData string `json:"oc_calc_data"`
OrderMargin types.Number `json:"order_margin"`
WalletBalance types.Number `json:"wallet_balance"`
CrossSequence int64 `json:"cross_seq"`
PositionSequence int64 `json:"position_seq"`
TakeProfitStopLossMode string `json:"tp_sl_mode"`
CreatedAt string `json:"created_at"`
UpdateAt string `json:"updated_at"`
}
// SetTradingAndStopResp stores set trading and stop response
type SetTradingAndStopResp struct {
PositionData
ID int64 `json:"id"`
RiskID int64 `json:"risk_id"`
AutoAddMargin int64 `json:"auto_add_margin"`
OccupiedFundingFee convert.StringToFloat64 `json:"occ_funding_fee"`
TakeProfit convert.StringToFloat64 `json:"take_profit"`
StopLoss convert.StringToFloat64 `json:"stop_loss"`
PositionStatus string `json:"position_status"`
DeleverageIndicator int64 `json:"deleverage_indicator"`
CalculatedData string `json:"oc_calc_data"`
OrderMargin convert.StringToFloat64 `json:"order_margin"`
WalletBalance convert.StringToFloat64 `json:"wallet_balance"`
CrossSequence int64 `json:"cross_seq"`
PositionSequence int64 `json:"position_seq"`
CreatedAt string `json:"created_at"`
UpdateAt string `json:"updated_at"`
ExtensionField map[string]interface{} `json:"ext_fields"`
ID int64 `json:"id"`
RiskID int64 `json:"risk_id"`
AutoAddMargin int64 `json:"auto_add_margin"`
OccupiedFundingFee types.Number `json:"occ_funding_fee"`
TakeProfit types.Number `json:"take_profit"`
StopLoss types.Number `json:"stop_loss"`
PositionStatus string `json:"position_status"`
DeleverageIndicator int64 `json:"deleverage_indicator"`
CalculatedData string `json:"oc_calc_data"`
OrderMargin types.Number `json:"order_margin"`
WalletBalance types.Number `json:"wallet_balance"`
CrossSequence int64 `json:"cross_seq"`
PositionSequence int64 `json:"position_seq"`
CreatedAt string `json:"created_at"`
UpdateAt string `json:"updated_at"`
ExtensionField map[string]interface{} `json:"ext_fields"`
}
// USDTPositionResp stores USDT position response
@@ -551,24 +551,24 @@ type UpdateMarginResp struct {
// TradeData stores trade data
type TradeData struct {
OrderID string `json:"order_id"`
OrderLinkedID string `json:"order_link_id"`
OrderSide string `json:"side"`
Symbol string `json:"symbol"`
ExecutionID string `json:"exec_id"`
OrderPrice float64 `json:"order_price"`
OrderQty float64 `json:"order_qty"`
OrderType string `json:"order_type"`
FeeRate float64 `json:"fee_rate"`
ExecutionFee convert.StringToFloat64 `json:"exec_fee"`
ExecutionPrice convert.StringToFloat64 `json:"exec_price"`
ExecutionQty float64 `json:"exec_qty"`
ExecutionType string `json:"exec_type"`
ExecutionValue convert.StringToFloat64 `json:"exec_value"`
LeavesQty float64 `json:"leaves_qty"`
ClosedSize float64 `json:"closed_size"`
LastLiquidity string `json:"last_liquidity_ind"`
TradeTimeMs int64 `json:"trade_time_ms"`
OrderID string `json:"order_id"`
OrderLinkedID string `json:"order_link_id"`
OrderSide string `json:"side"`
Symbol string `json:"symbol"`
ExecutionID string `json:"exec_id"`
OrderPrice float64 `json:"order_price"`
OrderQty float64 `json:"order_qty"`
OrderType string `json:"order_type"`
FeeRate float64 `json:"fee_rate"`
ExecutionFee types.Number `json:"exec_fee"`
ExecutionPrice types.Number `json:"exec_price"`
ExecutionQty float64 `json:"exec_qty"`
ExecutionType string `json:"exec_type"`
ExecutionValue types.Number `json:"exec_value"`
LeavesQty float64 `json:"leaves_qty"`
ClosedSize float64 `json:"closed_size"`
LastLiquidity string `json:"last_liquidity_ind"`
TradeTimeMs int64 `json:"trade_time_ms"`
}
// TradeResp stores trade response
@@ -654,30 +654,30 @@ type WalletData struct {
// FundRecord stores funding records
type FundRecord struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Coin string `json:"coin"`
Type string `json:"type"`
Amount convert.StringToFloat64 `json:"amount"`
TxID string `json:"tx_id"`
Address string `json:"address"`
WalletBalance convert.StringToFloat64 `json:"wallet_balance"`
ExecutionTime string `json:"exec_time"`
CrossSequence int64 `json:"cross_seq"`
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Coin string `json:"coin"`
Type string `json:"type"`
Amount types.Number `json:"amount"`
TxID string `json:"tx_id"`
Address string `json:"address"`
WalletBalance types.Number `json:"wallet_balance"`
ExecutionTime string `json:"exec_time"`
CrossSequence int64 `json:"cross_seq"`
}
// FundWithdrawalRecord stores funding withdrawal records
type FundWithdrawalRecord struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Coin string `json:"coin"`
Status string `json:"status"`
Amount convert.StringToFloat64 `json:"amount"`
Fee float64 `json:"fee"`
Address string `json:"address"`
TxID string `json:"tx_id"`
SubmittedAt time.Time `json:"submited_at"`
UpdatedAt time.Time `json:"updated_at"`
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Coin string `json:"coin"`
Status string `json:"status"`
Amount types.Number `json:"amount"`
Fee float64 `json:"fee"`
Address string `json:"address"`
TxID string `json:"tx_id"`
SubmittedAt time.Time `json:"submited_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// AssetExchangeRecord stores asset exchange records
@@ -694,79 +694,79 @@ type AssetExchangeRecord struct {
// USDCOrderbookData stores orderbook data for USDCMarginedFutures
type USDCOrderbookData struct {
Price convert.StringToFloat64 `json:"price"`
Size convert.StringToFloat64 `json:"size"`
Side string `json:"side"`
Price types.Number `json:"price"`
Size types.Number `json:"size"`
Side string `json:"side"`
}
// USDCContract stores contract data
type USDCContract struct {
Symbol string `json:"symbol"`
Status string `json:"status"`
BaseCoin string `json:"baseCoin"`
QuoteCoin string `json:"quoteCoin"`
TakerFeeRate convert.StringToFloat64 `json:"takerFeeRate"`
MakerFeeRate convert.StringToFloat64 `json:"makerFeeRate"`
MinLeverage convert.StringToFloat64 `json:"minLeverage"`
MaxLeverage convert.StringToFloat64 `json:"maxLeverage"`
LeverageStep convert.StringToFloat64 `json:"leverageStep"`
MinPrice convert.StringToFloat64 `json:"minPrice"`
MaxPrice convert.StringToFloat64 `json:"maxPrice"`
TickSize convert.StringToFloat64 `json:"tickSize"`
MaxTradingQty convert.StringToFloat64 `json:"maxTradingQty"`
MinTradingQty convert.StringToFloat64 `json:"minTradingQty"`
QtyStep convert.StringToFloat64 `json:"qtyStep"`
DeliveryTime bybitTimeMilliSecStr `json:"deliveryTime"`
Symbol string `json:"symbol"`
Status string `json:"status"`
BaseCoin string `json:"baseCoin"`
QuoteCoin string `json:"quoteCoin"`
TakerFeeRate types.Number `json:"takerFeeRate"`
MakerFeeRate types.Number `json:"makerFeeRate"`
MinLeverage types.Number `json:"minLeverage"`
MaxLeverage types.Number `json:"maxLeverage"`
LeverageStep types.Number `json:"leverageStep"`
MinPrice types.Number `json:"minPrice"`
MaxPrice types.Number `json:"maxPrice"`
TickSize types.Number `json:"tickSize"`
MaxTradingQty types.Number `json:"maxTradingQty"`
MinTradingQty types.Number `json:"minTradingQty"`
QtyStep types.Number `json:"qtyStep"`
DeliveryTime bybitTimeMilliSecStr `json:"deliveryTime"`
}
// USDCSymbol stores symbol data
type USDCSymbol struct {
Symbol string `json:"symbol"`
NextFundingTime string `json:"nextFundingTime"`
Bid convert.StringToFloat64 `json:"bid"`
BidSize convert.StringToFloat64 `json:"bidSize"`
Ask convert.StringToFloat64 `json:"ask"`
AskSize convert.StringToFloat64 `json:"askSize"`
LastPrice convert.StringToFloat64 `json:"lastPrice"`
OpenInterest convert.StringToFloat64 `json:"openInterest"`
IndexPrice convert.StringToFloat64 `json:"indexPrice"`
MarkPrice convert.StringToFloat64 `json:"markPrice"`
Change24h convert.StringToFloat64 `json:"change24h"`
High24h convert.StringToFloat64 `json:"high24h"`
Low24h convert.StringToFloat64 `json:"low24h"`
Volume24h convert.StringToFloat64 `json:"volume24h"`
Turnover24h convert.StringToFloat64 `json:"turnover24h"`
TotalVolume convert.StringToFloat64 `json:"totalVolume"`
TotalTurnover convert.StringToFloat64 `json:"totalTurnover"`
FundingRate convert.StringToFloat64 `json:"fundingRate"`
PredictedFundingRate convert.StringToFloat64 `json:"predictedFundingRate"`
CountdownHour convert.StringToFloat64 `json:"countdownHour"`
UnderlyingPrice string `json:"underlyingPrice"`
Symbol string `json:"symbol"`
NextFundingTime string `json:"nextFundingTime"`
Bid types.Number `json:"bid"`
BidSize types.Number `json:"bidSize"`
Ask types.Number `json:"ask"`
AskSize types.Number `json:"askSize"`
LastPrice types.Number `json:"lastPrice"`
OpenInterest types.Number `json:"openInterest"`
IndexPrice types.Number `json:"indexPrice"`
MarkPrice types.Number `json:"markPrice"`
Change24h types.Number `json:"change24h"`
High24h types.Number `json:"high24h"`
Low24h types.Number `json:"low24h"`
Volume24h types.Number `json:"volume24h"`
Turnover24h types.Number `json:"turnover24h"`
TotalVolume types.Number `json:"totalVolume"`
TotalTurnover types.Number `json:"totalTurnover"`
FundingRate types.Number `json:"fundingRate"`
PredictedFundingRate types.Number `json:"predictedFundingRate"`
CountdownHour types.Number `json:"countdownHour"`
UnderlyingPrice string `json:"underlyingPrice"`
}
// USDCKlineBase stores Kline Base
type USDCKlineBase struct {
Symbol string `json:"symbol"`
Period string `json:"period"`
OpenTime bybitTimeSecStr `json:"openTime"`
Open convert.StringToFloat64 `json:"open"`
High convert.StringToFloat64 `json:"high"`
Low convert.StringToFloat64 `json:"low"`
Close convert.StringToFloat64 `json:"close"`
Symbol string `json:"symbol"`
Period string `json:"period"`
OpenTime bybitTimeSecStr `json:"openTime"`
Open types.Number `json:"open"`
High types.Number `json:"high"`
Low types.Number `json:"low"`
Close types.Number `json:"close"`
}
// USDCKline stores kline data
type USDCKline struct {
USDCKlineBase
Volume convert.StringToFloat64 `json:"volume"`
Turnover convert.StringToFloat64 `json:"turnover"`
Volume types.Number `json:"volume"`
Turnover types.Number `json:"turnover"`
}
// USDCOpenInterest stores open interest data
type USDCOpenInterest struct {
Symbol string `json:"symbol"`
Timestamp bybitTimeMilliSecStr `json:"timestamp"`
OpenInterest convert.StringToFloat64 `json:"openInterest"`
Symbol string `json:"symbol"`
Timestamp bybitTimeMilliSecStr `json:"timestamp"`
OpenInterest types.Number `json:"openInterest"`
}
// USDCLargeOrder stores large order data
@@ -787,191 +787,191 @@ type USDCAccountRatio struct {
// USDCTrade stores trade data
type USDCTrade struct {
ID string `json:"id"`
Symbol string `json:"symbol"`
OrderPrice convert.StringToFloat64 `json:"orderPrice"`
OrderQty convert.StringToFloat64 `json:"orderQty"`
Side string `json:"side"`
Timestamp bybitTimeMilliSecStr `json:"time"`
ID string `json:"id"`
Symbol string `json:"symbol"`
OrderPrice types.Number `json:"orderPrice"`
OrderQty types.Number `json:"orderQty"`
Side string `json:"side"`
Timestamp bybitTimeMilliSecStr `json:"time"`
}
// USDCCreateOrderResp stores create order response
type USDCCreateOrderResp struct {
ID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Symbol string `json:"symbol"`
OrderPrice convert.StringToFloat64 `json:"orderPrice"`
OrderQty convert.StringToFloat64 `json:"orderQty"`
OrderType string `json:"orderType"`
Side string `json:"side"`
ID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Symbol string `json:"symbol"`
OrderPrice types.Number `json:"orderPrice"`
OrderQty types.Number `json:"orderQty"`
OrderType string `json:"orderType"`
Side string `json:"side"`
}
// USDCOrder store order data
type USDCOrder struct {
ID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Symbol string `json:"symbol"`
OrderType string `json:"orderType"`
Side string `json:"side"`
Qty convert.StringToFloat64 `json:"qty"`
Price convert.StringToFloat64 `json:"price"`
TimeInForce string `json:"timeInForce"`
TotalOrderValue convert.StringToFloat64 `json:"cumExecValue"`
TotalFilledQty convert.StringToFloat64 `json:"cumExecQty"`
TotalFee convert.StringToFloat64 `json:"cumExecFee"`
InitialMargin string `json:"orderIM"`
OrderStatus string `json:"orderStatus"`
TakeProfit convert.StringToFloat64 `json:"takeProfit"`
StopLoss convert.StringToFloat64 `json:"stopLoss"`
TPTriggerBy string `json:"tpTriggerBy"`
SLTriggerBy string `json:"slTriggerBy"`
LastExecPrice float64 `json:"lastExecPrice"`
BasePrice string `json:"basePrice"`
TriggerPrice convert.StringToFloat64 `json:"triggerPrice"`
TriggerBy string `json:"triggerBy"`
ReduceOnly bool `json:"reduceOnly"`
StopOrderType string `json:"stopOrderType"`
CloseOnTrigger string `json:"closeOnTrigger"`
CreatedAt bybitTimeMilliSecStr `json:"createdAt"`
ID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Symbol string `json:"symbol"`
OrderType string `json:"orderType"`
Side string `json:"side"`
Qty types.Number `json:"qty"`
Price types.Number `json:"price"`
TimeInForce string `json:"timeInForce"`
TotalOrderValue types.Number `json:"cumExecValue"`
TotalFilledQty types.Number `json:"cumExecQty"`
TotalFee types.Number `json:"cumExecFee"`
InitialMargin string `json:"orderIM"`
OrderStatus string `json:"orderStatus"`
TakeProfit types.Number `json:"takeProfit"`
StopLoss types.Number `json:"stopLoss"`
TPTriggerBy string `json:"tpTriggerBy"`
SLTriggerBy string `json:"slTriggerBy"`
LastExecPrice float64 `json:"lastExecPrice"`
BasePrice string `json:"basePrice"`
TriggerPrice types.Number `json:"triggerPrice"`
TriggerBy string `json:"triggerBy"`
ReduceOnly bool `json:"reduceOnly"`
StopOrderType string `json:"stopOrderType"`
CloseOnTrigger string `json:"closeOnTrigger"`
CreatedAt bybitTimeMilliSecStr `json:"createdAt"`
}
// USDCOrderHistory stores order history
type USDCOrderHistory struct {
USDCOrder
LeavesQty convert.StringToFloat64 `json:"leavesQty"` // Est. unfilled order qty
CashFlow string `json:"cashFlow"`
RealisedPnl convert.StringToFloat64 `json:"realisedPnl"`
UpdatedAt bybitTimeMilliSecStr `json:"updatedAt"`
LeavesQty types.Number `json:"leavesQty"` // Est. unfilled order qty
CashFlow string `json:"cashFlow"`
RealisedPnl types.Number `json:"realisedPnl"`
UpdatedAt bybitTimeMilliSecStr `json:"updatedAt"`
}
// USDCTradeHistory stores trade history
type USDCTradeHistory struct {
ID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Symbol string `json:"symbol"`
Side string `json:"side"`
TradeID string `json:"tradeId"`
ExecPrice convert.StringToFloat64 `json:"execPrice"`
ExecQty convert.StringToFloat64 `json:"execQty"`
ExecFee convert.StringToFloat64 `json:"execFee"`
FeeRate convert.StringToFloat64 `json:"feeRate"`
ExecType string `json:"execType"`
ExecValue convert.StringToFloat64 `json:"execValue"`
TradeTime bybitTimeMilliSecStr `json:"tradeTime"`
LastLiquidityInd string `json:"lastLiquidityInd"`
ID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Symbol string `json:"symbol"`
Side string `json:"side"`
TradeID string `json:"tradeId"`
ExecPrice types.Number `json:"execPrice"`
ExecQty types.Number `json:"execQty"`
ExecFee types.Number `json:"execFee"`
FeeRate types.Number `json:"feeRate"`
ExecType string `json:"execType"`
ExecValue types.Number `json:"execValue"`
TradeTime bybitTimeMilliSecStr `json:"tradeTime"`
LastLiquidityInd string `json:"lastLiquidityInd"`
}
// USDCTxLog stores transaction log data
type USDCTxLog struct {
TxTime bybitTimeMilliSecStr `json:"transactionTime"`
Symbol string `json:"symbol"`
Type string `json:"type"`
Side string `json:"side"`
Quantity convert.StringToFloat64 `json:"qty"`
Size convert.StringToFloat64 `json:"size"`
TradePrice convert.StringToFloat64 `json:"tradePrice"`
Funding convert.StringToFloat64 `json:"funding"`
Fee convert.StringToFloat64 `json:"fee"`
CashFlow string `json:"cashFlow"`
Change convert.StringToFloat64 `json:"change"`
WalletBalance convert.StringToFloat64 `json:"walletBalance"`
FeeRate convert.StringToFloat64 `json:"feeRate"`
TradeID string `json:"tradeId"`
OrderID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Info string `json:"info"`
TxTime bybitTimeMilliSecStr `json:"transactionTime"`
Symbol string `json:"symbol"`
Type string `json:"type"`
Side string `json:"side"`
Quantity types.Number `json:"qty"`
Size types.Number `json:"size"`
TradePrice types.Number `json:"tradePrice"`
Funding types.Number `json:"funding"`
Fee types.Number `json:"fee"`
CashFlow string `json:"cashFlow"`
Change types.Number `json:"change"`
WalletBalance types.Number `json:"walletBalance"`
FeeRate types.Number `json:"feeRate"`
TradeID string `json:"tradeId"`
OrderID string `json:"orderId"`
OrderLinkID string `json:"orderLinkId"`
Info string `json:"info"`
}
// USDCWalletBalance store USDC wallet balance
type USDCWalletBalance struct {
Equity convert.StringToFloat64 `json:"equity"`
WalletBalance convert.StringToFloat64 `json:"walletBalance"`
AvailableBalance convert.StringToFloat64 `json:"availableBalance"`
AccountIM convert.StringToFloat64 `json:"accountIM"`
AccountMM convert.StringToFloat64 `json:"accountMM"`
TotalRPL convert.StringToFloat64 `json:"totalRPL"`
TotalSessionUPL convert.StringToFloat64 `json:"totalSessionUPL"`
TotalSessionRPL convert.StringToFloat64 `json:"totalSessionRPL"`
Equity types.Number `json:"equity"`
WalletBalance types.Number `json:"walletBalance"`
AvailableBalance types.Number `json:"availableBalance"`
AccountIM types.Number `json:"accountIM"`
AccountMM types.Number `json:"accountMM"`
TotalRPL types.Number `json:"totalRPL"`
TotalSessionUPL types.Number `json:"totalSessionUPL"`
TotalSessionRPL types.Number `json:"totalSessionRPL"`
}
// USDCAssetInfo stores USDC asset data
type USDCAssetInfo struct {
BaseCoin string `json:"baseCoin"`
TotalDelta convert.StringToFloat64 `json:"totalDelta"`
TotalGamma convert.StringToFloat64 `json:"totalGamma"`
TotalVega convert.StringToFloat64 `json:"totalVega"`
TotalTheta convert.StringToFloat64 `json:"totalTheta"`
TotalRPL convert.StringToFloat64 `json:"totalRPL"`
SessionUPL convert.StringToFloat64 `json:"sessionUPL"`
SessionRPL convert.StringToFloat64 `json:"sessionRPL"`
IM convert.StringToFloat64 `json:"im"`
MM convert.StringToFloat64 `json:"mm"`
BaseCoin string `json:"baseCoin"`
TotalDelta types.Number `json:"totalDelta"`
TotalGamma types.Number `json:"totalGamma"`
TotalVega types.Number `json:"totalVega"`
TotalTheta types.Number `json:"totalTheta"`
TotalRPL types.Number `json:"totalRPL"`
SessionUPL types.Number `json:"sessionUPL"`
SessionRPL types.Number `json:"sessionRPL"`
IM types.Number `json:"im"`
MM types.Number `json:"mm"`
}
// USDCPosition store USDC position data
type USDCPosition struct {
Symbol string `json:"symbol"`
Leverage convert.StringToFloat64 `json:"leverage"`
ClosingFee convert.StringToFloat64 `json:"occClosingFee"`
LiquidPrice string `json:"liqPrice"`
Position float64 `json:"positionValue"`
TakeProfit convert.StringToFloat64 `json:"takeProfit"`
RiskID string `json:"riskId"`
TrailingStop convert.StringToFloat64 `json:"trailingStop"`
UnrealisedPnl convert.StringToFloat64 `json:"unrealisedPnl"`
MarkPrice convert.StringToFloat64 `json:"markPrice"`
CumRealisedPnl convert.StringToFloat64 `json:"cumRealisedPnl"`
PositionMM convert.StringToFloat64 `json:"positionMM"`
PositionIM convert.StringToFloat64 `json:"positionIM"`
EntryPrice convert.StringToFloat64 `json:"entryPrice"`
Size convert.StringToFloat64 `json:"size"`
SessionRPL convert.StringToFloat64 `json:"sessionRPL"`
SessionUPL convert.StringToFloat64 `json:"sessionUPL"`
StopLoss convert.StringToFloat64 `json:"stopLoss"`
OrderMargin convert.StringToFloat64 `json:"orderMargin"`
SessionAvgPrice convert.StringToFloat64 `json:"sessionAvgPrice"`
CreatedAt bybitTimeMilliSecStr `json:"createdAt"`
UpdatedAt bybitTimeMilliSecStr `json:"updatedAt"`
TpSLMode string `json:"tpSLMode"`
Side string `json:"side"`
BustPrice string `json:"bustPrice"`
PositionStatus string `json:"positionStatus"`
DeleverageIndicator int64 `json:"deleverageIndicator"`
Symbol string `json:"symbol"`
Leverage types.Number `json:"leverage"`
ClosingFee types.Number `json:"occClosingFee"`
LiquidPrice string `json:"liqPrice"`
Position float64 `json:"positionValue"`
TakeProfit types.Number `json:"takeProfit"`
RiskID string `json:"riskId"`
TrailingStop types.Number `json:"trailingStop"`
UnrealisedPnl types.Number `json:"unrealisedPnl"`
MarkPrice types.Number `json:"markPrice"`
CumRealisedPnl types.Number `json:"cumRealisedPnl"`
PositionMM types.Number `json:"positionMM"`
PositionIM types.Number `json:"positionIM"`
EntryPrice types.Number `json:"entryPrice"`
Size types.Number `json:"size"`
SessionRPL types.Number `json:"sessionRPL"`
SessionUPL types.Number `json:"sessionUPL"`
StopLoss types.Number `json:"stopLoss"`
OrderMargin types.Number `json:"orderMargin"`
SessionAvgPrice types.Number `json:"sessionAvgPrice"`
CreatedAt bybitTimeMilliSecStr `json:"createdAt"`
UpdatedAt bybitTimeMilliSecStr `json:"updatedAt"`
TpSLMode string `json:"tpSLMode"`
Side string `json:"side"`
BustPrice string `json:"bustPrice"`
PositionStatus string `json:"positionStatus"`
DeleverageIndicator int64 `json:"deleverageIndicator"`
}
// USDCSettlementHistory store USDC settlement history data
type USDCSettlementHistory struct {
Symbol string `json:"symbol"`
Side string `json:"side"`
Time bybitTimeMilliSecStr `json:"time"`
Size convert.StringToFloat64 `json:"size"`
SessionAvgPrice convert.StringToFloat64 `json:"sessionAvgPrice"`
MarkPrice convert.StringToFloat64 `json:"markPrice"`
SessionRpl convert.StringToFloat64 `json:"sessionRpl"`
Symbol string `json:"symbol"`
Side string `json:"side"`
Time bybitTimeMilliSecStr `json:"time"`
Size types.Number `json:"size"`
SessionAvgPrice types.Number `json:"sessionAvgPrice"`
MarkPrice types.Number `json:"markPrice"`
SessionRpl types.Number `json:"sessionRpl"`
}
// USDCRiskLimit store USDC risk limit data
type USDCRiskLimit struct {
RiskID string `json:"riskId"`
Symbol string `json:"symbol"`
Limit string `json:"limit"`
Section []string `json:"section"`
StartingMargin convert.StringToFloat64 `json:"startingMargin"`
MaintainMargin convert.StringToFloat64 `json:"maintainMargin"`
IsLowestRisk bool `json:"isLowestRisk"`
MaxLeverage convert.StringToFloat64 `json:"maxLeverage"`
RiskID string `json:"riskId"`
Symbol string `json:"symbol"`
Limit string `json:"limit"`
Section []string `json:"section"`
StartingMargin types.Number `json:"startingMargin"`
MaintainMargin types.Number `json:"maintainMargin"`
IsLowestRisk bool `json:"isLowestRisk"`
MaxLeverage types.Number `json:"maxLeverage"`
}
// USDCFundingInfo store USDC funding data
type USDCFundingInfo struct {
Symbol string `json:"symbol"`
Time bybitTimeMilliSecStr `json:"fundingRateTimestamp"`
Rate convert.StringToFloat64 `json:"fundingRate"`
Symbol string `json:"symbol"`
Time bybitTimeMilliSecStr `json:"fundingRateTimestamp"`
Rate types.Number `json:"fundingRate"`
}
// CFuturesTradingFeeRate stores trading fee rate
type CFuturesTradingFeeRate struct {
TakerFeeRate convert.StringToFloat64 `json:"taker_fee_rate"`
MakerFeeRate convert.StringToFloat64 `json:"maker_fee_rate"`
UserID int64 `json:"user_id"`
TakerFeeRate types.Number `json:"taker_fee_rate"`
MakerFeeRate types.Number `json:"maker_fee_rate"`
UserID int64 `json:"user_id"`
}

View File

@@ -3407,7 +3407,7 @@ func TestForceFileStandard(t *testing.T) {
t.Error(err)
}
if t.Failed() {
t.Fatal("Please use convert.StringToFloat64 type instead of `float64` and remove `,string` as strings can be empty in unmarshal process. Then call the Float64() method.")
t.Fatal("Please use types.Number type instead of `float64` and remove `,string` as strings can be empty in unmarshal process. Then call the Float64() method.")
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -13,7 +13,6 @@ import (
"github.com/shopspring/decimal"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/config"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
@@ -32,6 +31,7 @@ import (
"github.com/thrasher-corp/gocryptotrader/exchanges/trade"
"github.com/thrasher-corp/gocryptotrader/log"
"github.com/thrasher-corp/gocryptotrader/portfolio/withdraw"
"github.com/thrasher-corp/gocryptotrader/types"
)
// GetDefaultConfig returns a default exchange config
@@ -1048,8 +1048,8 @@ func (g *Gateio) SubmitOrder(ctx context.Context, s *order.Submit) (*order.Submi
Side: orderTypeFormat,
Type: s.Type.Lower(),
Account: g.assetTypeToString(s.AssetType),
Amount: convert.StringToFloat64(s.Amount),
Price: convert.StringToFloat64(s.Price),
Amount: types.Number(s.Amount),
Price: types.Number(s.Price),
CurrencyPair: s.Pair,
Text: s.ClientOrderID,
})
@@ -1091,7 +1091,7 @@ func (g *Gateio) SubmitOrder(ctx context.Context, s *order.Submit) (*order.Submi
fOrder, err := g.PlaceFuturesOrder(ctx, &OrderCreateParams{
Contract: s.Pair,
Size: s.Amount,
Price: convert.StringToFloat64(s.Price),
Price: types.Number(s.Price),
Settle: settle,
ReduceOnly: s.ReduceOnly,
TimeInForce: "gtc",
@@ -1128,7 +1128,7 @@ func (g *Gateio) SubmitOrder(ctx context.Context, s *order.Submit) (*order.Submi
newOrder, err := g.PlaceDeliveryOrder(ctx, &OrderCreateParams{
Contract: s.Pair,
Size: s.Amount,
Price: convert.StringToFloat64(s.Price),
Price: types.Number(s.Price),
Settle: settle,
ReduceOnly: s.ReduceOnly,
TimeInForce: "gtc",
@@ -1156,7 +1156,7 @@ func (g *Gateio) SubmitOrder(ctx context.Context, s *order.Submit) (*order.Submi
optionOrder, err := g.PlaceOptionOrder(ctx, OptionOrderParam{
Contract: s.Pair.String(),
OrderSize: s.Amount,
Price: convert.StringToFloat64(s.Price),
Price: types.Number(s.Price),
ReduceOnly: s.ReduceOnly,
Text: s.ClientOrderID,
})
@@ -1544,7 +1544,7 @@ func (g *Gateio) WithdrawCryptocurrencyFunds(ctx context.Context, withdrawReques
}
response, err := g.WithdrawCurrency(ctx,
WithdrawalRequestParam{
Amount: convert.StringToFloat64(withdrawRequest.Amount),
Amount: types.Number(withdrawRequest.Amount),
Currency: withdrawRequest.Currency,
Address: withdrawRequest.Crypto.Address,
Chain: withdrawRequest.Crypto.Chain,

View File

@@ -1,8 +1,8 @@
package gemini
import (
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/types"
)
const (
@@ -32,17 +32,17 @@ type Ticker struct {
// SymbolDetails contains additional symbol details
type SymbolDetails struct {
Symbol string `json:"symbol"`
BaseCurrency string `json:"base_currency"`
QuoteCurrency string `json:"quote_currency"`
TickSize float64 `json:"tick_size"`
QuoteIncrement float64 `json:"quote_increment"`
MinOrderSize convert.StringToFloat64 `json:"min_order_size"`
Status string `json:"status"`
WrapEnabled bool `json:"wrap_enabled"`
ProductType string `json:"product_type"`
ContractType string `json:"contract_type"`
ContractPriceCurrency string `json:"contract_price_currency"`
Symbol string `json:"symbol"`
BaseCurrency string `json:"base_currency"`
QuoteCurrency string `json:"quote_currency"`
TickSize float64 `json:"tick_size"`
QuoteIncrement float64 `json:"quote_increment"`
MinOrderSize types.Number `json:"min_order_size"`
Status string `json:"status"`
WrapEnabled bool `json:"wrap_enabled"`
ProductType string `json:"product_type"`
ContractType string `json:"contract_type"`
ContractPriceCurrency string `json:"contract_price_currency"`
}
// TickerV2 holds returned ticker data from the exchange

View File

@@ -5,6 +5,7 @@ import (
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/types"
)
var (
@@ -74,17 +75,17 @@ type Contract struct {
// FuturesTicker stores ticker data
type FuturesTicker struct {
Sequence int64 `json:"sequence"`
Symbol string `json:"symbol"`
Side order.Side `json:"side"`
Size float64 `json:"size"`
Price convert.StringToFloat64 `json:"price"`
BestBidSize float64 `json:"bestBidSize"`
BestBidPrice convert.StringToFloat64 `json:"bestBidPrice"`
BestAskSize float64 `json:"bestAskSize"`
BestAskPrice convert.StringToFloat64 `json:"bestAskPrice"`
TradeID string `json:"tradeId"`
FilledTime convert.ExchangeTime `json:"ts"`
Sequence int64 `json:"sequence"`
Symbol string `json:"symbol"`
Side order.Side `json:"side"`
Size float64 `json:"size"`
Price types.Number `json:"price"`
BestBidSize float64 `json:"bestBidSize"`
BestBidPrice types.Number `json:"bestBidPrice"`
BestAskSize float64 `json:"bestAskSize"`
BestAskPrice types.Number `json:"bestAskPrice"`
TradeID string `json:"tradeId"`
FilledTime convert.ExchangeTime `json:"ts"`
}
type futuresOrderbookResponse struct {

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

73
types/number.go Normal file
View File

@@ -0,0 +1,73 @@
package types
import (
"errors"
"fmt"
"strconv"
"github.com/shopspring/decimal"
)
var errInvalidNumberValue = errors.New("invalid value for Number type")
// Number represents a floating point number, and implements json.Unmarshaller and json.Marshaller
type Number float64
// UnmarshalJSON implements json.Unmarshaler
func (f *Number) UnmarshalJSON(data []byte) error {
switch c := data[0]; c { // From json.decode literalInterface
case 'n', 't', 'f': // null, true, false
return fmt.Errorf("%w: %s", errInvalidNumberValue, data)
case '"': // string
if len(data) < 2 || data[len(data)-1] != '"' {
return fmt.Errorf("%w: %s", errInvalidNumberValue, data)
}
data = data[1 : len(data)-1] // Naive Unquote
default: // Should be a number
if c != '-' && (c < '0' || c > '9') { // Invalid json syntax
return fmt.Errorf("%w: %s", errInvalidNumberValue, data)
}
}
if len(data) == 0 {
*f = Number(0)
return nil
}
val, err := strconv.ParseFloat(string(data), 64)
if err != nil {
return fmt.Errorf("%w: %s", errInvalidNumberValue, data) // We don't use err; We know it's not valid and errInvalidNumberValue is clearer
}
*f = Number(val)
return nil
}
// MarshalJSON implements json.Marshaler by formatting to a json string
// 1337.37 will marshal to "1337.37"
// 0 will marshal to an empty string: ""
func (f Number) MarshalJSON() ([]byte, error) {
if f == 0 {
return []byte(`""`), nil
}
val := strconv.FormatFloat(float64(f), 'f', -1, 64)
return []byte(`"` + val + `"`), nil
}
// Float64 returns the underlying float64
func (f Number) Float64() float64 {
return float64(f)
}
// Int64 returns the truncated integer component of the number
func (f Number) Int64() int64 {
// It's likely this is sufficient, since Numbers probably have not had floating point math performed on them
// However if issues arise then we can switch to math.Round
return int64(f)
}
// Decimal returns a decimal.Decimal
func (f Number) Decimal() decimal.Decimal {
return decimal.NewFromFloat(float64(f))
}

83
types/number_test.go Normal file
View File

@@ -0,0 +1,83 @@
package types
import (
"testing"
"github.com/shopspring/decimal"
"github.com/stretchr/testify/assert"
)
// TestNumberUnmarshalJSON asserts the following behaviour:
// * Literal numbers and quoted are valid
// * Anything else returns errInvalidNumberValue
func TestNumberUnmarshalJSON(t *testing.T) {
t.Parallel()
var n Number
err := n.UnmarshalJSON([]byte(`"0.00000001"`))
assert.NoError(t, err, "Unmarshal should not error")
assert.Equal(t, 1e-8, n.Float64(), "Float64() should return the correct value")
err = n.UnmarshalJSON([]byte(`""`))
assert.NoError(t, err, "Unmarshal should not error")
assert.Zero(t, n.Float64(), "UnmarshalJSON should parse empty as 0")
err = n.UnmarshalJSON([]byte(`1337.37`))
assert.NoError(t, err, "Unmarshal should not error on number types")
assert.Equal(t, 1337.37, n.Float64(), "UnmarshalJSON should handle raw numerics")
// Invalid value checking
for _, i := range []string{`"MEOW"`, `null`, `false`, `true`, `"1337.37`} {
err = n.UnmarshalJSON([]byte(i))
assert.ErrorIsf(t, err, errInvalidNumberValue, "UnmarshalJSON should error with invalid Value for `%s`", i)
}
}
// TestNumberMarshalJSON asserts the following behaviour:
// 0 marshalls to quoted empty string
// Anything else marshalls as a quoted number
func TestNumberMarshalJSON(t *testing.T) {
data, err := new(Number).MarshalJSON()
assert.NoError(t, err, "MarshalJSON should not error")
assert.Equal(t, `""`, string(data), "MarshalJSON should return the correct value")
data, err = Number(1337.1337).MarshalJSON()
assert.NoError(t, err, "MarshalJSON should not error")
assert.Equal(t, `"1337.1337"`, string(data), "MarshalJSON should return the correct value")
}
// TestNumberFloat64 asserts Float64() returns a valid float64
func TestNumberFloat64(t *testing.T) {
t.Parallel()
assert.Equal(t, 0.04200064, Number(0.04200064).Float64(), "Float64() should return the correct value")
}
// TestNumberDecimal asserts Decimal() returns a valid decimal.Decimal
func TestNumberDecimal(t *testing.T) {
t.Parallel()
assert.Equal(t, decimal.NewFromFloat(0.04200064), Number(0.04200064).Decimal(), "Decimal() should return the correct value")
}
// TestNumberInt64 asserts Int64() returns a valid truncated int64
func TestNumberInt64(t *testing.T) {
t.Parallel()
assert.Equal(t, int64(42), Number(42.00000064).Int64(), "Int64() should return the correct truncated value")
assert.Equal(t, int64(43), Number(43.99999964).Int64(), "Int64() should not round the number")
}
// BenchmarkNumberUnmarshalJSON provides a barebones benchmark of Unmarshaling a string value
// Ballpark: 42.78 ns/op 16 B/op 1 allocs/op
func BenchmarkNumberUnmarshalJSON(b *testing.B) {
var n Number
for i := 0; i < b.N; i++ {
_ = n.UnmarshalJSON([]byte(`"0.04200074"`))
}
}
// BenchmarkNumberMarshalJSON provides a barebones benchmark of Marshaling a string value
// Ballpark: 118.2 ns/op 56 B/op 3 allocs/op
func BenchmarkNumberMarshalJSON(b *testing.B) {
for i := 0; i < b.N; i++ {
_, _ = Number(1337.1337).MarshalJSON()
}
}