Files
gocryptotrader/currency/forexprovider/fixer.io/fixer.go
Scott fcc5ad4551 exchanges/qa: Add exchange wrapper testing suite (#1159)
* initial concept of a nice validation tester for exchanges

* adds some datahandler design

* expand testing

* more tests and fixes

* minor end of day fix for bithumb

* fixes implementation issues

* more test coverage and improvements, but not sure if i should continue

* fix more wrapper implementations

* adds error type, more fixes

* changes signature, fixes implementations

* fixes more wrapper implementations

* one more bit

* more cleanup

* WOW things work?

* lintle 1/1337

* mini bump

* fixes all linting

* neaten

* GetOrderInfo+ asset pair fixes+improvements

* adds new websocket test

* expand ws testing

* fix bug, expand tests, improve implementation

* code coverage of a lot of new codes

* fixes everything

* reverts accidental changes

* minor fixes from reviewing code

* removes Bitfinex cancelBatchOrder implementation

* fixes dumb baby typo for babies

* mini nit fixes

* so many nits to address

* addresses all the nits

* Titlecase

* switcheroo

* removes websocket testing for now

* fix appveyor, minor test fix

* fixes typo, re-kindles killed kode

* skip binance wrapper tests when running CI

* expired context, huobi okx fixes

* kodespull

* fix ordering

* time fix because why not

* fix exmo, others

* hopefully this fixes all of my life's problems

* last thing today

* huobi, more like hypotrophy

* golangci-lint, more like mypooroldknee-splint

* fix huobi times by removing them

* should fix okx currency issues

* blocks the application

* adds last little contingency for pairs

* addresses most nits and new problems

* lovely fixed before seeing why okx sucks

* fixes issues with okx websocket

* the classic receieieivaier

* lintle

* adds test and fixes existing tests

* expands error handling messages during setup

* fixes dumb okx bugs introduced

* quick fix for lint and exmo

* fixes nixes

* fix exmo deposit issue

* lint

* fixes issue with extra asset runs missing

* fix surprise race

* all the lint and merge fixes

* fixes surprise bugs in OKx

* fixes issues with times and chains

* fixing all the merge stuff

* merge fix

* rm logs and a panic potential

* lovely lint lament

* an easy demonstration of scenario, but not of initial purpose

* put it in the bin

* Revert "put it in the bin"

This reverts commit 15c6490f713233d43f10957367fcbf18e3818bdd.

* re-add after immediate error popup

* fix mini poor test design

* okx okay

* merge fixes

* fixes issues discovered in lovely test

* I FORGOT TO COMMIT THIS

* nit fixaroonaboo

* forgoetten test fix

* revert old okx asset intrument work

* fixes

* revert problems I didnt understand. update bybit

* fix merge bugs

* test cleanup

* further improvements

* reshuffle and lint

* rm redundant CI_TEST by rm the CI_TEST field that is redundant

* path fix

* move to its own section, dont run on 32 bit + appveyor

* lint

* fix lbank

* address nits

* let it rip

* fix failing test time range

* niteroo boogaloo

* mod tidy, use common.SimpleTimeFormat
2023-07-03 11:09:43 +10:00

246 lines
6.9 KiB
Go

// Powered by 15+ exchange rate data sources, the Fixer API is capable of
// delivering real-time exchange rate data for 170 world currencies. The API
// comes with multiple endpoints, each serving a different use case. Endpoint
// functionalities include getting the latest exchange rate data for all or a
// specific set of currencies, converting amounts from one currency to another,
// retrieving Time-Series data for one or multiple currencies and querying the
// API for daily fluctuation data.
package fixer
import (
"context"
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
"github.com/thrasher-corp/gocryptotrader/log"
)
// Setup sets appropriate values for fixer object
func (f *Fixer) Setup(config base.Settings) error {
if config.APIKeyLvl < 0 || config.APIKeyLvl > 4 {
log.Errorf(log.Global,
"apikey incorrectly set in config.json for %s, please set appropriate account levels\n",
config.Name)
return errors.New("apikey set failure")
}
f.APIKey = config.APIKey
f.APIKeyLvl = config.APIKeyLvl
f.Enabled = config.Enabled
f.Name = config.Name
f.Verbose = config.Verbose
f.PrimaryProvider = config.PrimaryProvider
var err error
f.Requester, err = request.New(f.Name,
common.NewHTTPClientWithTimeout(base.DefaultTimeOut))
return err
}
// GetSupportedCurrencies returns supported currencies
func (f *Fixer) GetSupportedCurrencies() ([]string, error) {
var resp Symbols
err := f.SendOpenHTTPRequest(fixerSupportedCurrencies, nil, &resp)
if err != nil {
return nil, err
}
if !resp.Success {
return nil, errors.New(resp.Error.Type + resp.Error.Info)
}
currencies := make([]string, 0, len(resp.Map))
for key := range resp.Map {
currencies = append(currencies, key)
}
return currencies, nil
}
// GetRates is a wrapper function to return rates
func (f *Fixer) GetRates(baseCurrency, symbols string) (map[string]float64, error) {
rates, err := f.GetLatestRates(baseCurrency, symbols)
if err != nil {
return nil, err
}
if f.APIKeyLvl == fixerAPIFree {
baseCurrency = "EUR"
}
standardisedRates := make(map[string]float64)
for k, v := range rates {
curr := baseCurrency + k
standardisedRates[curr] = v
}
return standardisedRates, nil
}
// GetLatestRates returns real-time exchange rate data for all available or a
// specific set of currencies. NOTE DEFAULT BASE CURRENCY IS EUR
func (f *Fixer) GetLatestRates(baseCurrency, symbols string) (map[string]float64, error) {
var resp Rates
v := url.Values{}
if f.APIKeyLvl > fixerAPIFree {
v.Add("base", baseCurrency)
}
v.Add("symbols", symbols)
err := f.SendOpenHTTPRequest(fixerAPILatest, v, &resp)
if err != nil {
return resp.Rates, err
}
if !resp.Success {
return resp.Rates, errors.New(resp.Error.Type + resp.Error.Info)
}
return resp.Rates, nil
}
// GetHistoricalRates returns historical exchange rate data for all available or
// a specific set of currencies.
// date - YYYY-MM-DD [required] A date in the past
// base - USD [optional]
// symbols - the desired symbols
func (f *Fixer) GetHistoricalRates(date, baseCurrency string, symbols []string) (map[string]float64, error) {
var resp Rates
v := url.Values{}
v.Set("symbols", strings.Join(symbols, ","))
if baseCurrency != "" {
v.Set("base", baseCurrency)
}
err := f.SendOpenHTTPRequest(date, v, &resp)
if err != nil {
return resp.Rates, err
}
if !resp.Success {
return resp.Rates, errors.New(resp.Error.Type + resp.Error.Info)
}
return resp.Rates, nil
}
// ConvertCurrency allows for conversion of any amount from one currency to
// another.
// from - The three-letter currency code of the currency you would like to
// convert from.
// to - The three-letter currency code of the currency you would like to convert
// to.
// amount - The amount to be converted.
// date - [optional] Specify a date (format YYYY-MM-DD) to use historical rates
// for this conversion.
func (f *Fixer) ConvertCurrency(from, to, date string, amount float64) (float64, error) {
if f.APIKeyLvl < fixerAPIBasic {
return 0, errors.New("insufficient API privileges, upgrade to basic to use this function")
}
var resp Conversion
v := url.Values{}
v.Set("from", from)
v.Set("to", to)
v.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
v.Set("date", date)
err := f.SendOpenHTTPRequest(fixerAPIConvert, v, &resp)
if err != nil {
return resp.Result, err
}
if !resp.Success {
return resp.Result, errors.New(resp.Error.Type + resp.Error.Info)
}
return resp.Result, nil
}
// GetTimeSeriesData returns daily historical exchange rate data between two
// specified dates for all available or a specific set of currencies.
func (f *Fixer) GetTimeSeriesData(startDate, endDate, baseCurrency string, symbols []string) (map[string]interface{}, error) {
if f.APIKeyLvl < fixerAPIProfessional {
return nil, errors.New("insufficient API privileges, upgrade to professional to use this function")
}
var resp TimeSeries
v := url.Values{}
v.Set("start_date", startDate)
v.Set("end_date", endDate)
v.Set("base", baseCurrency)
v.Set("symbols", strings.Join(symbols, ","))
err := f.SendOpenHTTPRequest(fixerAPITimeSeries, v, &resp)
if err != nil {
return resp.Rates, err
}
if !resp.Success {
return resp.Rates, errors.New(resp.Error.Type + resp.Error.Info)
}
return resp.Rates, nil
}
// GetFluctuationData returns fluctuation data between two specified dates for
// all available or a specific set of currencies.
func (f *Fixer) GetFluctuationData(startDate, endDate, baseCurrency string, symbols []string) (map[string]Flux, error) {
if f.APIKeyLvl < fixerAPIProfessionalPlus {
return nil, errors.New("insufficient API privileges, upgrade to professional plus or enterprise to use this function")
}
var resp Fluctuation
v := url.Values{}
v.Set("start_date", startDate)
v.Set("end_date", endDate)
v.Set("base", baseCurrency)
v.Set("symbols", strings.Join(symbols, ","))
err := f.SendOpenHTTPRequest(fixerAPIFluctuation, v, &resp)
if err != nil {
return resp.Rates, err
}
if !resp.Success {
return resp.Rates, errors.New(resp.Error.Type + resp.Error.Info)
}
return resp.Rates, nil
}
// SendOpenHTTPRequest sends a typical get request
func (f *Fixer) SendOpenHTTPRequest(endpoint string, v url.Values, result interface{}) error {
if v == nil {
v = url.Values{}
}
v.Set("access_key", f.APIKey)
var auth request.AuthType
var path string
if f.APIKeyLvl == fixerAPIFree {
path = fixerAPI + endpoint + "?" + v.Encode()
auth = request.UnauthenticatedRequest
} else {
path = fixerAPISSL + endpoint + "?" + v.Encode()
auth = request.AuthenticatedRequest
}
item := &request.Item{
Method: http.MethodGet,
Path: path,
Result: &result,
Verbose: f.Verbose}
return f.Requester.SendPayload(context.Background(), request.Unset, func() (*request.Item, error) {
return item, nil
}, auth)
}