exchanges

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2019 License: ISC Imports: 14 Imported by: 3

Documentation

Index

Constants

View Source
const (
	// DefaultCurrency is overridden by ExchangeBotConfig.BtcIndex. Data
	// structures are cached for DefaultCurrency, so requests are a little bit
	// faster.
	DefaultCurrency = "USD"
	// DefaultDataExpiry is the amount of time between calls to the exchange API.
	DefaultDataExpiry = "20m"
	// DefaultRequestExpiry : Any data older than RequestExpiry will be discarded.
	DefaultRequestExpiry = "60m"
)
View Source
const (
	Coinbase    = "coinbase"
	CoinbaseURL = "https://api.coinbase.com/v2/exchange-rates?currency=BTC"
	Coindesk    = "coindesk"
	CoindeskURL = "https://api.coindesk.com/v1/bpi/currentprice.json"
	Binance     = "binance"
	BinanceURL  = "https://api.binance.com/api/v1/ticker/24hr?symbol=DCRBTC"
	Bittrex     = "bittrex"
	BittrexURL  = "https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-dcr"
	DragonEx    = "dragonex"
	DragonExURL = "https://openapi.dragonex.io/api/v1/market/real/?symbol_id=1520101"
	Huobi       = "huobi"
	HuobiURL    = "https://api.huobi.pro/market/detail/merged?symbol=dcrbtc"
	Poloniex    = "poloniex"
	PoloniexURL = "https://poloniex.com/public?command=returnTicker"
)

Tokens. Used to identify the exchange.

Variables

BtcIndices maps tokens to constructors for BTC-fiat exchanges.

DcrExchanges maps tokens to constructors for DCR-BTC exchanges.

Functions

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func IsBtcIndex

func IsBtcIndex(token string) bool

IsBtcIndex checks whether the given token is a known Bitcoin index, as opposed to a Decred-to-Bitcoin Exchange.

func IsDcrExchange

func IsDcrExchange(token string) bool

IsDcrExchange checks whether the given token is a known Decred-BTC exchange.

func Tokens

func Tokens() []string

Tokens is a new slice of available exchange tokens.

func UseLogger

func UseLogger(logger slog.Logger)

UseLogger uses a specified Logger to output package logging info.

Types

type BinanceExchange

type BinanceExchange struct {
	*CommonExchange
}

BinanceExchange is a high-volume and well-respected crypto exchange.

func (*BinanceExchange) Refresh

func (binance *BinanceExchange) Refresh()

Refresh retrieves and parses API data from Binance.

type BinanceResponse

type BinanceResponse struct {
	Symbol             string `json:"symbol"`
	PriceChange        string `json:"priceChange"`
	PriceChangePercent string `json:"priceChangePercent"`
	WeightedAvgPrice   string `json:"weightedAvgPrice"`
	PrevClosePrice     string `json:"prevClosePrice"`
	LastPrice          string `json:"lastPrice"`
	LastQty            string `json:"lastQty"`
	BidPrice           string `json:"bidPrice"`
	BidQty             string `json:"bidQty"`
	AskPrice           string `json:"askPrice"`
	AskQty             string `json:"askQty"`
	OpenPrice          string `json:"openPrice"`
	HighPrice          string `json:"highPrice"`
	LowPrice           string `json:"lowPrice"`
	Volume             string `json:"volume"`
	QuoteVolume        string `json:"quoteVolume"`
	OpenTime           int64  `json:"openTime"`
	CloseTime          int64  `json:"closeTime"`
	FirstID            int64  `json:"firstId"`
	LastID             int64  `json:"lastId"`
	Count              int64  `json:"count"`
}

BinanceResponse models the JSON data returned from the Binance API.

type BittrexExchange

type BittrexExchange struct {
	*CommonExchange
	MarketName string
}

BittrexExchange is an unregulated U.S. crypto exchange with good volume.

func (*BittrexExchange) Refresh

func (bittrex *BittrexExchange) Refresh()

Refresh retrieves and parses API data from Bittrex. Bittrex provides timestamps in a string format that is not quite RFC 3339.

type BittrexResponse

type BittrexResponse struct {
	Success bool                    `json:"success"`
	Message string                  `json:"message"`
	Result  []BittrexResponseResult `json:"result"`
}

BittrexResponse models the JSON data returned from the Bittrex API.

type BittrexResponseResult

type BittrexResponseResult struct {
	MarketName     string  `json:"MarketName"`
	High           float64 `json:"High"`
	Low            float64 `json:"Low"`
	Volume         float64 `json:"Volume"`
	Last           float64 `json:"Last"`
	BaseVolume     float64 `json:"BaseVolume"`
	TimeStamp      string  `json:"TimeStamp"`
	Bid            float64 `json:"Bid"`
	Ask            float64 `json:"Ask"`
	OpenBuyOrders  int     `json:"OpenBuyOrders"`
	OpenSellOrders int     `json:"OpenSellOrders"`
	PrevDay        float64 `json:"PrevDay"`
	Created        string  `json:"Created"`
}

BittrexResponseResult models the "result" field of the Bittrex API response.

type BotChannels

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

BotChannels is passed to exchanges for communication with the Start loop.

type CoinbaseExchange

type CoinbaseExchange struct {
	*CommonExchange
}

CoinbaseExchange provides tons of bitcoin-fiat exchange pairs.

func (*CoinbaseExchange) Refresh

func (coinbase *CoinbaseExchange) Refresh()

Refresh retrieves and parses API data from Coinbase.

type CoinbaseResponse

type CoinbaseResponse struct {
	Data CoinbaseResponseData `json:"data"`
}

CoinbaseResponse models the JSON data returned from the Coinbase API.

type CoinbaseResponseData

type CoinbaseResponseData struct {
	Currency string            `json:"currency"`
	Rates    map[string]string `json:"rates"`
}

CoinbaseResponseData models the "data" field of the Coinbase API response.

type CoindeskExchange

type CoindeskExchange struct {
	*CommonExchange
}

CoindeskExchange provides Bitcoin indices for USD, GBP, and EUR by default. Others are available, but custom requests would need to be implemented.

func (*CoindeskExchange) Refresh

func (coindesk *CoindeskExchange) Refresh()

Refresh retrieves and parses API data from Coindesk.

type CoindeskResponse

type CoindeskResponse struct {
	Time       CoindeskResponseTime           `json:"time"`
	Disclaimer string                         `json:"disclaimer"`
	ChartName  string                         `json:"chartName"`
	Bpi        map[string]CoindeskResponseBpi `json:"bpi"`
}

CoindeskResponse models the JSON data returned from the Coindesk API.

type CoindeskResponseBpi

type CoindeskResponseBpi struct {
	Code        string  `json:"code"`
	Symbol      string  `json:"symbol"`
	Rate        string  `json:"rate"`
	Description string  `json:"description"`
	RateFloat   float64 `json:"rate_float"`
}

CoindeskResponseBpi models the "bpi" field of the Coindesk API response.

type CoindeskResponseTime

type CoindeskResponseTime struct {
	Updated    string    `json:"updated"`
	UpdatedIso time.Time `json:"updatedISO"`
	Updateduk  string    `json:"updateduk"`
}

CoindeskResponseTime models the "time" field of the Coindesk API response.

type CommonExchange

type CommonExchange struct {
	URL string
	// contains filtered or unexported fields
}

CommonExchange is embedded in all of the exchange types and handles some state tracking and token handling for ExchangeBot communications. The http.Request must be created individually for each exchange.

func (*CommonExchange) Hurry

func (xc *CommonExchange) Hurry(d time.Duration)

Hurry can be used to subtract some amount of time from the lastUpate and lastFail, and can be used to de-sync the exchange updates.

func (*CommonExchange) IsFailed

func (xc *CommonExchange) IsFailed() bool

IsFailed will be true if xc.lastFail > xc.lastUpdate.

func (*CommonExchange) LastFail

func (xc *CommonExchange) LastFail() time.Time

LastFail gets the last time.Time of a failed exchange update.

func (*CommonExchange) LastTry

func (xc *CommonExchange) LastTry() time.Time

LastTry is the more recent of lastFail and LastUpdate.

func (*CommonExchange) LastUpdate

func (xc *CommonExchange) LastUpdate() time.Time

LastUpdate gets a time.Time of the last successful exchange update.

func (*CommonExchange) LogRequest

func (xc *CommonExchange) LogRequest()

LogRequest sets the lastRequest time.Time.

func (*CommonExchange) Token

func (xc *CommonExchange) Token() string

Token is the string associated with the exchange's token.

func (*CommonExchange) Update

func (xc *CommonExchange) Update(state *ExchangeState)

Update sends an updated ExchangeState to the ExchangeBot.

func (*CommonExchange) UpdateIndices

func (xc *CommonExchange) UpdateIndices(indices FiatIndices)

UpdateIndices sends a bitcoin index update to the ExchangeBot.

type Conversion

type Conversion struct {
	Value float64 `json:"value"`
	Index string  `json:"index"`
}

Conversion is a representation of some amount of DCR in another index.

func (*Conversion) TwoDecimals

func (c *Conversion) TwoDecimals() string

TwoDecimals is a string representation of the value with two digits after the decimal point, but will show more to achieve at least three significant digits.

type DragonExResponse

type DragonExResponse struct {
	Ok   bool                   `json:"ok"`
	Code int                    `json:"code"`
	Data []DragonExResponseData `json:"data"`
	Msg  string                 `json:"msg"`
}

DragonExResponse models the JSON data returned from the DragonEx API.

type DragonExResponseData

type DragonExResponseData struct {
	ClosePrice      string `json:"close_price"`
	CurrentVolume   string `json:"current_volume"`
	MaxPrice        string `json:"max_price"`
	MinPrice        string `json:"min_price"`
	OpenPrice       string `json:"open_price"`
	PriceBase       string `json:"price_base"`
	PriceChange     string `json:"price_change"`
	PriceChangeRate string `json:"price_change_rate"`
	Timestamp       int64  `json:"timestamp"`
	TotalAmount     string `json:"total_amount"`
	TotalVolume     string `json:"total_volume"`
	UsdtVolume      string `json:"usdt_amount"`
	SymbolID        int    `json:"symbol_id"`
}

DragonExResponseData models the JSON data from the DragonEx API. Dragonex has the current price in close_price

type DragonExchange

type DragonExchange struct {
	*CommonExchange
	SymbolID int
}

DragonExchange is a Singapore-based crytocurrency exchange.

func (*DragonExchange) Refresh

func (dragonex *DragonExchange) Refresh()

Refresh retrieves and parses API data from DragonEx.

type Exchange

type Exchange interface {
	LastUpdate() time.Time
	LastFail() time.Time
	LastTry() time.Time
	Refresh()
	IsFailed() bool
	Token() string
	Hurry(time.Duration)
	Update(*ExchangeState)
	UpdateIndices(FiatIndices)
}

Exchange is the interface that ExchangeBot understands. Most of the methods are implemented by CommonExchange, but Refresh is implemented in the individual exchange types.

func NewBinance

func NewBinance(client *http.Client, channels *BotChannels) (binance Exchange, err error)

NewBinance constructs a BinanceExchange.

func NewBittrex

func NewBittrex(client *http.Client, channels *BotChannels) (bittrex Exchange, err error)

NewBittrex constructs a BittrexExchange.

func NewCoinbase

func NewCoinbase(client *http.Client, channels *BotChannels) (coinbase Exchange, err error)

NewCoinbase constructs a CoinbaseExchange.

func NewCoindesk

func NewCoindesk(client *http.Client, channels *BotChannels) (coindesk Exchange, err error)

NewCoindesk constructs a CoindeskExchange.

func NewDragonEx

func NewDragonEx(client *http.Client, channels *BotChannels) (dragonex Exchange, err error)

NewDragonEx constructs a DragonExchange.

func NewHuobi

func NewHuobi(client *http.Client, channels *BotChannels) (huobi Exchange, err error)

NewHuobi constructs a HuobiExchange.

func NewPoloniex

func NewPoloniex(client *http.Client, channels *BotChannels) (poloniex Exchange, err error)

NewPoloniex constructs a PoloniexExchange.

type ExchangeBot

type ExchangeBot struct {
	DcrBtcExchanges map[string]Exchange
	IndexExchanges  map[string]Exchange
	Exchanges       map[string]Exchange
	// BtcIndex is the (typically fiat) currency to which the DCR price should be
	// converted by default. Other conversions are available via a lookup in
	// indexMap, but with slightly lower performance.
	// 3-letter currency code, e.g. USD.
	BtcIndex string

	DataExpiry    time.Duration
	RequestExpiry time.Duration

	TLSCredentials credentials.TransportCredentials
	// contains filtered or unexported fields
}

ExchangeBot monitors exchanges and processes updates. When an update is received from an exchange, the state is updated, and some convenient data structures are prepared. Make ExchangeBot with NewExchangeBot.

func NewExchangeBot

func NewExchangeBot(config *ExchangeBotConfig) (*ExchangeBot, error)

NewExchangeBot constructs a new ExchangeBot with the provided configuration.

func (*ExchangeBot) AvailableIndices

func (bot *ExchangeBot) AvailableIndices() []string

AvailableIndices creates a fresh slice of all available index currency codes.

func (*ExchangeBot) Conversion

func (bot *ExchangeBot) Conversion(dcrVal float64) *Conversion

Conversion attempts to multiply the supplied float with the default index. Nil pointer will be returned if there is no valid exchangeState.

func (*ExchangeBot) ConvertedState

func (bot *ExchangeBot) ConvertedState(code string) (*ExchangeBotState, error)

ConvertedState returns an ExchangeBotState with a base of the provided currency code, if available.

func (*ExchangeBot) ConvertedStateBytes

func (bot *ExchangeBot) ConvertedStateBytes(symbol string) ([]byte, error)

ConvertedStateBytes gives a JSON-encoded byte array of the currentState with a base of the provided currency code, if available.

func (*ExchangeBot) Cycle

func (bot *ExchangeBot) Cycle()

Cycle refreshes all expired exchanges.

func (*ExchangeBot) Indices

func (bot *ExchangeBot) Indices(token string) FiatIndices

Indices is the fiat indices for a given BTC index exchange.

func (*ExchangeBot) IsFailed

func (bot *ExchangeBot) IsFailed() bool

IsFailed is whether the failed flag was set during the last IndexUpdate or ExchangeUpdate. The failed flag is set when either no Bitcoin Index sources or no Decred Exchanges are up-to-date. Individual exchanges can be outdated/failed without IsFailed being false, as long as there is at least one Bitcoin index and one Decred exchange.

func (*ExchangeBot) Price

func (bot *ExchangeBot) Price() float64

Price gets the lastest Price in the default currency (BtcIndex).

func (*ExchangeBot) Start

func (bot *ExchangeBot) Start(ctx context.Context, wg *sync.WaitGroup)

Start is the main ExchangeBot loop, reading from the exchange update channel and scheduling refresh cycles.

func (*ExchangeBot) State

func (bot *ExchangeBot) State() *ExchangeBotState

State is a copy of the current ExchangeBotState. A JSON-encoded byte array of the current state can be accessed through StateBytes().

func (*ExchangeBot) StateBytes

func (bot *ExchangeBot) StateBytes() []byte

StateBytes is a JSON-encoded byte array of the currentState.

func (*ExchangeBot) UpdateChannels

func (bot *ExchangeBot) UpdateChannels() *UpdateChannels

UpdateChannels creates an UpdateChannels, which holds a channel to receive exchange updates and a channel which is closed when the start loop exits.

type ExchangeBotConfig

type ExchangeBotConfig struct {
	Disabled       []string
	DataExpiry     string
	RequestExpiry  string
	BtcIndex       string
	Indent         bool
	MasterBot      string
	MasterCertFile string
}

ExchangeBotConfig is the configuration options for ExchangeBot. DataExpiry must be less than RequestExpiry. Recommend RequestExpiry > 2*DataExpiry, which will permit the exchange API request to fail a couple of times before the exchange's data is discarded.

type ExchangeBotState

type ExchangeBotState struct {
	BtcIndex    string                    `json:"btc_index"`
	Price       float64                   `json:"price"`
	Volume      float64                   `json:"volume"`
	DcrBtc      map[string]*ExchangeState `json:"dcr_btc_exchanges"`
	FiatIndices map[string]*ExchangeState `json:"btc_indices"`
}

ExchangeBotState is the current known state of all exchanges, in a certain base currency, and a volume-averaged price and total volume in DCR.

type ExchangeState

type ExchangeState struct {
	Price      float64 `json:"price"`
	BaseVolume float64 `json:"base_volume,omitempty"`
	Volume     float64 `json:"volume,omitempty"`
	Change     float64 `json:"change,omitempty"`
	Stamp      int64   `json:"timestamp,omitempty"`
}

ExchangeState is the simple template for a price. The only member that is guaranteed is a price. For Decred exchanges, the volumes will also be populated.

type ExchangeUpdate

type ExchangeUpdate struct {
	Token string
	State *ExchangeState
}

ExchangeUpdate packages the ExchangeState for the update channel.

type FiatIndices

type FiatIndices map[string]float64

FiatIndices maps currency codes to Bitcoin exchange rates.

type HuobiExchange

type HuobiExchange struct {
	*CommonExchange
	Ok string
}

HuobiExchange is based in Hong Kong and Singapore.

func (*HuobiExchange) Refresh

func (huobi *HuobiExchange) Refresh()

Refresh retrieves and parses API data from Huobi.

type HuobiResponse

type HuobiResponse struct {
	Status string            `json:"status"`
	Ch     string            `json:"ch"`
	Ts     int64             `json:"ts"`
	Tick   HuobiResponseTick `json:"tick"`
}

HuobiResponse models the JSON data returned from the Huobi API.

type HuobiResponseTick

type HuobiResponseTick struct {
	Amount  float64   `json:"amount"`
	Open    float64   `json:"open"`
	Close   float64   `json:"close"`
	High    float64   `json:"high"`
	ID      int64     `json:"id"`
	Count   int64     `json:"count"`
	Low     float64   `json:"low"`
	Version int64     `json:"version"`
	Ask     []float64 `json:"ask"`
	Vol     float64   `json:"vol"`
	Bid     []float64 `json:"bid"`
}

HuobiResponseTick models the "tick" field of the Huobi API response.

type IndexUpdate

type IndexUpdate struct {
	Token   string
	Indices FiatIndices
}

IndexUpdate is sent from the Exchange to the ExchangeBot indexChan when new data is received.

type PoloniexExchange

type PoloniexExchange struct {
	*CommonExchange
	CurrencyPair string
}

PoloniexExchange is a U.S.-based exchange.

func (*PoloniexExchange) Refresh

func (poloniex *PoloniexExchange) Refresh()

Refresh retrieves and parses API data from Poloniex.

type PoloniexPair

type PoloniexPair struct {
	ID            int    `json:"id"`
	Last          string `json:"last"`
	LowestAsk     string `json:"lowestAsk"`
	HighestBid    string `json:"highestBid"`
	PercentChange string `json:"percentChange"`
	BaseVolume    string `json:"baseVolume"`
	QuoteVolume   string `json:"quoteVolume"`
	IsFrozen      string `json:"isFrozen"`
	High24hr      string `json:"high24hr"`
	Low24hr       string `json:"low24hr"`
}

PoloniexPair models the data returned from the Poloniex API.

type UpdateChannels

type UpdateChannels struct {
	Update chan *UpdateSignal
	Quit   chan struct{}
}

UpdateChannels are requested by the user with ExchangeBot.UpdateChannels.

type UpdateSignal

type UpdateSignal struct {
	Token string
	State *ExchangeBotState
	Bytes []byte
}

UpdateSignal is the update sent over the update channels, and includes an ExchangeBotState and a JSON-encoded byte array of the state. Token is the exchange which triggered the update.

func (UpdateSignal) TriggerState

func (signal UpdateSignal) TriggerState() (xcState *ExchangeState, err error)

TriggerState is the ExchangeState for the exchange that triggered the update.

Directories

Path Synopsis
rateserver module

Jump to

Keyboard shortcuts

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