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

376 lines
9.2 KiB
Go
Raw Permalink Normal View History

2021-05-22 19:34:40 +00:00
package okexapi
import (
"bytes"
2023-09-06 11:14:21 +00:00
"context"
2021-05-22 19:34:40 +00:00
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
2021-05-23 05:44:08 +00:00
"fmt"
2021-05-22 19:34:40 +00:00
"net/http"
"net/url"
"strings"
"time"
2021-05-23 05:44:08 +00:00
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
2023-09-06 11:14:21 +00:00
"github.com/c9s/requestgen"
2021-05-22 19:34:40 +00:00
"github.com/pkg/errors"
)
2021-05-23 04:11:27 +00:00
const defaultHTTPTimeout = time.Second * 15
2021-05-22 19:34:40 +00:00
const RestBaseURL = "https://www.okex.com/"
const PublicWebSocketURL = "wss://ws.okex.com:8443/ws/v5/public"
const PrivateWebSocketURL = "wss://ws.okex.com:8443/ws/v5/private"
type SideType string
const (
SideTypeBuy SideType = "buy"
SideTypeSell SideType = "sell"
)
type OrderType string
const (
2023-08-22 07:14:18 +00:00
OrderTypeMarket OrderType = "market"
OrderTypeLimit OrderType = "limit"
OrderTypePostOnly OrderType = "post_only"
OrderTypeFOK OrderType = "fok"
OrderTypeIOC OrderType = "ioc"
2021-05-24 16:50:53 +00:00
)
type InstrumentType string
const (
InstrumentTypeSpot InstrumentType = "SPOT"
InstrumentTypeSwap InstrumentType = "SWAP"
InstrumentTypeFutures InstrumentType = "FUTURES"
InstrumentTypeOption InstrumentType = "OPTION"
2023-08-11 01:28:58 +00:00
InstrumentTypeMARGIN InstrumentType = "MARGIN"
)
2021-05-24 16:50:53 +00:00
type OrderState string
const (
OrderStateCanceled OrderState = "canceled"
OrderStateLive OrderState = "live"
OrderStatePartiallyFilled OrderState = "partially_filled"
OrderStateFilled OrderState = "filled"
)
2021-05-22 19:34:40 +00:00
type RestClient struct {
2023-09-06 11:14:21 +00:00
requestgen.BaseAPIClient
2021-05-23 04:11:27 +00:00
2021-05-22 19:34:40 +00:00
Key, Secret, Passphrase string
}
2023-09-06 13:21:13 +00:00
var parsedBaseURL *url.URL
func init() {
url, err := url.Parse(RestBaseURL)
2021-05-22 19:34:40 +00:00
if err != nil {
2023-09-06 13:21:13 +00:00
panic(err)
2021-05-22 19:34:40 +00:00
}
2023-09-06 13:21:13 +00:00
parsedBaseURL = url
}
2021-05-22 19:34:40 +00:00
2023-09-06 13:21:13 +00:00
func NewClient() *RestClient {
client := &RestClient{
2023-09-06 11:14:21 +00:00
BaseAPIClient: requestgen.BaseAPIClient{
2023-09-06 13:21:13 +00:00
BaseURL: parsedBaseURL,
2023-09-06 11:14:21 +00:00
HttpClient: &http.Client{
Timeout: defaultHTTPTimeout,
},
2021-05-23 04:11:27 +00:00
},
2021-05-22 19:34:40 +00:00
}
2023-09-06 13:21:13 +00:00
return client
2021-05-22 19:34:40 +00:00
}
func (c *RestClient) Auth(key, secret, passphrase string) {
c.Key = key
2022-06-17 07:04:23 +00:00
// pragma: allowlist nextline secret
2021-05-22 19:34:40 +00:00
c.Secret = secret
c.Passphrase = passphrase
}
2023-09-06 11:14:21 +00:00
// NewAuthenticatedRequest creates new http request for authenticated routes.
func (c *RestClient) NewAuthenticatedRequest(ctx context.Context, method, refURL string, params url.Values, payload interface{}) (*http.Request, error) {
2021-05-22 19:34:40 +00:00
if len(c.Key) == 0 {
return nil, errors.New("empty api key")
}
if len(c.Secret) == 0 {
return nil, errors.New("empty api secret")
}
rel, err := url.Parse(refURL)
if err != nil {
return nil, err
}
if params != nil {
rel.RawQuery = params.Encode()
}
pathURL := c.BaseURL.ResolveReference(rel)
path := pathURL.Path
if rel.RawQuery != "" {
path += "?" + rel.RawQuery
}
2021-05-22 19:34:40 +00:00
2021-05-23 04:11:27 +00:00
// set location to UTC so that it outputs "2020-12-08T09:08:57.715Z"
t := time.Now().In(time.UTC)
2021-05-22 19:34:40 +00:00
timestamp := t.Format("2006-01-02T15:04:05.999Z07:00")
2021-05-23 04:11:27 +00:00
2021-05-22 19:34:40 +00:00
var body []byte
if payload != nil {
switch v := payload.(type) {
case string:
body = []byte(v)
case []byte:
body = v
default:
body, err = json.Marshal(v)
if err != nil {
return nil, err
}
}
}
signKey := timestamp + strings.ToUpper(method) + path + string(body)
signature := Sign(signKey, c.Secret)
2021-05-22 19:34:40 +00:00
req, err := http.NewRequest(method, pathURL.String(), bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
req.Header.Add("OK-ACCESS-KEY", c.Key)
req.Header.Add("OK-ACCESS-SIGN", signature)
2021-05-22 19:34:40 +00:00
req.Header.Add("OK-ACCESS-TIMESTAMP", timestamp)
req.Header.Add("OK-ACCESS-PASSPHRASE", c.Passphrase)
return req, nil
}
2021-05-23 04:11:27 +00:00
type BalanceDetail struct {
2021-05-23 05:45:17 +00:00
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"`
2021-05-23 04:11:27 +00:00
}
type Account struct {
2021-05-23 05:45:17 +00:00
TotalEquityInUSD fixedpoint.Value `json:"totalEq"`
UpdateTime string `json:"uTime"`
Details []BalanceDetail `json:"details"`
2021-05-23 04:11:27 +00:00
}
2023-09-06 11:14:21 +00:00
func (c *RestClient) AccountBalances(ctx context.Context) (*Account, error) {
req, err := c.NewAuthenticatedRequest(ctx, "GET", "/api/v5/account/balance", nil, nil)
2021-05-23 04:11:27 +00:00
if err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
response, err := c.SendRequest(req)
2021-05-23 04:11:27 +00:00
if err != nil {
return nil, err
}
var balanceResponse struct {
Code string `json:"code"`
Message string `json:"msg"`
Data []Account `json:"data"`
2021-05-23 04:11:27 +00:00
}
2021-05-23 04:11:27 +00:00
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
2021-05-23 04:11:27 +00:00
}
2021-05-23 05:44:08 +00:00
type AssetBalance struct {
2021-05-23 05:45:17 +00:00
Currency string `json:"ccy"`
Balance fixedpoint.Value `json:"bal"`
Frozen fixedpoint.Value `json:"frozenBal,omitempty"`
Available fixedpoint.Value `json:"availBal,omitempty"`
2021-05-23 05:44:08 +00:00
}
type AssetBalanceList []AssetBalance
2023-09-06 11:14:21 +00:00
func (c *RestClient) AssetBalances(ctx context.Context) (AssetBalanceList, error) {
req, err := c.NewAuthenticatedRequest(ctx, "GET", "/api/v5/asset/balances", nil, nil)
2021-05-23 05:44:08 +00:00
if err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
response, err := c.SendRequest(req)
2021-05-23 05:44:08 +00:00
if err != nil {
return nil, err
}
var balanceResponse struct {
Code string `json:"code"`
Message string `json:"msg"`
Data AssetBalanceList `json:"data"`
}
if err := response.DecodeJSON(&balanceResponse); err != nil {
return nil, err
}
return balanceResponse.Data, nil
}
type AssetCurrency struct {
2021-05-23 05:45:17 +00:00
Currency string `json:"ccy"`
Name string `json:"name"`
Chain string `json:"chain"`
CanDeposit bool `json:"canDep"`
CanWithdraw bool `json:"canWd"`
CanInternal bool `json:"canInternal"`
MinWithdrawalFee fixedpoint.Value `json:"minFee"`
MaxWithdrawalFee fixedpoint.Value `json:"maxFee"`
MinWithdrawalThreshold fixedpoint.Value `json:"minWd"`
2021-05-23 05:44:08 +00:00
}
2023-09-06 11:14:21 +00:00
func (c *RestClient) AssetCurrencies(ctx context.Context) ([]AssetCurrency, error) {
req, err := c.NewAuthenticatedRequest(ctx, "GET", "/api/v5/asset/currencies", nil, nil)
2021-05-23 05:44:08 +00:00
if err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
response, err := c.SendRequest(req)
2021-05-23 05:44:08 +00:00
if err != nil {
return nil, err
}
var currencyResponse struct {
Code string `json:"code"`
Message string `json:"msg"`
Data []AssetCurrency `json:"data"`
}
if err := response.DecodeJSON(&currencyResponse); err != nil {
return nil, err
}
return currencyResponse.Data, nil
}
type MarketTicker struct {
InstrumentType string `json:"instType"`
InstrumentID string `json:"instId"`
// last traded price
Last fixedpoint.Value `json:"last"`
// last traded size
LastSize fixedpoint.Value `json:"lastSz"`
AskPrice fixedpoint.Value `json:"askPx"`
AskSize fixedpoint.Value `json:"askSz"`
BidPrice fixedpoint.Value `json:"bidPx"`
BidSize fixedpoint.Value `json:"bidSz"`
Open24H fixedpoint.Value `json:"open24h"`
High24H fixedpoint.Value `json:"high24H"`
Low24H fixedpoint.Value `json:"low24H"`
Volume24H fixedpoint.Value `json:"vol24h"`
VolumeCurrency24H fixedpoint.Value `json:"volCcy24h"`
// Millisecond timestamp
Timestamp types.MillisecondTimestamp `json:"ts"`
}
2023-09-06 11:14:21 +00:00
func (c *RestClient) MarketTicker(ctx context.Context, instId string) (*MarketTicker, error) {
2021-05-23 05:44:08 +00:00
// SPOT, SWAP, FUTURES, OPTION
var params = url.Values{}
params.Add("instId", instId)
2023-09-06 11:14:21 +00:00
req, err := c.NewRequest(ctx, "GET", "/api/v5/market/ticker", params, nil)
2021-05-23 05:44:08 +00:00
if err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
response, err := c.SendRequest(req)
2021-05-23 05:44:08 +00:00
if err != nil {
return nil, err
}
var tickerResponse struct {
Code string `json:"code"`
Message string `json:"msg"`
Data []MarketTicker `json:"data"`
}
if err := response.DecodeJSON(&tickerResponse); err != nil {
return nil, err
}
if len(tickerResponse.Data) == 0 {
return nil, fmt.Errorf("ticker of %s not found", instId)
}
return &tickerResponse.Data[0], nil
}
2023-09-06 11:14:21 +00:00
func (c *RestClient) MarketTickers(ctx context.Context, instType InstrumentType) ([]MarketTicker, error) {
2021-05-23 05:44:08 +00:00
// SPOT, SWAP, FUTURES, OPTION
var params = url.Values{}
2021-05-25 19:04:49 +00:00
params.Add("instType", string(instType))
2021-05-23 05:44:08 +00:00
2023-09-06 11:14:21 +00:00
req, err := c.NewRequest(ctx, "GET", "/api/v5/market/tickers", params, nil)
2021-05-23 05:44:08 +00:00
if err != nil {
return nil, err
}
2023-09-06 11:14:21 +00:00
response, err := c.SendRequest(req)
2021-05-23 05:44:08 +00:00
if err != nil {
return nil, err
}
var tickerResponse struct {
Code string `json:"code"`
Message string `json:"msg"`
Data []MarketTicker `json:"data"`
}
if err := response.DecodeJSON(&tickerResponse); err != nil {
return nil, err
}
return tickerResponse.Data, nil
}
func Sign(payload string, secret string) string {
2021-05-22 19:34:40 +00:00
var sig = hmac.New(sha256.New, []byte(secret))
_, err := sig.Write([]byte(payload))
if err != nil {
return ""
}
return base64.StdEncoding.EncodeToString(sig.Sum(nil))
// return hex.EncodeToString(sig.Sum(nil))
}
2023-09-06 11:14:21 +00:00
type APIResponse struct {
Code string `json:"code"`
Message string `json:"msg"`
Data json.RawMessage `json:"data"`
}