exchanges

package module
v0.0.0-...-775ef2c Latest Latest
Warning

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

Go to latest
Published: May 19, 2019 License: ISC Imports: 18 Imported by: 2

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 = "5m"
	// DefaultRequestExpiry : Any data older than RequestExpiry will be discarded.
	DefaultRequestExpiry = "60m"
)
View Source
const (
	Coinbase = "coinbase"
	Coindesk = "coindesk"
	Binance  = "binance"
	Bittrex  = "bittrex"
	DragonEx = "dragonex"
	Huobi    = "huobi"
	Poloniex = "poloniex"
)

Tokens. Used to identify the exchange.

View Source
const (
	BittrexOrderAdd = iota
	BittrexOrderRemove
	BittrexOrderUpdate
)

A few websocket (SignalR) constants.

Variables

View Source
var (
	CoinbaseURLs = URLs{
		Price: "https://api.coinbase.com/v2/exchange-rates?currency=BTC",
	}
	CoindeskURLs = URLs{
		Price: "https://api.coindesk.com/v1/bpi/currentprice.json",
	}
	BinanceURLs = URLs{
		Price: "https://api.binance.com/api/v1/ticker/24hr?symbol=FNOBTC",

		Depth: "https://api.binance.com/api/v1/depth?symbol=FNOBTC&limit=1000",
		Candlesticks: map[candlestickKey]string{
			// contains filtered or unexported fields
		},
	}
	BittrexURLs = URLs{
		Price: "https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-fno",

		Depth: "https://bittrex.com/api/v1.1/public/getorderbook?market=btc-fno&type=both",

		Candlesticks: map[candlestickKey]string{
			// contains filtered or unexported fields
		},

		Websocket: "socket.bittrex.com",
	}
	DragonExURLs = URLs{
		Price: "https://openapi.dragonex.io/api/v1/market/real/?symbol_id=1520101",

		Depth: "https://openapi.dragonex.io/api/v1/market/%s/?symbol_id=1520101",
		Candlesticks: map[candlestickKey]string{
			// contains filtered or unexported fields
		},
	}
	HuobiURLs = URLs{
		Price: "https://api.huobi.pro/market/detail/merged?symbol=fnobtc",

		Depth: "https://api.huobi.pro/market/depth?symbol=fnobtc&type=step0",
		Candlesticks: map[candlestickKey]string{
			// contains filtered or unexported fields
		},
	}
	PoloniexURLs = URLs{
		Price: "https://poloniex.com/public?command=returnTicker",

		Depth: "https://poloniex.com/public?command=returnOrderBook&currencyPair=BTC_FNO&depth=100",
		Candlesticks: map[candlestickKey]string{
			// contains filtered or unexported fields
		},
		Websocket: "wss://api2.poloniex.com",
	}
)

Prepare the URLs.

BtcIndices maps tokens to constructors for BTC-fiat exchanges.

FnoExchanges maps tokens to constructors for FNO-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 Fonero-to-Bitcoin Exchange.

func IsFnoExchange

func IsFnoExchange(token string) bool

IsFnoExchange checks whether the given token is a known Fonero-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 BinanceCandlestickResponse

type BinanceCandlestickResponse [][]interface{}

BinanceCandlestickResponse models candlestick data returned from the Binance API. Binance has a response with mixed-type arrays, so type-checking is appropriate. Sample response is [

[
  1499040000000,      // Open time
  "0.01634790",       // Open
  "0.80000000",       // High
  "0.01575800",       // Low
  "0.01577100",       // Close
  "148976.11427815",  // Volume
  ...
]

]

type BinanceDepthResponse

type BinanceDepthResponse struct {
	UpdateID int64
	Bids     [][2]string
	Asks     [][2]string
}

BinanceDepthResponse models the response for Binance depth chart data.

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 BinancePriceResponse

type BinancePriceResponse 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"`
}

BinancePriceResponse models the JSON price data returned from the Binance API.

type BittrexCandlestick

type BittrexCandlestick struct {
	Open       float64 `json:"O"`
	High       float64 `json:"H"`
	Low        float64 `json:"L"`
	Close      float64 `json:"C"`
	Volume     float64 `json:"V"`
	Time       string  `json:"T"`
	BaseVolume float64 `json:"BV"`
}

BittrexCandlestick models a single candlestick in the Bittrex API response.

type BittrexCandlestickResponse

type BittrexCandlestickResponse struct {
	Success     bool                `json:"success"`
	Message     string              `json:"message"`
	Result      BittrexCandlesticks `json:"result"`
	Explanation *string             `json:"explanation"`
}

BittrexCandlestickResponse models the response from the Bittrex kline data endpoint.

type BittrexCandlesticks

type BittrexCandlesticks []BittrexCandlestick

BittrexCandlesticks is a slice of BittrexCandlestick

type BittrexDepthArray

type BittrexDepthArray []BittrexDepthPoint

BittrexDepthArray is a slice of BittrexDepthPoint

type BittrexDepthPoint

type BittrexDepthPoint struct {
	Quantity float64 `json:"Quantity"`
	Rate     float64 `json:"Rate"`
}

BittrexDepthPoint models a single point of the bittrex order book.

type BittrexDepthResponse

type BittrexDepthResponse struct {
	Success bool               `json:"success"`
	Message string             `json:"message"`
	Result  BittrexDepthResult `json:"result"`
}

BittrexDepthResponse models the Bittrex order book response.

type BittrexDepthResult

type BittrexDepthResult struct {
	Buy  BittrexDepthArray `json:"buy"`
	Sell BittrexDepthArray `json:"sell"`
}

BittrexDepthResult models the result field of BittrexDepthResponse

type BittrexExchange

type BittrexExchange struct {
	*CommonExchange
	MarketName string
	// contains filtered or unexported fields
}

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 BittrexOrderbookUpdate

type BittrexOrderbookUpdate struct {
	Nonce      int64             `json:"Nonce"`
	MarketName string            `json:"MarketName"`
	Buys       []*BittrexWsOrder `json:"Buys"`
	Sells      []*BittrexWsOrder `json:"Sells"`
	Fills      []*BittrexWsFill  `json:"Fills"`
}

BittrexOrderbookUpdate models the websocket update from the Bittrex websocket.

type BittrexPriceResponse

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

BittrexPriceResponse 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 BittrexWsFill

type BittrexWsFill struct {
	OrderType string  `json:"OrderType"`
	Rate      float64 `json:"Rate"`
	Quantity  float64 `json:"Quantity"`
	TimeStamp string  `json:"TimeStamp"`
}

BittrexWsFill models an off-book trade notification from the Bittrex websocket.

type BittrexWsOrder

type BittrexWsOrder struct {
	Quantity float64 `json:"Quantity"`
	Rate     float64 `json:"Rate"`
	Type     int8    `json:"Type"` // 0 = ADD, 1 = REMOVE, 2 = UPDATE
}

BittrexWsOrder models an order book update from the Bittrex websocket.

type BotChannels

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

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

type Candlestick

type Candlestick struct {
	High   float64   `json:"high"`
	Low    float64   `json:"low"`
	Open   float64   `json:"open"`
	Close  float64   `json:"close"`
	Volume float64   `json:"volume"`
	Start  time.Time `json:"start"`
}

Candlestick is the record of price change over some bin width of time.

type Candlesticks

type Candlesticks []Candlestick

Candlesticks is a slice of CandleStick.

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) SilentUpdate

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

SilentUpdate stores the update for internal use, but does not signal an update to the ExchangeBot.

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 FNO 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 DepthData

type DepthData struct {
	Time int64        `json:"time"`
	Bids []DepthPoint `json:"bids"`
	Asks []DepthPoint `json:"asks"`
}

DepthData is an exchanges order book for use in a depth chart.

func (*DepthData) IsFresh

func (depth *DepthData) IsFresh() bool

IsFresh will be true if the data is older than depthDataExpiration.

type DepthPoint

type DepthPoint struct {
	Quantity float64 `json:"quantity"`
	Price    float64 `json:"price"`
}

DepthPoint is a single point in a set of depth chart data.

type DragonExCandlestickColumns

type DragonExCandlestickColumns []string

DragonExCandlestickColumns models the column list returned in a candlestick chart data response from Dragon Exchange.

type DragonExCandlestickData

type DragonExCandlestickData struct {
	Columns DragonExCandlestickColumns `json:"columns"`
	Lists   DragonExCandlestickPts     `json:"lists"`
}

DragonExCandlestickData models the Data field of DragonExCandlestickResponse.

type DragonExCandlestickList

type DragonExCandlestickList []interface{}

DragonExCandlestickList models the value list returned in a candlestick chart data response from Dragon Exchange.

type DragonExCandlestickPts

type DragonExCandlestickPts []DragonExCandlestickList

DragonExCandlestickLists is a list of DragonExCandlestickList

type DragonExCandlestickResponse

type DragonExCandlestickResponse struct {
	DragonExResponse
	Data DragonExCandlestickData
}

DragonExCandlestickResponse models the response from DragonEx for the historical k-line data.

type DragonExDepthArray

type DragonExDepthArray []DragonExDepthPt

DragonExDepthArray is a slice of DragonExDepthPt.

type DragonExDepthPt

type DragonExDepthPt struct {
	Price  string `json:"price"`
	Volume string `json:"volume"`
}

DragonExDepthPt models a single point of data in a Dragon Exchange depth chart data set.

type DragonExDepthResponse

type DragonExDepthResponse struct {
	DragonExResponse
	Data DragonExDepthArray `json:"data"`
}

DragonExDepthResponse models the Dragon Exchange depth chart data response.

type DragonExPriceResponse

type DragonExPriceResponse struct {
	DragonExResponse
	Data []DragonExPriceResponseData `json:"data"`
}

DragonExPriceResponse models the JSON data returned from the DragonEx API.

type DragonExPriceResponseData

type DragonExPriceResponseData 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"`
}

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

type DragonExResponse

type DragonExResponse struct {
	Ok   bool   `json:"ok"`
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

DragonExResponse models the generic fields returned in every response.

type DragonExchange

type DragonExchange struct {
	*CommonExchange
	SymbolID int
	// contains filtered or unexported fields
}

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)
	SilentUpdate(*ExchangeState) // skip passing update to the update channel
	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 {
	FnoBtcExchanges map[string]Exchange
	IndexExchanges  map[string]Exchange
	Exchanges       map[string]Exchange

	// BtcIndex is the (typically fiat) currency to which the FNO 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(fnoVal 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 Fonero 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 Fonero exchange.

func (*ExchangeBot) Price

func (bot *ExchangeBot) Price() float64

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

func (*ExchangeBot) QuickDepth

func (bot *ExchangeBot) QuickDepth(token string) (chart []byte, err error)

QuickDepth returns the up-to-date depth chart data for the specified exchange, pulling from the cache if appropriate.

func (*ExchangeBot) QuickSticks

func (bot *ExchangeBot) QuickSticks(token string, rawBin string) ([]byte, error)

QuickSticks returns the up-to-date candlestick data for the specified exchange and bin width, pulling from the cache if appropriate.

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"`
	BtcPrice    float64                   `json:"btc_fiat_price"`
	Price       float64                   `json:"price"`
	Volume      float64                   `json:"volume"`
	FnoBtc      map[string]*ExchangeState `json:"fno_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 FNO.

func (*ExchangeBotState) BtcToFiat

func (state *ExchangeBotState) BtcToFiat(btc float64) float64

BtcToFiat converts an amount of Bitcoin to fiat using the current calculated exchange rate.

func (*ExchangeBotState) FiatToBtc

func (state *ExchangeBotState) FiatToBtc(fiat float64) float64

FiatToBtc converts an amount of fiat in the default index to a value in BTC.

func (*ExchangeBotState) VolumeOrderedExchanges

func (state *ExchangeBotState) VolumeOrderedExchanges() []*tokenedExchange

VolumeOrderedExchanges returns a list of tokenedExchange sorted by volume, highest volume first.

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"`
	Depth        *DepthData                      `json:"depth,omitempty"`
	Candlesticks map[candlestickKey]Candlesticks `json:"candlesticks,omitempty"`
}

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

func (*ExchangeState) HasCandlesticks

func (state *ExchangeState) HasCandlesticks() bool

HasCandlesticks checks for data in the candlesticks map.

func (*ExchangeState) HasDepth

func (state *ExchangeState) HasDepth() bool

HasDepth is true if the there is data in the depth field.

func (*ExchangeState) StickList

func (state *ExchangeState) StickList() string

StickList is a semicolon-delimited list of available binSize.

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 HuobiCandlestickData

type HuobiCandlestickData []*HuobiCandlestickPt

HuobiCandlestickData is a list of candlestick data pts.

type HuobiCandlestickPt

type HuobiCandlestickPt struct {
	ID     int64   `json:"id"` // ID is actually start time as unix stamp
	Open   float64 `json:"open"`
	Close  float64 `json:"close"`
	Low    float64 `json:"low"`
	High   float64 `json:"high"`
	Amount float64 `json:"amount"` // Volume BTC
	Vol    float64 `json:"vol"`    // Volume FNO
	Count  int64   `json:"count"`
}

HuobiCandlestickPt is a single candlestick pt in a Huobi API candelstick response.

type HuobiCandlestickResponse

type HuobiCandlestickResponse struct {
	HuobiResponse
	Data HuobiCandlestickData `json:"data"`
}

HuobiCandlestickResponse models the response from Huobi for candlestick data.

type HuobiDepthPts

type HuobiDepthPts [][2]float64

HuobiDepthPts is a list of tuples [price, volume].

type HuobiDepthResponse

type HuobiDepthResponse struct {
	HuobiResponse
	Tick HuobiDepthTick `json:"tick"`
}

HuobiDepthResponse models the response from a Huobi API depth chart response.

type HuobiDepthTick

type HuobiDepthTick struct {
	ID   int64         `json:"id"`
	Ts   int64         `json:"ts"`
	Bids HuobiDepthPts `json:"bids"`
	Asks HuobiDepthPts `json:"asks"`
}

HuobiDepthTick models the tick field of the Huobi depth chart response.

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 HuobiPriceResponse

type HuobiPriceResponse struct {
	HuobiResponse
	Tick HuobiPriceTick `json:"tick"`
}

HuobiPriceResponse models the JSON data returned from the Huobi API.

type HuobiPriceTick

type HuobiPriceTick 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"`
}

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

type HuobiResponse

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

HuobiResponse models the common response fields in all API BittrexResponseResult

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 PoloniexCandlestickPt

type PoloniexCandlestickPt struct {
	Date            int64   `json:"date"`
	High            float64 `json:"high"`
	Low             float64 `json:"low"`
	Open            float64 `json:"open"`
	Close           float64 `json:"close"`
	Volume          float64 `json:"volume"`
	QuoteVolume     float64 `json:"quoteVolume"`
	WeightedAverage float64 `json:"weightedAverage"`
}

type PoloniexCandlestickResponse

type PoloniexCandlestickResponse []*PoloniexCandlestickPt

type PoloniexDepthArray

type PoloniexDepthArray []*PoloniexDepthPt

PoloniexDepthArray is a slice of depth chart data points.

type PoloniexDepthPt

type PoloniexDepthPt [2]interface{}

PoloniexDepthPt is a tuple of ["price", volume].

type PoloniexDepthResponse

type PoloniexDepthResponse struct {
	Asks     PoloniexDepthArray `json:"asks"`
	Bids     PoloniexDepthArray `json:"bids"`
	IsFrozen string             `json:"isFrozen"`
	Seq      int64              `json:"seq"`
}

PoloniexDepthResponse models the response from Poloniex for depth chart data.

type PoloniexExchange

type PoloniexExchange struct {
	*CommonExchange
	CurrencyPair string
	// contains filtered or unexported fields
}

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 URLs

type URLs struct {
	Price        string
	Depth        string
	Candlesticks map[candlestickKey]string
	Websocket    string
}

URLs is a set of endpoints for an exchange's various datasets.

type UpdateChannels

type UpdateChannels struct {
	Exchange chan *ExchangeUpdate
	Index    chan *IndexUpdate
	Quit     chan struct{}
}

UpdateChannels are requested by the user with ExchangeBot.UpdateChannels.

func NewUpdateChannels

func NewUpdateChannels() *UpdateChannels

NewUpdateChannels creates a new initialized set of UpdateChannels.

type WebsocketProcessor

type WebsocketProcessor func([]byte)

WebsocketProcessor is a callback for new websocket messages from the server.

Jump to

Keyboard shortcuts

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