binance: implement GetDepthRequest with requestgen

This commit is contained in:
c9s 2024-02-06 12:23:56 +08:00
parent 2f40149387
commit 7e5d25a7e0
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
4 changed files with 252 additions and 10 deletions

View File

@ -0,0 +1,25 @@
package binanceapi
import (
"github.com/c9s/requestgen"
"github.com/c9s/bbgo/pkg/fixedpoint"
)
type Depth struct {
LastUpdateId int64 `json:"lastUpdateId"`
Bids [][]fixedpoint.Value `json:"bids"`
Asks [][]fixedpoint.Value `json:"asks"`
}
//go:generate requestgen -method GET -url "/api/v3/depth" -type GetDepthRequest -responseType .Depth
type GetDepthRequest struct {
client requestgen.AuthenticatedAPIClient
symbol string `param:"symbol"`
limit int `param:"limit" defaultValue:"1000"`
}
func (c *RestClient) NewGetDepthRequest() *GetDepthRequest {
return &GetDepthRequest{client: c}
}

View File

@ -0,0 +1,190 @@
// Code generated by "requestgen -method GET -url /api/v3/depth -type GetDepthRequest -responseType .Depth"; DO NOT EDIT.
package binanceapi
import (
"context"
"encoding/json"
"fmt"
"net/url"
"reflect"
"regexp"
)
func (g *GetDepthRequest) Symbol(symbol string) *GetDepthRequest {
g.symbol = symbol
return g
}
func (g *GetDepthRequest) Limit(limit int) *GetDepthRequest {
g.limit = limit
return g
}
// GetQueryParameters builds and checks the query parameters and returns url.Values
func (g *GetDepthRequest) GetQueryParameters() (url.Values, error) {
var params = map[string]interface{}{}
query := url.Values{}
for _k, _v := range params {
query.Add(_k, fmt.Sprintf("%v", _v))
}
return query, nil
}
// GetParameters builds and checks the parameters and return the result in a map object
func (g *GetDepthRequest) GetParameters() (map[string]interface{}, error) {
var params = map[string]interface{}{}
// check symbol field -> json key symbol
symbol := g.symbol
// assign parameter of symbol
params["symbol"] = symbol
// check limit field -> json key limit
limit := g.limit
// assign parameter of limit
params["limit"] = limit
return params, nil
}
// GetParametersQuery converts the parameters from GetParameters into the url.Values format
func (g *GetDepthRequest) GetParametersQuery() (url.Values, error) {
query := url.Values{}
params, err := g.GetParameters()
if err != nil {
return query, err
}
for _k, _v := range params {
if g.isVarSlice(_v) {
g.iterateSlice(_v, func(it interface{}) {
query.Add(_k+"[]", fmt.Sprintf("%v", it))
})
} else {
query.Add(_k, fmt.Sprintf("%v", _v))
}
}
return query, nil
}
// GetParametersJSON converts the parameters from GetParameters into the JSON format
func (g *GetDepthRequest) GetParametersJSON() ([]byte, error) {
params, err := g.GetParameters()
if err != nil {
return nil, err
}
return json.Marshal(params)
}
// GetSlugParameters builds and checks the slug parameters and return the result in a map object
func (g *GetDepthRequest) GetSlugParameters() (map[string]interface{}, error) {
var params = map[string]interface{}{}
return params, nil
}
func (g *GetDepthRequest) applySlugsToUrl(url string, slugs map[string]string) string {
for _k, _v := range slugs {
needleRE := regexp.MustCompile(":" + _k + "\\b")
url = needleRE.ReplaceAllString(url, _v)
}
return url
}
func (g *GetDepthRequest) iterateSlice(slice interface{}, _f func(it interface{})) {
sliceValue := reflect.ValueOf(slice)
for _i := 0; _i < sliceValue.Len(); _i++ {
it := sliceValue.Index(_i).Interface()
_f(it)
}
}
func (g *GetDepthRequest) isVarSlice(_v interface{}) bool {
rt := reflect.TypeOf(_v)
switch rt.Kind() {
case reflect.Slice:
return true
}
return false
}
func (g *GetDepthRequest) GetSlugsMap() (map[string]string, error) {
slugs := map[string]string{}
params, err := g.GetSlugParameters()
if err != nil {
return slugs, nil
}
for _k, _v := range params {
slugs[_k] = fmt.Sprintf("%v", _v)
}
return slugs, nil
}
// GetPath returns the request path of the API
func (g *GetDepthRequest) GetPath() string {
return "/api/v3/depth"
}
// Do generates the request object and send the request object to the API endpoint
func (g *GetDepthRequest) Do(ctx context.Context) (*Depth, error) {
// empty params for GET operation
var params interface{}
query, err := g.GetParametersQuery()
if err != nil {
return nil, err
}
var apiURL string
apiURL = g.GetPath()
req, err := g.client.NewAuthenticatedRequest(ctx, "GET", apiURL, query, params)
if err != nil {
return nil, err
}
response, err := g.client.SendRequest(req)
if err != nil {
return nil, err
}
var apiResponse Depth
type responseUnmarshaler interface {
Unmarshal(data []byte) error
}
if unmarshaler, ok := interface{}(&apiResponse).(responseUnmarshaler); ok {
if err := unmarshaler.Unmarshal(response.Body); err != nil {
return nil, err
}
} else {
// The line below checks the content type, however, some API server might not send the correct content type header,
// Hence, this is commented for backward compatibility
// response.IsJSON()
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
}
}
type responseValidator interface {
Validate() error
}
if validator, ok := interface{}(&apiResponse).(responseValidator); ok {
if err := validator.Validate(); err != nil {
return nil, err
}
}
return &apiResponse, nil
}

View File

@ -1346,15 +1346,32 @@ func (e *Exchange) QueryDepth(ctx context.Context, symbol string) (snapshot type
return e.queryFuturesDepth(ctx, symbol)
}
response, err := e.client.NewDepthService().Symbol(symbol).Limit(DefaultDepthLimit).Do(ctx)
response, err := e.client2.NewGetDepthRequest().Symbol(symbol).Limit(DefaultDepthLimit).Do(ctx)
if err != nil {
return snapshot, finalUpdateID, err
}
return convertDepth(snapshot, symbol, finalUpdateID, response)
return convertDepth(symbol, response)
}
func convertDepth(
func convertDepth(symbol string, response *binanceapi.Depth) (snapshot types.SliceOrderBook, finalUpdateID int64, err error) {
snapshot.Symbol = symbol
// empty time since the API does not provide time information.
snapshot.Time = time.Time{}
finalUpdateID = response.LastUpdateId
for _, entry := range response.Bids {
snapshot.Bids = append(snapshot.Bids, types.PriceVolume{Price: entry[0], Volume: entry[1]})
}
for _, entry := range response.Asks {
snapshot.Asks = append(snapshot.Asks, types.PriceVolume{Price: entry[0], Volume: entry[1]})
}
return snapshot, finalUpdateID, err
}
func convertDepthLegacy(
snapshot types.SliceOrderBook, symbol string, finalUpdateID int64, response *binance.DepthResponse,
) (types.SliceOrderBook, int64, error) {
snapshot.Symbol = symbol

View File

@ -15,7 +15,9 @@ import (
"github.com/c9s/bbgo/pkg/types"
)
func (e *Exchange) queryFuturesClosedOrders(ctx context.Context, symbol string, since, until time.Time, lastOrderID uint64) (orders []types.Order, err error) {
func (e *Exchange) queryFuturesClosedOrders(
ctx context.Context, symbol string, since, until time.Time, lastOrderID uint64,
) (orders []types.Order, err error) {
req := e.futuresClient.NewListOrdersService().Symbol(symbol)
if lastOrderID > 0 {
@ -34,7 +36,9 @@ func (e *Exchange) queryFuturesClosedOrders(ctx context.Context, symbol string,
return toGlobalFuturesOrders(binanceOrders, false)
}
func (e *Exchange) TransferFuturesAccountAsset(ctx context.Context, asset string, amount fixedpoint.Value, io types.TransferDirection) error {
func (e *Exchange) TransferFuturesAccountAsset(
ctx context.Context, asset string, amount fixedpoint.Value, io types.TransferDirection,
) error {
req := e.client2.NewFuturesTransferRequest()
req.Asset(asset)
req.Amount(amount.String())
@ -63,7 +67,7 @@ func (e *Exchange) TransferFuturesAccountAsset(ctx context.Context, asset string
// Balance.Available = Wallet Balance(in Binance UI) - Used Margin
// Balance.Locked = Used Margin
func (e *Exchange) QueryFuturesAccount(ctx context.Context) (*types.Account, error) {
//account, err := e.futuresClient.NewGetAccountService().Do(ctx)
// account, err := e.futuresClient.NewGetAccountService().Do(ctx)
reqAccount := e.futuresClient2.NewFuturesGetAccountRequest()
account, err := reqAccount.Do(ctx)
if err != nil {
@ -218,7 +222,9 @@ func (e *Exchange) submitFuturesOrder(ctx context.Context, order types.SubmitOrd
return createdOrder, err
}
func (e *Exchange) QueryFuturesKLines(ctx context.Context, symbol string, interval types.Interval, options types.KLineQueryOptions) ([]types.KLine, error) {
func (e *Exchange) QueryFuturesKLines(
ctx context.Context, symbol string, interval types.Interval, options types.KLineQueryOptions,
) ([]types.KLine, error) {
var limit = 1000
if options.Limit > 0 {
@ -272,7 +278,9 @@ func (e *Exchange) QueryFuturesKLines(ctx context.Context, symbol string, interv
return kLines, nil
}
func (e *Exchange) queryFuturesTrades(ctx context.Context, symbol string, options *types.TradeQueryOptions) (trades []types.Trade, err error) {
func (e *Exchange) queryFuturesTrades(
ctx context.Context, symbol string, options *types.TradeQueryOptions,
) (trades []types.Trade, err error) {
var remoteTrades []*futures.AccountTrade
req := e.futuresClient.NewListAccountTradeService().
@ -376,7 +384,7 @@ func (e *Exchange) queryFuturesDepth(ctx context.Context, symbol string) (snapsh
Asks: res.Asks,
}
return convertDepth(snapshot, symbol, finalUpdateID, response)
return convertDepthLegacy(snapshot, symbol, finalUpdateID, response)
}
func (e *Exchange) GetFuturesClient() *binanceapi.FuturesRestClient {
@ -386,7 +394,9 @@ func (e *Exchange) GetFuturesClient() *binanceapi.FuturesRestClient {
// QueryFuturesIncomeHistory queries the income history on the binance futures account
// This is more binance futures specific API, the convert function is not designed yet.
// TODO: consider other futures platforms and design the common data structure for this
func (e *Exchange) QueryFuturesIncomeHistory(ctx context.Context, symbol string, incomeType binanceapi.FuturesIncomeType, startTime, endTime *time.Time) ([]binanceapi.FuturesIncome, error) {
func (e *Exchange) QueryFuturesIncomeHistory(
ctx context.Context, symbol string, incomeType binanceapi.FuturesIncomeType, startTime, endTime *time.Time,
) ([]binanceapi.FuturesIncome, error) {
req := e.futuresClient2.NewFuturesGetIncomeHistoryRequest()
req.Symbol(symbol)
req.IncomeType(incomeType)