bbgo_origin/pkg/exchange/okex/okexapi/market.go

103 lines
2.1 KiB
Go
Raw Normal View History

package okexapi
import (
"context"
2023-09-06 11:14:21 +00:00
"encoding/json"
"fmt"
"net/url"
)
type MarketTickersRequest struct {
client *RestClient
instType string
}
func (r *MarketTickersRequest) InstrumentType(instType string) *MarketTickersRequest {
r.instType = instType
return r
}
func (r *MarketTickersRequest) Do(ctx context.Context) ([]MarketTicker, error) {
// SPOT, SWAP, FUTURES, OPTION
var params = url.Values{}
params.Add("instType", string(r.instType))
2023-09-06 11:14:21 +00:00
req, err := r.client.NewRequest(ctx, "GET", "/api/v5/market/tickers", params, nil)
if err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
response, err := r.client.SendRequest(req)
if err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
var apiResponse APIResponse
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
var data []MarketTicker
if err := json.Unmarshal(apiResponse.Data, &data); err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
return data, nil
}
type MarketTickerRequest struct {
client *RestClient
instId string
}
func (r *MarketTickerRequest) InstrumentID(instId string) *MarketTickerRequest {
r.instId = instId
return r
}
func (r *MarketTickerRequest) Do(ctx context.Context) (*MarketTicker, error) {
// SPOT, SWAP, FUTURES, OPTION
var params = url.Values{}
params.Add("instId", r.instId)
2023-09-06 11:14:21 +00:00
req, err := r.client.NewRequest(ctx, "GET", "/api/v5/market/ticker", params, nil)
if err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
response, err := r.client.SendRequest(req)
if err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
var apiResponse APIResponse
if err := response.DecodeJSON(&apiResponse); err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
var data []MarketTicker
if err := json.Unmarshal(apiResponse.Data, &data); err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
if len(data) == 0 {
return nil, fmt.Errorf("ticker of %s not found", r.instId)
}
2023-09-06 11:14:21 +00:00
return &data[0], nil
}
2023-09-06 11:14:21 +00:00
func (c *RestClient) NewMarketTickerRequest(instId string) *MarketTickerRequest {
return &MarketTickerRequest{
2023-09-06 11:14:21 +00:00
client: c,
instId: instId,
}
}
2023-09-06 11:14:21 +00:00
func (c *RestClient) NewMarketTickersRequest(instType string) *MarketTickersRequest {
return &MarketTickersRequest{
2023-09-06 11:14:21 +00:00
client: c,
instType: instType,
}
}