pkg/exchange: generate account by requestgen

This commit is contained in:
Edwin 2024-01-09 14:20:56 +08:00
parent c2e3fed6d3
commit a463c02183
4 changed files with 208 additions and 47 deletions

View File

@ -13,7 +13,6 @@ import (
"time" "time"
"github.com/c9s/bbgo/pkg/fixedpoint" "github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
"github.com/c9s/requestgen" "github.com/c9s/requestgen"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
@ -158,52 +157,6 @@ func (c *RestClient) NewAuthenticatedRequest(ctx context.Context, method, refURL
return req, nil return req, nil
} }
type BalanceDetail struct {
Currency string `json:"ccy"`
Available fixedpoint.Value `json:"availEq"`
CashBalance fixedpoint.Value `json:"cashBal"`
OrderFrozen fixedpoint.Value `json:"ordFrozen"`
Frozen fixedpoint.Value `json:"frozenBal"`
Equity fixedpoint.Value `json:"eq"`
EquityInUSD fixedpoint.Value `json:"eqUsd"`
UpdateTime types.MillisecondTimestamp `json:"uTime"`
UnrealizedProfitAndLoss fixedpoint.Value `json:"upl"`
}
type Account struct {
TotalEquityInUSD fixedpoint.Value `json:"totalEq"`
UpdateTime string `json:"uTime"`
Details []BalanceDetail `json:"details"`
}
func (c *RestClient) AccountBalances(ctx context.Context) (*Account, error) {
req, err := c.NewAuthenticatedRequest(ctx, "GET", "/api/v5/account/balance", nil, nil)
if err != nil {
return nil, err
}
response, err := c.SendRequest(req)
if err != nil {
return nil, err
}
var balanceResponse struct {
Code string `json:"code"`
Message string `json:"msg"`
Data []Account `json:"data"`
}
if err := response.DecodeJSON(&balanceResponse); err != nil {
return nil, err
}
if len(balanceResponse.Data) == 0 {
return nil, errors.New("empty account data")
}
return &balanceResponse.Data[0], nil
}
type AssetBalance struct { type AssetBalance struct {
Currency string `json:"ccy"` Currency string `json:"ccy"`
Balance fixedpoint.Value `json:"bal"` Balance fixedpoint.Value `json:"bal"`

View File

@ -60,6 +60,17 @@ func TestClient_GetMarketTicker(t *testing.T) {
t.Logf("tickers: %+v", tickers) t.Logf("tickers: %+v", tickers)
} }
func TestClient_GetAcountInfo(t *testing.T) {
client := getTestClientOrSkip(t)
ctx := context.Background()
req := client.NewGetAccountInfoRequest()
acct, err := req.Do(ctx)
assert.NoError(t, err)
assert.NotEmpty(t, acct)
t.Logf("acct: %+v", acct)
}
func TestClient_GetFundingRateRequest(t *testing.T) { func TestClient_GetFundingRateRequest(t *testing.T) {
client := NewClient() client := NewClient()
ctx := context.Background() ctx := context.Background()

View File

@ -0,0 +1,40 @@
package okexapi
import (
"github.com/c9s/requestgen"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
//go:generate -command GetRequest requestgen -method GET -responseType .APIResponse -responseDataField Data
//go:generate -command PostRequest requestgen -method POST -responseType .APIResponse -responseDataField Data
type BalanceDetail struct {
Currency string `json:"ccy"`
Available fixedpoint.Value `json:"availEq"`
CashBalance fixedpoint.Value `json:"cashBal"`
OrderFrozen fixedpoint.Value `json:"ordFrozen"`
Frozen fixedpoint.Value `json:"frozenBal"`
Equity fixedpoint.Value `json:"eq"`
EquityInUSD fixedpoint.Value `json:"eqUsd"`
UpdateTime types.MillisecondTimestamp `json:"uTime"`
UnrealizedProfitAndLoss fixedpoint.Value `json:"upl"`
}
type Account struct {
TotalEquityInUSD fixedpoint.Value `json:"totalEq"`
UpdateTime types.MillisecondTimestamp `json:"uTime"`
Details []BalanceDetail `json:"details"`
}
//go:generate GetRequest -url "/api/v5/account/balance" -type GetAccountInfoRequest -responseDataType []Account
type GetAccountInfoRequest struct {
client requestgen.AuthenticatedAPIClient
}
func (c *RestClient) NewGetAccountInfoRequest() *GetAccountInfoRequest {
return &GetAccountInfoRequest{
client: c,
}
}

View File

@ -0,0 +1,157 @@
// Code generated by "requestgen -method GET -responseType .APIResponse -responseDataField Data -url /api/v5/account/balance -type GetAccountInfoRequest -responseDataType []Account"; DO NOT EDIT.
package okexapi
import (
"context"
"encoding/json"
"fmt"
"net/url"
"reflect"
"regexp"
)
// GetQueryParameters builds and checks the query parameters and returns url.Values
func (g *GetAccountInfoRequest) 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 *GetAccountInfoRequest) GetParameters() (map[string]interface{}, error) {
var params = map[string]interface{}{}
return params, nil
}
// GetParametersQuery converts the parameters from GetParameters into the url.Values format
func (g *GetAccountInfoRequest) 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 *GetAccountInfoRequest) 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 *GetAccountInfoRequest) GetSlugParameters() (map[string]interface{}, error) {
var params = map[string]interface{}{}
return params, nil
}
func (g *GetAccountInfoRequest) 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 *GetAccountInfoRequest) 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 *GetAccountInfoRequest) isVarSlice(_v interface{}) bool {
rt := reflect.TypeOf(_v)
switch rt.Kind() {
case reflect.Slice:
return true
}
return false
}
func (g *GetAccountInfoRequest) 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 *GetAccountInfoRequest) GetPath() string {
return "/api/v5/account/balance"
}
// Do generates the request object and send the request object to the API endpoint
func (g *GetAccountInfoRequest) Do(ctx context.Context) ([]Account, error) {
// no body params
var params interface{}
query := url.Values{}
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 APIResponse
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
}
type responseValidator interface {
Validate() error
}
validator, ok := interface{}(apiResponse).(responseValidator)
if ok {
if err := validator.Validate(); err != nil {
return nil, err
}
}
var data []Account
if err := json.Unmarshal(apiResponse.Data, &data); err != nil {
return nil, err
}
return data, nil
}