Merge pull request #26 from isther/main

Features
This commit is contained in:
CommaHunger 2024-01-08 13:13:24 +01:00 committed by GitHub
commit 2cef19a9cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 2752 additions and 1014 deletions

View File

@ -2,7 +2,6 @@ package bybit_connector
import (
"context"
"encoding/json"
"github.com/wuhewuhe/bybit.go.api/handlers"
"net/http"
)

View File

@ -2,7 +2,6 @@ package bybit_connector
import (
"context"
"encoding/json"
"net/http"
)

View File

@ -2,7 +2,6 @@ package bybit_connector
import (
"context"
"encoding/json"
"github.com/wuhewuhe/bybit.go.api/handlers"
"net/http"
)

View File

@ -6,17 +6,21 @@ import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/wuhewuhe/bybit.go.api/handlers"
"io"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/bitly/go-simplejson"
jsoniter "github.com/json-iterator/go"
"github.com/wuhewuhe/bybit.go.api/handlers"
)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type ServerResponse struct {
RetCode int `json:"retCode"`
RetMsg string `json:"retMsg"`
@ -77,6 +81,14 @@ func GetCurrentTime() int64 {
return timeStamp
}
func newJSON(data []byte) (j *simplejson.Json, err error) {
j, err = simplejson.NewJson(data)
if err != nil {
return nil, err
}
return j, nil
}
// NewBybitHttpClient NewClient Create client function for initialising new Bybit client
func NewBybitHttpClient(apiKey string, APISecret string, options ...ClientOption) *Client {
c := &Client{
@ -152,6 +164,9 @@ func (c *Client) parseRequest(r *request, opts ...RequestOption) (err error) {
func (c *Client) callAPI(ctx context.Context, r *request, opts ...RequestOption) (data []byte, err error) {
err = c.parseRequest(r, opts...)
if err != nil {
return nil, err
}
req, err := http.NewRequest(r.method, r.fullURL, r.body)
if err != nil {
return []byte{}, err
@ -196,36 +211,79 @@ func (c *Client) callAPI(ctx context.Context, r *request, opts ...RequestOption)
return data, nil
}
// NewMarketKlineService Market Endpoints
func (c *Client) NewMarketKlineService(klineType, category, symbol, interval string) *Klines {
return &Klines{
c: c,
category: category,
symbol: symbol,
interval: interval,
klineType: klineType,
}
func (c *Client) NewInstrumentsInfoService() *InstrumentsInfoService {
return &InstrumentsInfoService{c: c}
}
func (c *Client) NewMarketKLinesService(klineType string, params map[string]interface{}) *MarketClient {
return &MarketClient{
c: c,
klineType: klineType,
params: params,
}
// NewMarketKlineService Market Kline Endpoints
func (c *Client) NewMarketKlineService() *MarketKlinesService {
return &MarketKlinesService{c: c}
}
func (c *Client) NewMarketInfoServiceNoParams() *MarketClient {
return &MarketClient{
c: c,
}
// NewMarketMarkPriceKlineService Market Mark Price Kline Endpoints
func (c *Client) NewMarketMarkPriceKlineService() *MarketMarkPriceKlineService {
return &MarketMarkPriceKlineService{c: c}
}
func (c *Client) NewMarketInfoService(params map[string]interface{}) *MarketClient {
return &MarketClient{
c: c,
params: params,
}
// NewMarketIndexPriceKlineService Market Index Price Kline Endpoints
func (c *Client) NewMarketIndexPriceKlineService() *MarketIndexPriceKlineService {
return &MarketIndexPriceKlineService{c: c}
}
// NewMarketPremiumIndexPriceKlineService Market Premium Index Price Kline Endpoints
func (c *Client) NewMarketPremiumIndexPriceKlineService() *MarketPremiumIndexPriceKlineService {
return &MarketPremiumIndexPriceKlineService{c: c}
}
func (c *Client) NewOrderBookService() *MarketOrderBookService {
return &MarketOrderBookService{c: c}
}
func (c *Client) NewTickersService() *MarketTickersService {
return &MarketTickersService{c: c}
}
func (c *Client) NewFundingTatesService() *MarketFundingRatesService {
return &MarketFundingRatesService{c: c}
}
func (c *Client) NewGetPublicRecentTradesService() *GetPublicRecentTradesService {
return &GetPublicRecentTradesService{c: c}
}
// GetOpenInterestsServicdde
func (c *Client) NewGetOpenInterestsService() *GetOpenInterestsService {
return &GetOpenInterestsService{c: c}
}
// GetHistoricalVolatilityService
func (c *Client) NewGetHistoricalVolatilityService() *GetHistoricalVolatilityService {
return &GetHistoricalVolatilityService{c: c}
}
// GetInsuranceInfoService
func (c *Client) NewGetInsuranceInfoService() *GetInsuranceInfoService {
return &GetInsuranceInfoService{c: c}
}
// GetRiskLimitService
func (c *Client) NewGetRiskLimitService() *GetRiskLimitService {
return &GetRiskLimitService{c: c}
}
// GetDeliveryPriceService
func (c *Client) NewGetDeliveryPriceService() *GetDeliveryPriceService {
return &GetDeliveryPriceService{c: c}
}
// GetMarketLSRatioService
func (c *Client) NewGetMarketLSRatioService() *GetMarketLSRatioService {
return &GetMarketLSRatioService{c: c}
}
// GetServerTimeService
func (c *Client) NewGetServerTimeService() *GetServerTimeService {
return &GetServerTimeService{c: c}
}
// NewPlaceOrderService Trade Endpoints

View File

@ -1,14 +1,15 @@
package bybit_connector
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"time"
)
type MessageHandler func(message string) error
@ -43,6 +44,8 @@ type WebSocket struct {
maxAliveTime string
pingInterval int
onMessage MessageHandler
ctx context.Context
cancel context.CancelFunc
}
type WebsocketOption func(*WebSocket)
@ -111,6 +114,7 @@ func (b *WebSocket) Connect(args []string) error {
go b.handleIncomingMessages()
b.ctx, b.cancel = context.WithCancel(context.Background())
Ping(b)
return b.sendSubscription(args)
@ -126,12 +130,16 @@ func Ping(b *WebSocket) {
if err := b.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
fmt.Println("Failed to send ping:", err)
}
case <-b.ctx.Done():
fmt.Println("Exit ping")
return
}
}
}()
}
func (b *WebSocket) Disconnect() error {
b.cancel()
return b.conn.Close()
}

View File

@ -1,51 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
PlaceBatchTrade()
}
func PlaceBatchTrade() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"category": "option",
"request": []map[string]interface{}{
{
"category": "option",
"symbol": "BTC-10FEB23-24000-C",
"orderType": "Limit",
"side": "Buy",
"qty": "0.1",
"price": "5",
"orderIv": "0.1",
"timeInForce": "GTC",
"orderLinkId": "9b381bb1-401",
"mmp": false,
"reduceOnly": false,
},
{
"category": "option",
"symbol": "BTC-10FEB23-24000-C",
"orderType": "Limit",
"side": "Buy",
"qty": "0.1",
"price": "5",
"orderIv": "0.1",
"timeInForce": "GTC",
"orderLinkId": "82ee86dd-001",
"mmp": false,
"reduceOnly": false,
},
},
}
orderResult, err := client.NewTradeService(params).PlaceBatchOrder(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(orderResult))
}

View File

@ -1,21 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
PlaceOrder()
}
func PlaceOrder() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
orderResult, err := client.NewPlaceOrderService("linear", "XRPUSDT", "Buy", "Market", "10").Do(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(orderResult))
}

View File

@ -1,31 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
PlaceTrade()
}
func PlaceTrade() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{
"category": "linear",
"symbol": "BTCUSDT",
"side": "Buy",
"positionIdx": 0,
"orderType": "Limit",
"qty": "0.001",
"price": "10000",
"timeInForce": "GTC",
}
orderResult, err := client.NewTradeService(params).PlaceOrder(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(orderResult))
}

View File

@ -1,22 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
PlaceTrade()
}
func PlaceTrade() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"accountType": "UNIFIED", "category": "linear"}
accountResult, err := client.NewAccountService(params).GetTransactionLog(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(accountResult))
}

View File

@ -1,22 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
AssetInfo()
}
func AssetInfo() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"accountType": "spot"}
assetResult, err := client.NewAssetService(params).GetAssetInfo(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(assetResult))
}

View File

@ -1,22 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
GetCoinInfo()
}
func GetCoinInfo() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"coin": "USDT"}
assetResult, err := client.NewAssetService(params).GetCoinInfo(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(assetResult))
}

View File

@ -1,22 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
PlaceTrade()
}
func PlaceTrade() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{}
orderResult, err := client.NewBrokerService(params).GetBrokerEarning(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(orderResult))
}

View File

@ -1,22 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
PlaceTrade()
}
func PlaceTrade() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"coin": "USDT"}
orderResult, err := client.NewLendingService(params).GetC2cLendingCoinInfo(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(orderResult))
}

View File

@ -1,25 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
InstrumentInfo()
}
func InstrumentInfo() {
client := bybit.NewBybitHttpClient("", "")
// NewServerTimeService
params := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "status": "Trading"}
marketKline, err := client.NewMarketInfoService(params).GetInstrumentInfo(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(marketKline))
}

View File

@ -1,25 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
IndexKline()
}
func IndexKline() {
client := bybit.NewBybitHttpClient("", "")
// NewServerTimeService
params := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "interval": "1", "Limit": 2}
marketKline, err := client.NewMarketKLinesService("index-price-kline", params).GetMarketKline(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(marketKline))
}

View File

@ -1,24 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
MarketKline()
}
func MarketKline() {
client := bybit.NewBybitHttpClient("", "")
// NewServerTimeService
marketKline, err := client.NewMarketKlineService("premium-index-price-kline", "linear", "BTCUSDT", "1").Limit(10).Do(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(marketKline))
}

View File

@ -1,24 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
ServerTime()
}
func ServerTime() {
client := bybit.NewBybitHttpClient("", "")
// NewServerTimeService
serverTime, err := client.NewMarketInfoServiceNoParams().GetServerTime(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(serverTime))
}

View File

@ -1,22 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
PlaceTrade()
}
func PlaceTrade() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"category": "linear", "settleCoin": "USDT", "limit": 10}
orderResult, err := client.NewPositionService(params).GetPositionList(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(orderResult))
}

View File

@ -1,22 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
SwitchPositionMode()
}
func SwitchPositionMode() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"category": "linear", "coin": "USDT", "mode": 3}
orderResult, err := client.NewPositionService(params).SwitchPositionMode(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(orderResult))
}

View File

@ -1,22 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
PlaceTrade()
}
func PlaceTrade() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"category": "linear", "settleCoin": "USDT", "limit": 10}
orderResult, err := client.NewPreUpgradeService(params).GetPreUpgradeOrderHistory(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(orderResult))
}

View File

@ -1,22 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
PlaceTrade()
}
func PlaceTrade() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"ltCoin": "BTC3L"}
leverageTokenResult, err := client.NewSpotLeverageService(params).GetLeverageTokenInfo(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(leverageTokenResult))
}

View File

@ -1,22 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
SpotMarginData()
}
func SpotMarginData() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"ltCoin": "BTC3L"}
leverageTokenResult, err := client.NewSpotMarginDataService(params, true).GetSpotMarginData(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(leverageTokenResult))
}

View File

@ -1,28 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
CreateSubApiKey()
}
func CreateSubApiKey() {
client := bybit.NewBybitHttpClient("8wYkmpLsMg10eNQyPm", "Ouxc34myDnXvei54XsBZgoQzfGxO4bkr2Zsj", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"subuid": "100366706", "readOnly": 0,
"permissions": []map[string]interface{}{
{
"Wallet": []string{"AccountTransfer", "SubMemberTransferList"},
},
},
}
userResult, err := client.NewUserService(params).CreateSubApiKey(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(userResult))
}

View File

@ -1,22 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
CreateNewSubUser()
}
func CreateNewSubUser() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"username": "06112023Victor", "memberType": 1}
userResult, err := client.NewUserService(params).CreateSubMember(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(userResult))
}

View File

@ -1,21 +0,0 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
GetApiKeyInfo()
}
func GetApiKeyInfo() {
client := bybit.NewBybitHttpClient("YOUR_API_KEY", "YOUR_API_SECRET", bybit.WithBaseURL(bybit.TESTNET))
userResult, err := client.NewUserServiceNoParams().GetAPIKeyInfo(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(userResult))
}

View File

@ -1,15 +0,0 @@
package main
import (
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
ws := bybit.NewBybitPrivateWebSocket("wss://stream-testnet.bybit.com/v5/private", "YOUR_API_KEY", "YOUR_API_SECRET", func(message string) error {
fmt.Println("Received:", message)
return nil
})
_ = ws.Connect([]string{"order"})
select {}
}

View File

@ -1,15 +0,0 @@
package main
import (
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
ws := bybit.NewBybitPublicWebSocket("wss://stream.bybit.com/v5/public/spot", func(message string) error {
fmt.Println("Received:", message)
return nil
})
_ = ws.Connect([]string{"orderbook.1.BTCUSDT"})
select {}
}

4
go.mod
View File

@ -3,13 +3,17 @@ module github.com/wuhewuhe/bybit.go.api
go 1.21
require (
github.com/bitly/go-simplejson v0.5.1
github.com/google/uuid v1.5.0
github.com/gorilla/websocket v1.5.1
github.com/json-iterator/go v1.1.12
github.com/stretchr/testify v1.8.4
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.5.1 // indirect
golang.org/x/net v0.19.0 // indirect

10
go.sum
View File

@ -1,10 +1,19 @@
github.com/bitly/go-simplejson v0.5.1 h1:xgwPbetQScXt1gh9BmoJ6j9JMr3TElvuIyjR8pgdoow=
github.com/bitly/go-simplejson v0.5.1/go.mod h1:YOPVLzCfwK14b4Sff3oP1AmGhI9T9Vsg84etUnlyp+Q=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@ -12,6 +21,7 @@ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSS
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.1 h1:4VhoImhV/Bm0ToFkXFi8hXNXwpDRZ/ynw3amt82mzq0=
github.com/stretchr/objx v0.5.1/go.mod h1:/iHQpkQwBD6DLUmQ4pE+s1TXdob1mORJ4/UFdrifcy0=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=

View File

@ -2,7 +2,6 @@ package bybit_connector
import (
"context"
"encoding/json"
"github.com/wuhewuhe/bybit.go.api/handlers"
"net/http"
)

296
market.go
View File

@ -1,296 +0,0 @@
package bybit_connector
import (
"context"
"encoding/json"
"github.com/wuhewuhe/bybit.go.api/handlers"
"net/http"
)
type MarketClient struct {
c *Client
klineType string
params map[string]interface{}
}
func (s *MarketClient) GetServerTime(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/time",
secType: secTypeNone,
}
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetMarketKline(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/" + s.klineType,
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetInstrumentInfo(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/instruments-info",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetOrderBookInfo(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/orderbook",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetMarketTickers(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/tickers",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetFundingRates(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/tickers",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetPublicRecentTrades(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/recent-trade",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetOpenInterests(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/open-interest",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetHistoricalVolatility(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/historical-volatility",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetInsuranceInfo(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/insurance",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetRiskLimit(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/risk-limit",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetDeliveryPrice(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/delivery-price",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetMarketLSRatio(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/account-ratio",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}

View File

@ -1,67 +0,0 @@
package bybit_connector
import (
"context"
"encoding/json"
"net/http"
)
// Klines Market Kline (GET /v5/market/kline)
type Klines struct {
c *Client
klineType string
category string
symbol string
interval string
limit *int
start *uint64
end *uint64
}
// Limit set limit
func (s *Klines) Limit(limit int) *Klines {
s.limit = &limit
return s
}
// Start set startTime
func (s *Klines) Start(startTime uint64) *Klines {
s.start = &startTime
return s
}
// End set endTime
func (s *Klines) End(endTime uint64) *Klines {
s.end = &endTime
return s
}
func (s *Klines) Do(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/" + s.klineType,
secType: secTypeNone,
}
r.setParam("category", s.category)
r.setParam("symbol", s.symbol)
r.setParam("interval", s.interval)
if s.limit != nil {
r.setParam("limit", *s.limit)
}
if s.start != nil {
r.setParam("start", *s.start)
}
if s.end != nil {
r.setParam("end", *s.end)
}
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}

1167
market_service.go Normal file

File diff suppressed because it is too large Load Diff

1334
market_service_test.go Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,69 +0,0 @@
package bybit_connector
import (
"github.com/stretchr/testify/suite"
"github.com/wuhewuhe/bybit.go.api/models"
"testing"
)
type marketTestSuite struct {
baseTestSuite
}
func TestMarket(t *testing.T) {
suite.Run(t, new(marketTestSuite))
}
func (s *marketTestSuite) TestServerTime() {
data := []byte(`{
"retCode": 0,
"retMsg": "OK",
"result": {
"timeSecond": "1699287551",
"timeNano": "1699287551919622633"
},
"retExtInfo": {},
"time": 1699287551919
}`)
s.mockDo(data, nil)
defer s.assertDo()
s.assertReq(func(r *request) {
e := newRequest()
s.assertRequestEqual(e, r)
})
serverTime, err := s.client.NewMarketInfoServiceNoParams().GetServerTime(newContext())
e1 := &models.ServerTimeResult{
TimeSecond: "1699287551",
TimeNano: "1699287551919622633",
}
s.r().NoError(err)
s.assertServerTimeEqual(e1, serverTime)
}
func (s *marketTestSuite) assertServerTimeEqual(expected *models.ServerTimeResult, actual *ServerResponse) {
// Assert that the actual result is not nil and is a map
r := s.r()
actualResult, ok := actual.Result.(map[string]interface{})
if !ok {
r.FailNow("Actual result is not a map", "Actual Result: %#v", actual.Result)
return
}
// Cast the map to the expected struct type
var actualStruct models.ServerTimeResult
timeSecond, okSecond := actualResult["timeSecond"].(string)
timeNano, okNano := actualResult["timeNano"].(string)
if !okSecond || !okNano {
r.FailNow("Failed to cast actual result fields to string", "Actual Result: %#v", actual.Result)
return
}
actualStruct.TimeSecond = timeSecond
actualStruct.TimeNano = timeNano
// Compare the fields
r.Equal(expected.TimeSecond, actualStruct.TimeSecond, "TimeSecond field is not equal")
r.Equal(expected.TimeNano, actualStruct.TimeNano, "TimeNano field is not equal")
}

52
models/enum.go Normal file
View File

@ -0,0 +1,52 @@
package models
type Category string
const (
CategorySpot Category = "spot"
CategoryLinear Category = "linear" //Unified Account: USDT perpetual, and USDC contract, including USDC perp, USDC futures; Classic Account: USDT perp
CategoryInverse Category = "inverse" // Inverse contract, including Inverse perp, Inverse futures
CategoryOption Category = "option"
)
type OrderStatus string
const (
OrderStatusCreated OrderStatus = "Created" //order has been accepted by the system but not yet put through the matching engine
OrderStatusNew OrderStatus = "New" //order has been placed successfully
OrderStatusRejected OrderStatus = "Rejected"
OrderStatusPartiallyFilled OrderStatus = "PartiallyFilled"
OrderStatusPartiallyFilledCanceled OrderStatus = "PartiallyFilledCanceled" //Only spot has this order status
OrderStatusFilled OrderStatus = "Filled"
OrderStatusCancelled OrderStatus = "Cancelled" //In derivatives, orders with this status may have an executed qty
OrderStatusUntriggered OrderStatus = "Untriggered"
OrderStatusTriggered OrderStatus = "Triggered"
OrderStatusDeactivated OrderStatus = "Deactivated" //UTA: Spot tp/sl order, conditional order, OCO order are cancelled before they are triggered
)
type TimeInForce string
const (
TimeInForceGTC TimeInForce = "GTC" //GoodTillCancel
TimeInForceIOC TimeInForce = "IOC" //ImmediateOrCancel
TimeInForceFOK TimeInForce = "FOK" //FillOrKill
TimeInForcePostOnly TimeInForce = "PostOnly"
)
type OrderType string
const (
OrderTypeMarket OrderType = "Market"
Limit OrderType = "Limit"
UNKNOWN OrderType = "UNKNOWN" //Is not a valid request parameter value. Is only used in some responses. Mainly, it is used when execType is Funding.
)
type SymbolStatus string
const (
SymbolStatusPreLaunch SymbolStatus = "PreLaunch"
SymbolStatusTrading SymbolStatus = "Trading"
SymbolStatusSettling SymbolStatus = "Settling"
SymbolStatusDelivering SymbolStatus = "Delivering"
SymbolStatusClosed SymbolStatus = "Closed"
)

View File

@ -16,13 +16,55 @@ type MarketKlineCandle struct {
}
type MarketKlineResponse struct {
Category string `json:"category"`
Symbol string `json:"symbol"`
List []MarketKlineCandle `json:"list"`
Category Category `json:"category"`
Symbol string `json:"symbol"`
List []*MarketKlineCandle `json:"list"`
}
type InstrumentInfo struct {
Category string `json:"category"`
type MarketMarkPriceKlineCandle struct {
StartTime string `json:"startTime"`
OpenPrice string `json:"openPrice"`
HighPrice string `json:"highPrice"`
LowPrice string `json:"lowPrice"`
ClosePrice string `json:"closePrice"`
}
type MarketMarkPriceKlineResponse struct {
Category Category `json:"category"`
Symbol string `json:"symbol"`
List []*MarketMarkPriceKlineCandle `json:"list"`
}
type MarketIndexPriceKlineCandle struct {
StartTime string `json:"startTime"`
OpenPrice string `json:"openPrice"`
HighPrice string `json:"highPrice"`
LowPrice string `json:"lowPrice"`
ClosePrice string `json:"closePrice"`
}
type MarketIndexPriceKlineResponse struct {
Category Category `json:"category"`
Symbol string `json:"symbol"`
List []*MarketIndexPriceKlineCandle `json:"list"`
}
type MarketPremiumIndexPriceKlineCandle struct {
StartTime string `json:"startTime"`
OpenPrice string `json:"openPrice"`
HighPrice string `json:"highPrice"`
LowPrice string `json:"lowPrice"`
ClosePrice string `json:"closePrice"`
}
type MarketPremiumIndexPriceKlineResponse struct {
Category Category `json:"category"`
Symbol string `json:"symbol"`
List []*MarketPremiumIndexPriceKlineCandle `json:"list"`
}
type InstrumentInfoResponse struct {
Category Category `json:"category"`
NextPageCursor string `json:"nextPageCursor"`
List []Instrument `json:"list"`
}
@ -30,13 +72,16 @@ type InstrumentInfo struct {
type Instrument struct {
Symbol string `json:"symbol"`
ContractType string `json:"contractType"`
Status string `json:"status"`
OptionType string `json:"optionType"`
Innovation string `json:"innovation"`
Status SymbolStatus `json:"status"`
BaseCoin string `json:"baseCoin"`
QuoteCoin string `json:"quoteCoin"`
LaunchTime string `json:"launchTime"`
DeliveryTime string `json:"deliveryTime"`
DeliveryFeeRate string `json:"deliveryFeeRate"`
PriceScale string `json:"priceScale"`
MarginTrading string `json:"marginTrading"`
LeverageFilter LeverageFilter `json:"leverageFilter"`
PriceFilter PriceFilter `json:"priceFilter"`
LotSizeFilter LotSizeFilter `json:"lotSizeFilter"`
@ -63,12 +108,18 @@ type LotSizeFilter struct {
MinOrderQty string `json:"minOrderQty"`
QtyStep string `json:"qtyStep"`
PostOnlyMaxOrderQty string `json:"postOnlyMaxOrderQty"`
BasePrecision string `json:"basePrecision"`
QuotePrecision string `json:"quotePrecision"`
MaxOrderAmt string `json:"maxOrderAmt"`
MinOrderAmt string `jsoN:"minOrderAmt"`
}
type OrderBookEntry struct {
Price string `json:"0"`
Size string `json:"1"`
}
// type OrderBookEntry struct {
// Price string `json:"0"`
// Size string `json:"1"`
// }
type OrderBookEntry []string
type OrderBookInfo struct {
Symbol string `json:"s"`
@ -103,11 +154,19 @@ type TickerInfo struct {
Bid1Price string `json:"bid1Price"`
Ask1Price string `json:"ask1Price"`
Bid1Size string `json:"bid1Size"`
Ask1Iv string `json:"ask1Iv"`
Bid1Iv string `json:"bid1Iv"`
MarkIv string `json:"markIv"`
UnderlyingPrice string `json:"underlyingPrice"`
TotalVolume string `json:"totalVolume"`
TotalTurnover string `json:"totalTurnover"`
Change24h string `json:"change24h"`
UsdIndexPrice string `json:"usdIndexPrice"`
}
type MarketTickers struct {
Category string `json:"category"`
List []TickerInfo `json:"list"`
Category string `json:"category"`
List []*TickerInfo `json:"list"`
}
type FundingRateInfo struct {
@ -136,6 +195,18 @@ type PublicRecentTradeHistory struct {
List []TradeInfo `json:"list"`
}
type OpenInterestInfo struct {
Category string `json:"category"`
Symbol string `json:"symbol"`
List []OpenInterest `json:"list"`
NextPageCursor string `json:"nextPageCursor"`
}
type OpenInterest struct {
OpenInterest string `json:"openInterest"`
Timestamp string `json:"timeStamp"`
}
type VolatilityData struct {
Period int `json:"period"`
Value string `json:"value"`
@ -144,7 +215,7 @@ type VolatilityData struct {
type HistoricalVolatilityInfo struct {
Category string `json:"category"`
List []VolatilityData `json:"list"`
List []VolatilityData `json:"result"`
}
type InsuranceData struct {
@ -159,13 +230,13 @@ type MarketInsuranceInfo struct {
}
type RiskLimitData struct {
Id int `json:"id"`
Symbol string `json:"symbol"`
RiskLimitValue string `json:"riskLimitValue"`
MaintenanceMargin float64 `json:"maintenanceMargin"`
InitialMargin float64 `json:"initialMargin"`
IsLowestRisk int `json:"isLowestRisk"`
MaxLeverage string `json:"maxLeverage"`
Id int `json:"id"`
Symbol string `json:"symbol"`
RiskLimitValue string `json:"riskLimitValue"`
MaintenanceMargin string `json:"maintenanceMargin"`
InitialMargin string `json:"initialMargin"`
IsLowestRisk int `json:"isLowestRisk"`
MaxLeverage string `json:"maxLeverage"`
}
type MarketRiskLimitInfo struct {

View File

@ -2,7 +2,6 @@ package bybit_connector
import (
"context"
"encoding/json"
"net/http"
)

View File

@ -2,7 +2,6 @@ package bybit_connector
import (
"context"
"encoding/json"
"github.com/wuhewuhe/bybit.go.api/handlers"
"net/http"
)

View File

@ -2,7 +2,6 @@ package bybit_connector
import (
"context"
"encoding/json"
"github.com/wuhewuhe/bybit.go.api/handlers"
"net/http"
)

View File

@ -1,7 +1,6 @@
package bybit_connector
import (
"encoding/json"
"fmt"
"io"
"log"

View File

@ -2,7 +2,6 @@ package bybit_connector
import (
"context"
"encoding/json"
"github.com/wuhewuhe/bybit.go.api/handlers"
"net/http"
)

View File

@ -2,7 +2,6 @@ package bybit_connector
import (
"context"
"encoding/json"
"errors"
"github.com/wuhewuhe/bybit.go.api/handlers"
"net/http"

View File

@ -2,7 +2,6 @@ package bybit_connector
import (
"context"
"encoding/json"
"github.com/wuhewuhe/bybit.go.api/handlers"
"github.com/wuhewuhe/bybit.go.api/models"
"net/http"

View File

@ -2,7 +2,6 @@ package bybit_connector
import (
"context"
"encoding/json"
"github.com/wuhewuhe/bybit.go.api/handlers"
"net/http"
)