bsvrates

package module
v0.4.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 14, 2023 License: MIT Imports: 14 Imported by: 0

README

go-bsvrates

Real-time exchange rates for BitcoinSV using multiple providers with fail-over support

Release Build Status Report codecov Go
Mergify Status Gitpod Ready-to-Code


Table of Contents


Installation

go-bsvrates requires a supported release of Go.

go get -u github.com/tonicpow/go-bsvrates

Documentation

View the generated documentation

GoDoc

Features
Library Deployment

goreleaser for easy binary or library deployment to GitHub and can be installed via: brew install goreleaser.

The .goreleaser.yml file is used to configure goreleaser.

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production.

Makefile Commands

View all makefile commands

make help

List of all current commands:

all                   Runs lint, test and vet
clean                 Remove previous builds and any test cache data
clean-mods            Remove all the Go mod cache
coverage              Shows the test coverage
diff                  Show the git diff
generate              Runs the go generate command in the base of the repo
godocs                Sync the latest tag with GoDocs
help                  Show this help message
install               Install the application
install-go            Install the application (Using Native Go)
install-releaser      Install the GoReleaser application
lint                  Run the golangci-lint application (install if not found)
release               Full production release (creates release in Github)
release               Runs common.release then runs godocs
release-snap          Test the full release (build binaries)
release-test          Full production test release (everything except deploy)
replace-version       Replaces the version in HTML/JS (pre-deploy)
run-examples          Runs the basic example
tag                   Generate a new tag and push (tag version=0.0.0)
tag-remove            Remove a tag if found (tag-remove version=0.0.0)
tag-update            Update an existing tag to current commit (tag-update version=0.0.0)
test                  Runs lint and ALL tests
test-ci               Runs all tests via CI (exports coverage)
test-ci-no-race       Runs all tests via CI (no race) (exports coverage)
test-ci-short         Runs unit tests via CI (exports coverage)
test-no-lint          Runs just tests
test-short            Runs vet, lint and tests (excludes integration tests)
test-unit             Runs tests and outputs coverage
uninstall             Uninstall the application (and remove files)
update-linter         Update the golangci-lint package (macOS only)
vet                   Run the Go vet application

Examples & Tests

All unit tests and examples run via GitHub Actions and uses Go version 1.18.x. View the configuration file.

Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Benchmarks

Run the Go benchmarks:

make bench

Code Standards

Read more about this Go project's code standards.


Usage

View the examples

Basic exchange rate implementation:

package main

import (
  "context"
  "log"

  "github.com/tonicpow/go-bsvrates"
)

func main() {

  // Create a new client (all default providers)
  client := bsvrates.NewClient(nil, nil)

  // Get rates
  rate, provider, _ := client.GetRate(context.Background(), bsvrates.CurrencyDollars)
  log.Printf("found rate: %v %s from provider: %s", rate, bsvrates.CurrencyToName(bsvrates.CurrencyDollars), provider.Name())
}

Basic price conversion implementation:

package main

import (
    "context"
    "log"

	"github.com/tonicpow/go-bsvrates"
)

func main() {

	// Create a new client (all default providers)
	client := bsvrates.NewClient(nil, nil)
    
	// Get a conversion from $ to Sats
	satoshis, provider, _ := client.GetConversion(context.Background(),bsvrates.CurrencyDollars, 0.01)
	log.Printf("0.01 USD = satoshis: %d from provider: %s", satoshis, provider.Name())
}

Maintainers

MrZ
MrZ

Contributing

View the contributing guidelines and please follow the code of conduct.

How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬. You can also support this project by becoming a sponsor on GitHub 👏 or by making a bitcoin donation to ensure this journey continues indefinitely! 🚀

Stars


Credits

Coin Paprika and What's On Chain for their hard work on their public API

Jad for his contributions to the package!


License

License

Documentation

Overview

Package bsvrates brings multiple providers into one place to obtain the current BSV exchange rate

Index

Examples

Constants

View Source
const (
	AUDCurrencyID = "aud-australian-dollar"
	BRLCurrencyID = "brl-brazil-real"
	CADCurrencyID = "cad-canadian-dollar"
	CHFCurrencyID = "chf-swiss-franc"
	CNYCurrencyID = "cny-yuan-renminbi"
	EURCurrencyID = "eur-euro"
	GBPCurrencyID = "gbp-pound-sterling"
	JPYCurrencyID = "jpy-japanese-yen"
	KRWCurrencyID = "krw-south-korea-won"
	MXNCurrencyID = "mxn-mexican-peso"
	NEWCurrencyID = "new-zealand-dollar"
	NOKCurrencyID = "nok-norwegian-krone"
	PLNCurrencyID = "pln-polish-zloty"
	RUBCurrencyID = "rub-russian-ruble"
	SEKCurrencyID = "sek-swedish-krona"
	TRYCurrencyID = "try-turkish-lira"
	TWDCurrencyID = "twd-taiwan-new-dollar"
	USDCurrencyID = usd + "-us-dollars"
	ZARCurrencyID = "zar-south-african-rand"
)

List of accepted known currencies (works for CoinPaprika only)

View Source
const (
	TickerQuoteUSD tickerQuote = "usd"
	TickerQuoteBTC tickerQuote = "btc"
)

Quote types

View Source
const (
	TickerInterval5m   tickerInterval = "5m"
	TickerInterval10m  tickerInterval = "10m"
	TickerInterval15m  tickerInterval = "15m"
	TickerInterval30m  tickerInterval = "30m"
	TickerInterval45m  tickerInterval = "45m"
	TickerInterval1h   tickerInterval = "1h"
	TickerInterval2h   tickerInterval = "2h"
	TickerInterval3h   tickerInterval = "3h"
	TickerInterval6h   tickerInterval = "6h"
	TickerInterval12h  tickerInterval = "12h"
	TickerInterval24h  tickerInterval = "24h"
	TickerInterval1d   tickerInterval = "1d"
	TickerInterval7d   tickerInterval = "7d"
	TickerInterval14d  tickerInterval = "14d"
	TickerInterval30d  tickerInterval = "30d"
	TickerInterval90d  tickerInterval = "90d"
	TickerInterval365d tickerInterval = "365d"
)

Interval types

View Source
const (
	CurrencyDollars = 1
	CurrencyBitcoin = 2
)

Currency constants for the different available currencies. Leave the start and last constants in place

View Source
const (

	// CoinPaprikaQuoteID is the id for CoinPaprika (BSV)
	CoinPaprikaQuoteID = "bsv-bitcoin-sv"
)
View Source
const SatoshisPerBitcoin = 1e8

SatoshisPerBitcoin is the fixed amount of Satoshis per Bitcoin denomination

Variables

This section is empty.

Functions

func ConvertFloatToIntBSV

func ConvertFloatToIntBSV(floatValue float64) int64

ConvertFloatToIntBSV converts the BSV float value to the satoshis int value

Example

ExampleConvertFloatToIntBSV example using ConvertFloatToIntBSV()

val := ConvertFloatToIntBSV(10.01)
fmt.Printf("%d", val)
Output:

1001000000

func ConvertFloatToIntUSD

func ConvertFloatToIntUSD(floatValue float64) int64

ConvertFloatToIntUSD converts a float to int

func ConvertIntToFloatUSD added in v0.1.3

func ConvertIntToFloatUSD(cents uint64) float64

ConvertIntToFloatUSD converts int to float (int cents to float dollars)

Example

ExampleConvertIntToFloatUSD example using ConvertIntToFloatUSD()

val := ConvertIntToFloatUSD(1000000)
fmt.Printf("%f", val)
Output:

10000.000000

func ConvertPriceToSatoshis

func ConvertPriceToSatoshis(currentRate float64, amount float64) (int64, error)

ConvertPriceToSatoshis will get the satoshis (amount) from the current rate. IE: 1 BSV = $150 and you want to know what $1 is in satoshis

Example

ExampleConvertPriceToSatoshis example using ConvertPriceToSatoshis()

val, _ := ConvertPriceToSatoshis(150, 1)
fmt.Printf("%d", val)
Output:

666667

func ConvertSatsToBSV

func ConvertSatsToBSV(satoshis int) float64

ConvertSatsToBSV converts satoshis to bsv

Example

ExampleConvertSatsToBSV example using ConvertSatsToBSV()

val := ConvertSatsToBSV(1001)
fmt.Printf("%f", val)
Output:

0.000010

func CurrencyToName

func CurrencyToName(currency Currency) string

CurrencyToName helper function to convert the currency value to it's associated name

func FormatCentsToDollars

func FormatCentsToDollars(cents int) string

FormatCentsToDollars formats the integer for currency in USD (cents to dollars)

Example

ExampleFormatCentsToDollars example using FormatCentsToDollars()

val := FormatCentsToDollars(1000)
fmt.Printf("%s", val)
Output:

10.00

func FormatCommas

func FormatCommas(num int) string

FormatCommas formats the integer with strings

Example

ExampleFormatCommas example using FormatCommas()

val := FormatCommas(1000000)
fmt.Printf("%s", val)
Output:

1,000,000

func GetCentsFromSatoshis added in v0.1.10

func GetCentsFromSatoshis(currentBSVRate float64, satoshis int64) int64

GetCentsFromSatoshis will return the cents (USD) of the given amount of satoshis IE: Current rate is $100 per 1 BSV... Supplying 1000000 satoshis should produce 100 cents

Example

ExampleGetCentsFromSatoshis example using GetCentsFromSatoshis()

cents := GetCentsFromSatoshis(100, 20000)
fmt.Printf("%d", cents)
Output:

2

func GetDollarsFromSatoshis added in v0.1.10

func GetDollarsFromSatoshis(currentBSVRate float64, satoshis int64) (dollars float64)

GetDollarsFromSatoshis will return the dollars (USD) of the given amount of satoshis IE: Current rate is $100 per 1 BSV... Supplying 100000000 satoshis should produce 1 dollar

Example

ExampleGetDollarsFromSatoshis example using GetDollarsFromSatoshis()

dollars := GetDollarsFromSatoshis(100, 10000)
fmt.Printf("%f", dollars)
Output:

0.010000

func ProviderToName

func ProviderToName(provider Provider) string

ProviderToName helper function to convert the provider value to it's associated name

func TransformCurrencyToInt

func TransformCurrencyToInt(decimalValue float64, currency Currency) (int64, error)

TransformCurrencyToInt takes the decimal format of the currency and returns the integer value Currently only supports USD and BSV

Example

ExampleTransformCurrencyToInt example using TransformCurrencyToInt()

val, _ := TransformCurrencyToInt(10.00, CurrencyDollars)
fmt.Printf("%d", val)
Output:

1000

func TransformIntToCurrency

func TransformIntToCurrency(intValue int, currency Currency) (string, error)

TransformIntToCurrency will take the int and return a float value. Currently, only supports USD and BSV

Example

ExampleTransformIntToCurrency example using TransformIntToCurrency()

val, _ := TransformIntToCurrency(1000, CurrencyDollars)
fmt.Printf("%s", val)
Output:

10.00

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the parent struct that contains the provider clients and list of providers to use

func (*Client) CoinPaprika

func (c *Client) CoinPaprika() CoinPaprikaInterface

CoinPaprika will return the client

func (*Client) GetConversion

func (c *Client) GetConversion(ctx context.Context, currency Currency, amount float64) (satoshis int64, providerUsed Provider, err error)

GetConversion will get the satoshi amount for the given currency + amount provided. The first provider that succeeds is the conversion that is returned

func (*Client) GetRate

func (c *Client) GetRate(ctx context.Context, currency Currency) (rate float64, providerUsed Provider, err error)

GetRate will get a BSV->Currency rate from the list of providers. The first provider that succeeds is the rate that is returned

func (*Client) Providers

func (c *Client) Providers() []Provider

Providers is the list of providers

func (*Client) SetCoinPaprika added in v0.2.0

func (c *Client) SetCoinPaprika(client CoinPaprikaInterface)

SetCoinPaprika will set the client

func (*Client) SetWhatsOnChain added in v0.2.0

func (c *Client) SetWhatsOnChain(client whatsonchain.ChainService)

SetWhatsOnChain will set the client

func (*Client) WhatsOnChain

func (c *Client) WhatsOnChain() whatsonchain.ChainService

WhatsOnChain will return the client

type ClientInterface added in v0.2.0

type ClientInterface interface {
	RateService
	CoinPaprika() CoinPaprikaInterface
	Providers() []Provider
	SetCoinPaprika(client CoinPaprikaInterface)
	SetWhatsOnChain(client whatsonchain.ChainService)
	WhatsOnChain() whatsonchain.ChainService
}

ClientInterface is the BSVRate client interface

func NewClient

func NewClient(clientOptions *ClientOptions, customHTTPClient HTTPInterface,
	providers ...Provider) ClientInterface

NewClient creates a new client for requests

type ClientOptions

type ClientOptions struct {
	BackOffExponentFactor          float64       `json:"back_off_exponent_factor"`
	BackOffInitialTimeout          time.Duration `json:"back_off_initial_timeout"`
	BackOffMaximumJitterInterval   time.Duration `json:"back_off_maximum_jitter_interval"`
	BackOffMaxTimeout              time.Duration `json:"back_off_max_timeout"`
	DialerKeepAlive                time.Duration `json:"dialer_keep_alive"`
	DialerTimeout                  time.Duration `json:"dialer_timeout"`
	RequestRetryCount              int           `json:"request_retry_count"`
	RequestTimeout                 time.Duration `json:"request_timeout"`
	TransportExpectContinueTimeout time.Duration `json:"transport_expect_continue_timeout"`
	TransportIdleTimeout           time.Duration `json:"transport_idle_timeout"`
	TransportMaxIdleConnections    int           `json:"transport_max_idle_connections"`
	TransportTLSHandshakeTimeout   time.Duration `json:"transport_tls_handshake_timeout"`
	UserAgent                      string        `json:"user_agent"`
}

ClientOptions holds all the configuration for connection, dialer and transport

func DefaultClientOptions

func DefaultClientOptions() (clientOptions *ClientOptions)

DefaultClientOptions will return a clientOptions struct with the default settings. Useful for starting with the default and then modifying as needed

func (*ClientOptions) ToWhatsOnChainOptions

func (c *ClientOptions) ToWhatsOnChainOptions() (options *whatsonchain.Options)

ToWhatsOnChainOptions will convert the current options to WOC Options

type CoinPaprikaInterface added in v0.2.0

type CoinPaprikaInterface interface {
	GetBaseAmountAndCurrencyID(currency string, amount float64) (string, float64)
	GetHistoricalTickers(ctx context.Context, coinID string, start, end time.Time, limit int, quote tickerQuote, interval tickerInterval) (response *HistoricalResponse, err error)
	GetMarketPrice(ctx context.Context, coinID string) (response *TickerResponse, err error)
	GetPriceConversion(ctx context.Context, baseCurrencyID, quoteCurrencyID string, amount float64) (response *PriceConversionResponse, err error)
	IsAcceptedCurrency(currency string) bool
}

CoinPaprikaInterface is an interface for the Coin Paprika Client

type Currency

type Currency uint8

Currency is a valid currency for rates or prices

func CurrencyFromName added in v0.0.4

func CurrencyFromName(name string) Currency

CurrencyFromName helper function to convert the name into it's Currency type

func (Currency) IsAccepted

func (c Currency) IsAccepted() bool

IsAccepted tests if the currency is accepted by all providers

func (Currency) IsValid

func (c Currency) IsValid() bool

IsValid tests if the provider is valid or not

func (Currency) Name

func (c Currency) Name() string

Name will return the display name for the given currency

type HTTPInterface added in v0.2.0

type HTTPInterface interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPInterface is used for the http client (mocking heimdall)

type HistoricalResponse added in v0.1.11

type HistoricalResponse struct {
	LastRequest *lastRequest      `json:"-"`
	Results     HistoricalResults `json:"-"`
}

HistoricalResponse is the response returned from the request

type HistoricalResults added in v0.1.11

type HistoricalResults []*HistoricalTicker

HistoricalResults is the results returned by the historical ticker request

type HistoricalTicker added in v0.1.11

type HistoricalTicker struct {
	MarketCap int64   `json:"market_cap"`
	Price     float64 `json:"price"`
	Timestamp string  `json:"timestamp"`
	Volume24h int64   `json:"volume_24h"`
}

HistoricalTicker is the ticker struct for historical request

type PaprikaClient

type PaprikaClient struct {
	HTTPClient HTTPInterface // carries out the http operations (heimdall client)
	UserAgent  string
}

PaprikaClient is the client for Coin Paprika

func (*PaprikaClient) GetBaseAmountAndCurrencyID

func (p *PaprikaClient) GetBaseAmountAndCurrencyID(currency string, amount float64) (string, float64)

GetBaseAmountAndCurrencyID will return an ID and default amount

func (*PaprikaClient) GetHistoricalTickers added in v0.1.11

func (p *PaprikaClient) GetHistoricalTickers(ctx context.Context, coinID string, start, end time.Time, limit int,
	quote tickerQuote, interval tickerInterval) (response *HistoricalResponse, err error)

GetHistoricalTickers will return the historical tickers given the range of time

See: https://api.coinpaprika.com/#tag/Tickers/paths/~1tickers~1{coin_id}~1historical/get

func (*PaprikaClient) GetMarketPrice

func (p *PaprikaClient) GetMarketPrice(ctx context.Context, coinID string) (response *TickerResponse, err error)

GetMarketPrice returns a response of the market price from Coin Paprika

See: https://api.coinpaprika.com/#operation/getTickersById

func (*PaprikaClient) GetPriceConversion

func (p *PaprikaClient) GetPriceConversion(ctx context.Context, baseCurrencyID, quoteCurrencyID string,
	amount float64) (response *PriceConversionResponse, err error)

GetPriceConversion returns a response of the conversion price from Coin Paprika

See: https://api.coinpaprika.com/#tag/Tools/paths/~1price-converter/get

func (*PaprikaClient) IsAcceptedCurrency

func (p *PaprikaClient) IsAcceptedCurrency(currency string) bool

IsAcceptedCurrency checks if the currency is accepted or not

type PriceConversionResponse

type PriceConversionResponse struct {
	Amount                float64      `json:"amount"`
	BaseCurrencyID        string       `json:"base_currency_id"`
	BaseCurrencyName      string       `json:"base_currency_name"`
	BasePriceLastUpdated  string       `json:"base_price_last_updated"`
	LastRequest           *lastRequest `json:"-"` // is the raw information from the last request
	Price                 float64      `json:"price"`
	QuoteCurrencyID       string       `json:"quote_currency_id"`
	QuoteCurrencyName     string       `json:"quote_currency_name"`
	QuotePriceLastUpdated string       `json:"quote_price_last_updated"`
}

PriceConversionResponse is the result returned from Coin Paprika conversion request

func (PriceConversionResponse) GetSatoshi

func (p PriceConversionResponse) GetSatoshi() (satoshi int64, err error)

GetSatoshi will convert the price into Satoshi's (integer value)

type Provider

type Provider uint8

Provider is a provider for rates or prices

const (
	ProviderWhatsOnChain Provider // 1
	ProviderCoinPaprika           // 2

)

Provider constants for the different available rate providers. Leave the start and last constants in place

func (Provider) IsValid

func (p Provider) IsValid() bool

IsValid tests if the provider is valid or not

func (Provider) Name

func (p Provider) Name() string

Name will return the display name for the given provider

type RateService added in v0.2.1

type RateService interface {
	GetConversion(ctx context.Context, currency Currency, amount float64) (satoshis int64, providerUsed Provider, err error)
	GetRate(ctx context.Context, currency Currency) (rate float64, providerUsed Provider, err error)
}

RateService is the rate methods

type TickerResponse

type TickerResponse struct {
	BetaValue         float64      `json:"beta_value"`
	CirculatingSupply int64        `json:"circulating_supply"`
	ID                string       `json:"id"`
	LastRequest       *lastRequest `json:"-"` // is the raw information from the last request
	LastUpdated       string       `json:"last_updated"`
	MaxSupply         int64        `json:"max_supply"`
	Name              string       `json:"name"`
	Quotes            *currency    `json:"quotes"`
	Rank              int          `json:"rank"`
	Symbol            string       `json:"symbol"`
	TotalSupply       int64        `json:"total_supply"`
}

TickerResponse is the result returned from Coin Paprika ticker request

Directories

Path Synopsis
examples
custom_options
Package main is an example of using the go-bsvrates package using custom options
Package main is an example of using the go-bsvrates package using custom options
custom_providers
Package main is an example of using the go-bsvrates package using custom providers
Package main is an example of using the go-bsvrates package using custom providers
get_historical_tickers
Package main is an example of using the go-bsvrates package
Package main is an example of using the go-bsvrates package
get_rates
Package main is an example of using the go-bsvrates package
Package main is an example of using the go-bsvrates package
price_conversion
Package main is an example of using the go-bsvrates package for price conversions
Package main is an example of using the go-bsvrates package for price conversions

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL