github.com/bitfinexcom/bitfinex-api-go@v0.0.0-20210608095005-9e0b26f200fb/v2/rest/market.go (about)

     1  package rest
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/url"
     7  	"path"
     8  	"strconv"
     9  
    10  	"github.com/bitfinexcom/bitfinex-api-go/pkg/convert"
    11  )
    12  
    13  type MarketService struct {
    14  	requestFactory
    15  	Synchronous
    16  }
    17  
    18  // AveragePriceRequest data structure for constructing average price query params
    19  type AveragePriceRequest struct {
    20  	Symbol    string
    21  	Amount    string
    22  	RateLimit string
    23  	Period    int
    24  }
    25  
    26  // ForeignExchangeRateRequest data structure for constructing foreign
    27  // exchange rate request payload
    28  type ForeignExchangeRateRequest struct {
    29  	FirstCurrency  string `json:"ccy1"`
    30  	SecondCurrency string `json:"ccy2"`
    31  }
    32  
    33  // AveragePrice Calculate the average execution price for Trading or rate for Margin funding.
    34  // See: https://docs.bitfinex.com/reference#rest-public-calc-market-average-price
    35  func (ms *MarketService) AveragePrice(pld AveragePriceRequest) ([]float64, error) {
    36  	req := NewRequestWithMethod(path.Join("calc", "trade", "avg"), "POST")
    37  	req.Params = make(url.Values)
    38  	req.Params.Add("symbol", pld.Symbol)
    39  	req.Params.Add("amount", pld.Amount)
    40  	req.Params.Add("rate_limit", pld.RateLimit)
    41  	req.Params.Add("period", strconv.Itoa(pld.Period))
    42  
    43  	raw, err := ms.Request(req)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  
    48  	resp, err := convert.F64Slice(raw)
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  
    53  	return resp, nil
    54  }
    55  
    56  // ForeignExchangeRate - Calculate the exchange rate between two currencies
    57  // See: https://docs.bitfinex.com/reference#rest-public-calc-foreign-exchange-rate
    58  func (ms *MarketService) ForeignExchangeRate(pld ForeignExchangeRateRequest) ([]float64, error) {
    59  	if len(pld.FirstCurrency) == 0 || len(pld.SecondCurrency) == 0 {
    60  		return nil, fmt.Errorf("FirstCurrency and SecondCurrency are required arguments")
    61  	}
    62  
    63  	bytes, err := json.Marshal(pld)
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  
    68  	req := NewRequestWithBytes(path.Join("calc", "fx"), bytes)
    69  	req.Headers["Content-Type"] = "application/json"
    70  
    71  	raw, err := ms.Request(req)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  
    76  	resp, err := convert.F64Slice(raw)
    77  	if err != nil {
    78  		return nil, err
    79  	}
    80  
    81  	return resp, nil
    82  }