provider

package
v1.0.1-alpha Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2023 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	KrakenRestHost = "https://api.kraken.com"
)

Variables

This section is empty.

Functions

func PastUnixTime

func PastUnixTime(t time.Duration) int64

PastUnixTime returns a millisecond timestamp that represents the unix time minus t.

Types

type AggregatedProviderCandles

type AggregatedProviderCandles map[Name]map[string][]types.CandlePrice

AggregatedProviderCandles defines a type alias for a map of provider -> asset -> []types.CandlePrice.

type AggregatedProviderPrices

type AggregatedProviderPrices map[Name]map[string]types.TickerPrice

AggregatedProviderPrices defines a type alias for a map of provider -> asset -> TickerPrice.

type BinanceCandle

type BinanceCandle struct {
	Symbol   string                `json:"s"` // Symbol ex.: ATOMUSD
	Metadata BinanceCandleMetadata `json:"k"` // Metadata for candle
}

BinanceCandle candle binance websocket channel "kline_1m" response.

type BinanceCandleMetadata

type BinanceCandleMetadata struct {
	Close     string `json:"c"` // Price at close
	TimeStamp int64  `json:"T"` // Close time in unix epoch ex.: 1645756200000
	Volume    string `json:"v"` // Volume during period
}

BinanceCandleMetadata candle metadata used to compute tvwap price.

type BinancePairSummary

type BinancePairSummary struct {
	Symbol string `json:"symbol"`
}

BinancePairSummary defines the response structure for a Binance pair summary.

type BinanceProvider

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

BinanceProvider defines an Oracle provider implemented by the Binance public API.

REF: https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-mini-ticker-stream REF: https://binance-docs.github.io/apidocs/spot/en/#kline-candlestick-streams

func NewBinanceProvider

func NewBinanceProvider(
	ctx context.Context,
	logger zerolog.Logger,
	endpoints Endpoint,
	binanceUS bool,
	pairs ...types.CurrencyPair,
) (*BinanceProvider, error)

func (*BinanceProvider) GetCandlePrices

func (p *BinanceProvider) GetCandlePrices(pairs ...types.CurrencyPair) (map[string][]types.CandlePrice, error)

GetCandlePrices returns the candlePrices based on the provided pairs.

func (*BinanceProvider) GetTickerPrices

func (p *BinanceProvider) GetTickerPrices(pairs ...types.CurrencyPair) (map[string]types.TickerPrice, error)

GetTickerPrices returns the tickerPrices based on the provided pairs.

func (*BinanceProvider) SubscribeCurrencyPairs

func (p *BinanceProvider) SubscribeCurrencyPairs(cps ...types.CurrencyPair) error

SubscribeCurrencyPairs sends the new subscription messages to the websocket and adds them to the providers subscribedPairs array.

type BinanceSubscriptionMsg

type BinanceSubscriptionMsg struct {
	Method string   `json:"method"` // SUBSCRIBE/UNSUBSCRIBE
	Params []string `json:"params"` // streams to subscribe ex.: usdatom@ticker
	ID     uint16   `json:"id"`     // identify messages going back and forth
}

BinanceSubscriptionMsg Msg to subscribe all the tickers channels.

type BinanceSubscriptionResp

type BinanceSubscriptionResp struct {
	Result string `json:"result"`
	ID     uint16 `json:"id"`
}

BinanceSubscriptionResp the response structure for a binance subscription response.

type BinanceTicker

type BinanceTicker struct {
	Symbol    string `json:"s"` // Symbol ex.: ATOMUSD
	LastPrice string `json:"c"` // Last price ex.: 0.0025
	Volume    string `json:"v"` // Total traded base asset volume ex.: 1000
	C         uint64 `json:"C"` // Statistics close time
}

BinanceTicker ticker price response. https://pkg.go.dev/encoding/json#Unmarshal Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. C field which is Statistics close time is not used, but it avoids implementing specific UnmarshalJSON.

type CoinbaseErrResponse

type CoinbaseErrResponse struct {
	Type   string `json:"type"`   // should be "error"
	Reason string `json:"reason"` // ex.: "tickers" is not a valid channel
}

CoinbaseErrResponse defines the response body for errors.

type CoinbasePairSummary

type CoinbasePairSummary struct {
	Base  string `json:"base_currency"`
	Quote string `json:"quote_currency"`
}

CoinbasePairSummary defines the response structure for a Coinbase pair summary.

type CoinbaseProvider

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

CoinbaseProvider defines an Oracle provider implemented by the Coinbase public API.

REF: https://www.coinbase.io/docs/websocket/index.html

func NewCoinbaseProvider

func NewCoinbaseProvider(
	ctx context.Context,
	logger zerolog.Logger,
	endpoints Endpoint,
	pairs ...types.CurrencyPair,
) (*CoinbaseProvider, error)

NewCoinbaseProvider creates a new CoinbaseProvider.

func (*CoinbaseProvider) GetAvailablePairs

func (p *CoinbaseProvider) GetAvailablePairs() (map[string]struct{}, error)

GetAvailablePairs returns all pairs to which the provider can subscribe.

func (*CoinbaseProvider) GetCandlePrices

func (p *CoinbaseProvider) GetCandlePrices(pairs ...types.CurrencyPair) (map[string][]types.CandlePrice, error)

func (*CoinbaseProvider) GetTickerPrices

func (p *CoinbaseProvider) GetTickerPrices(pairs ...types.CurrencyPair) (map[string]types.TickerPrice, error)

GetTickerPrices returns the tickerPrices based on the saved map.

func (*CoinbaseProvider) SubscribeCurrencyPairs

func (p *CoinbaseProvider) SubscribeCurrencyPairs(cps ...types.CurrencyPair) error

SubscribeCurrencyPairs sends the new subscription messages to the websocket and adds them to the providers subscribedPairs array.

type CoinbaseSubscriptionMsg

type CoinbaseSubscriptionMsg struct {
	Type       string   `json:"type"`        // ex. "subscribe"
	ProductIDs []string `json:"product_ids"` // streams to subscribe ex.: ["BOT-USDT", ...]
	Channels   []string `json:"channels"`    // channels to subscribe to ex.: "ticker"
}

CoinbaseSubscriptionMsg Msg to subscribe to all channels.

type CoinbaseTicker

type CoinbaseTicker struct {
	ProductID string `json:"product_id"` // ex.: ATOM-USDT
	Price     string `json:"price"`      // ex.: 523.0
	Volume    string `json:"volume_24h"` // 24-hour volume
}

CoinbaseTicker defines the ticker info we'd like to save.

type CoinbaseTrade

type CoinbaseTrade struct {
	ProductID string // ex.: ATOM-USDT
	Time      int64  // Time in unix epoch ex.: 164732388700
	Size      string // Size of the trade ex.: 10.41
	Price     string // ex.: 14.02
}

CoinbaseTrade defines the trade info we'd like to save.

type CoinbaseTradeResponse

type CoinbaseTradeResponse struct {
	Type      string `json:"type"`       // "last_match" or "match"
	ProductID string `json:"product_id"` // ex.: ATOM-USDT
	Time      string `json:"time"`       // Time in format 2006-01-02T15:04:05.000000Z
	Size      string `json:"size"`       // Size of the trade ex.: 10.41
	Price     string `json:"price"`      // ex.: 14.02
}

CoinbaseMatchResponse defines the response body for coinbase trades.

type CryptoCandle

type CryptoCandle struct {
	Close     string `json:"c"` // Price at close
	Volume    string `json:"v"` // Volume during interval
	Timestamp int64  `json:"t"` // End time of candlestick (Unix timestamp)
}

type CryptoCandleResponse

type CryptoCandleResponse struct {
	Result CryptoCandleResult `json:"result"`
}

type CryptoCandleResult

type CryptoCandleResult struct {
	InstrumentName string         `json:"instrument_name"` // ex.: ATOM_USDT
	Channel        string         `json:"channel"`         // ex.: candlestick
	Data           []CryptoCandle `json:"data"`            // candlestick data
}

type CryptoHeartbeatRequest

type CryptoHeartbeatRequest struct {
	ID     int64  `json:"id"`
	Method string `json:"method"` // public/respond-heartbeat
}

type CryptoHeartbeatResponse

type CryptoHeartbeatResponse struct {
	ID     int64  `json:"id"`
	Method string `json:"method"` // public/heartbeat
}

type CryptoInstruments

type CryptoInstruments struct {
	Data []CryptoTicker `json:"data"`
}

type CryptoPairsSummary

type CryptoPairsSummary struct {
	Result CryptoInstruments `json:"result"`
}

type CryptoProvider

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

CryptoProvider defines an Oracle provider implemented by the Crypto.com public API.

REF: https://exchange-docs.crypto.com/spot/index.html#introduction

func NewCryptoProvider

func NewCryptoProvider(
	ctx context.Context,
	logger zerolog.Logger,
	endpoints Endpoint,
	pairs ...types.CurrencyPair,
) (*CryptoProvider, error)

func (*CryptoProvider) GetAvailablePairs

func (p *CryptoProvider) GetAvailablePairs() (map[string]struct{}, error)

GetAvailablePairs returns all pairs to which the provider can subscribe. ex.: map["ATOMUSDT" => {}, "USDCUSDT" => {}].

func (*CryptoProvider) GetCandlePrices

func (p *CryptoProvider) GetCandlePrices(pairs ...types.CurrencyPair) (map[string][]types.CandlePrice, error)

GetCandlePrices returns the candlePrices based on the saved map.

func (*CryptoProvider) GetTickerPrices

func (p *CryptoProvider) GetTickerPrices(pairs ...types.CurrencyPair) (map[string]types.TickerPrice, error)

GetTickerPrices returns the tickerPrices based on the saved map.

func (*CryptoProvider) SubscribeCurrencyPairs

func (p *CryptoProvider) SubscribeCurrencyPairs(cps ...types.CurrencyPair) error

SubscribeCurrencyPairs sends the new subscription messages to the websocket and adds them to the providers subscribedPairs array.

type CryptoSubscriptionMsg

type CryptoSubscriptionMsg struct {
	ID     int64                    `json:"id"`
	Method string                   `json:"method"` // subscribe, unsubscribe
	Params CryptoSubscriptionParams `json:"params"`
	Nonce  int64                    `json:"nonce"` // Current timestamp (milliseconds since the Unix epoch)
}

type CryptoSubscriptionParams

type CryptoSubscriptionParams struct {
	Channels []string `json:"channels"` // Channels to be subscribed ex. ticker.ATOM_USDT
}

type CryptoTicker

type CryptoTicker struct {
	InstrumentName string `json:"i"` // Instrument Name, e.g. BTC_USDT, ETH_CRO, etc.
	Volume         string `json:"v"` // The total 24h traded volume
	LatestTrade    string `json:"a"` // The price of the latest trade, null if there weren't any trades
}

type CryptoTickerResponse

type CryptoTickerResponse struct {
	Result CryptoTickerResult `json:"result"`
}

type CryptoTickerResult

type CryptoTickerResult struct {
	InstrumentName string         `json:"instrument_name"` // ex.: ATOM_USDT
	Channel        string         `json:"channel"`         // ex.: ticker
	Data           []CryptoTicker `json:"data"`            // ticker data
}

type Endpoint

type Endpoint struct {
	// Name of the provider, ex. "binance"
	Name Name `toml:"name"`

	// Rest endpoint for the provider, ex. "https://api1.binance.com"
	Rest string `toml:"rest"`

	// Websocket endpoint for the provider, ex. "stream.binance.com:9443"
	Websocket string `toml:"websocket"`
}

Endpoint defines an override setting in our config for the hardcoded rest and websocket api endpoints.

type HuobiCandle

type HuobiCandle struct {
	CH   string          `json:"ch"` // Channel name. Format:market.$symbol.kline.$period
	Tick HuobiCandleTick `json:"tick"`
}

HuobiCandle defines the response type for the channel and the tick object for a given ticker/symbol.

type HuobiCandleTick

type HuobiCandleTick struct {
	Close     float64 `json:"close"` // Closing price during this period
	TimeStamp int64   `json:"id"`    // TimeStamp for this as an ID
	Volume    float64 `json:"vol"`   // Volume during this period
}

HuobiCandleTick defines the response type for the candle.

type HuobiPairData

type HuobiPairData struct {
	Symbol string `json:"symbol"`
}

HuobiPairData defines the data response structure for an Huobi pair.

type HuobiPairsSummary

type HuobiPairsSummary struct {
	Data []HuobiPairData `json:"data"`
}

HuobiPairsSummary defines the response structure for an Huobi pairs summary.

type HuobiProvider

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

HuobiProvider defines an Oracle provider implemented by the Huobi public API.

REF: https://huobiapi.github.io/docs/spot/v1/en/#market-ticker REF: https://huobiapi.github.io/docs/spot/v1/en/#get-klines-candles

func NewHuobiProvider

func NewHuobiProvider(
	ctx context.Context,
	logger zerolog.Logger,
	endpoints Endpoint,
	pairs ...types.CurrencyPair,
) (*HuobiProvider, error)

NewHuobiProvider returns a new Huobi provider with the WS connection and msg handler.

func (*HuobiProvider) GetAvailablePairs

func (p *HuobiProvider) GetAvailablePairs() (map[string]struct{}, error)

GetAvailablePairs returns all pairs to which the provider can subscribe.

func (*HuobiProvider) GetCandlePrices

func (p *HuobiProvider) GetCandlePrices(pairs ...types.CurrencyPair) (map[string][]types.CandlePrice, error)

GetTickerPrices returns the tickerPrices based on the saved map.

func (*HuobiProvider) GetTickerPrices

func (p *HuobiProvider) GetTickerPrices(pairs ...types.CurrencyPair) (map[string]types.TickerPrice, error)

GetTickerPrices returns the tickerPrices based on the saved map.

func (*HuobiProvider) SubscribeCurrencyPairs

func (p *HuobiProvider) SubscribeCurrencyPairs(cps ...types.CurrencyPair) error

SubscribeCurrencyPairs sends the new subscription messages to the websocket and adds them to the providers subscribedPairs array.

type HuobiSubscriptionMsg

type HuobiSubscriptionMsg struct {
	Sub string `json:"sub"` // channel to subscribe market.$symbol.ticker
}

HuobiSubscriptionMsg Msg to subscribe to one ticker channel at time.

type HuobiSubscriptionResp

type HuobiSubscriptionResp struct {
	Status string `json:"status"`
}

HuobiSubscriptionResp the response structure for a Huobi subscription response.

type HuobiTick

type HuobiTick struct {
	Vol       float64 `json:"vol"`           // Accumulated trading value of last 24 hours
	LastPrice float64 `json:"lastPriceAtom"` // Last traded price
}

HuobiTick defines the response type for the last 24h market summary and the last traded price for a given ticker/symbol.

type HuobiTicker

type HuobiTicker struct {
	CH   string    `json:"ch"` // Channel name. Format:market.$symbol.ticker
	Tick HuobiTick `json:"tick"`
}

HuobiTicker defines the response type for the channel and the tick object for a given ticker/symbol.

type KrakenCandle

type KrakenCandle struct {
	Close     string // Close price during this period
	TimeStamp int64  // Linux epoch timestamp
	Volume    string // Volume during this period
	Symbol    string // Symbol for this candle
}

KrakenCandle candle response from Kraken candle channel. REF: https://docs.kraken.com/websockets/#message-ohlc

func (*KrakenCandle) UnmarshalJSON

func (candle *KrakenCandle) UnmarshalJSON(buf []byte) error

type KrakenEvent

type KrakenEvent struct {
	Event string `json:"event"` // events from kraken ex.: systemStatus | subscriptionStatus
}

KrakenEvent wraps the possible events from the provider.

type KrakenEventSubscriptionStatus

type KrakenEventSubscriptionStatus struct {
	Status       string `json:"status"`       // subscribed|unsubscribed|error
	Pair         string `json:"pair"`         // Pair symbol base/quote ex.: "XBT/USD"
	ErrorMessage string `json:"errorMessage"` // error description
}

KrakenEventSubscriptionStatus parse the subscriptionStatus event message.

type KrakenPairData

type KrakenPairData struct {
	WsName string `json:"wsname"`
}

KrakenPairData defines the data response structure for an Kraken pair.

type KrakenPairsSummary

type KrakenPairsSummary struct {
	Result map[string]KrakenPairData `json:"result"`
}

KrakenPairsSummary defines the response structure for an Kraken pairs summary.

type KrakenProvider

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

KrakenProvider defines an Oracle provider implemented by the Kraken public API.

REF: https://docs.kraken.com/websockets/#overview

func NewKrakenProvider

func NewKrakenProvider(
	ctx context.Context,
	logger zerolog.Logger,
	endpoints Endpoint,
	pairs ...types.CurrencyPair,
) (*KrakenProvider, error)

NewKrakenProvider returns a new Kraken provider with the WS connection and msg handler.

func (*KrakenProvider) GetCandlePrices

func (p *KrakenProvider) GetCandlePrices(pairs ...types.CurrencyPair) (map[string][]types.CandlePrice, error)

GetCandlePrices returns the candlePrices based on the saved map.

func (*KrakenProvider) GetTickerPrices

func (p *KrakenProvider) GetTickerPrices(pairs ...types.CurrencyPair) (map[string]types.TickerPrice, error)

GetTickerPrices returns the tickerPrices based on the saved map.

func (*KrakenProvider) SubscribeCurrencyPairs

func (p *KrakenProvider) SubscribeCurrencyPairs(cps ...types.CurrencyPair) error

SubscribeCurrencyPairs sends the new subscription messages to the websocket and adds them to the providers subscribedPairs array.

type KrakenSubscriptionChannel

type KrakenSubscriptionChannel struct {
	Name string `json:"name"` // channel to be subscribed ex.: ticker
}

KrakenSubscriptionChannel Msg with the channel name to be subscribed.

type KrakenSubscriptionMsg

type KrakenSubscriptionMsg struct {
	Event        string                    `json:"event"`        // subscribe/unsubscribe
	Pair         []string                  `json:"pair"`         // Array of currency pairs ex.: "BTC/USD",
	Subscription KrakenSubscriptionChannel `json:"subscription"` // subscription object
}

KrakenSubscriptionMsg Msg to subscribe to all the pairs at once.

type KrakenTicker

type KrakenTicker struct {
	C []string `json:"c"` // Close with Price in the first position
	V []string `json:"v"` // Volume with the value over last 24 hours in the second position
}

KrakenTicker ticker price response from Kraken ticker channel. REF: https://docs.kraken.com/websockets/#message-ticker

type MessageHandler

type MessageHandler func(int, []byte)

type MockProvider

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

MockProvider defines a mocked exchange rate provider using a published Google sheets document to fetch mocked/fake exchange rates.

func NewMockProvider

func NewMockProvider(baseURL string, client *http.Client) (*MockProvider, error)

func (*MockProvider) GetCandlePrices

func (p *MockProvider) GetCandlePrices(pairs ...types.CurrencyPair) (map[string][]types.CandlePrice, error)

func (*MockProvider) GetTickerPrices

func (p *MockProvider) GetTickerPrices(pairs ...types.CurrencyPair) (map[string]types.TickerPrice, error)

GetTickerPrices returns the mocked ticker price for the given symbol.

func (MockProvider) SubscribeCurrencyPairs

func (p MockProvider) SubscribeCurrencyPairs(...types.CurrencyPair) error

SubscribeCurrencyPairs performs a no-op since mock does not use websocket.

type Name

type Name string

Name name of an oracle provider. Usually it is an exchange but this can be any provider name that can give token prices examples.: "binance", "osmosis", "kraken".

const (
	Kraken    Name = "kraken"
	Binance   Name = "binance"
	BinanceUS Name = "binanceus"
	Osmosis   Name = "osmosis"
	Crypto    Name = "crypto"
	Coinbase  Name = "coinbase"
	Huobi     Name = "huobi"
	Mock      Name = "mock"
)

func (Name) String

func (n Name) String() string

String cast provider name to string.

type OsmosisCandleResponse

type OsmosisCandleResponse struct {
	Time   int64   `json:"time"`
	Close  float64 `json:"close"`
	Volume float64 `json:"volume"`
}

OsmosisCandleResponse defines the response structure for an Osmosis candle request.

type OsmosisPairData

type OsmosisPairData struct {
	Base  string `json:"base_symbol"`
	Quote string `json:"quote_symbol"`
}

OsmosisPairData defines the data response structure for an Osmosis pair.

type OsmosisPairsSummary

type OsmosisPairsSummary struct {
	Data []OsmosisPairData `json:"data"`
}

OsmosisPairsSummary defines the response structure for an Osmosis pairs summary.

type OsmosisProvider

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

OsmosisProvider defines an Oracle provider implemented by the Osmosis public API.

REF: https://api-osmosis.imperator.co/swagger/

func NewOsmosisProvider

func NewOsmosisProvider(endpoint Endpoint) *OsmosisProvider

func (OsmosisProvider) GetAvailablePairs

func (p OsmosisProvider) GetAvailablePairs() (map[string]struct{}, error)

GetAvailablePairs return all available pairs symbol to susbscribe.

func (OsmosisProvider) GetCandlePrices

func (p OsmosisProvider) GetCandlePrices(pairs ...types.CurrencyPair) (map[string][]types.CandlePrice, error)

func (OsmosisProvider) GetTickerPrices

func (p OsmosisProvider) GetTickerPrices(pairs ...types.CurrencyPair) (map[string]types.TickerPrice, error)

func (OsmosisProvider) SubscribeCurrencyPairs

func (OsmosisProvider) SubscribeCurrencyPairs(...types.CurrencyPair) error

SubscribeCurrencyPairs performs a no-op since osmosis does not use websockets.

type OsmosisTokenResponse

type OsmosisTokenResponse struct {
	Price  float64 `json:"price"`
	Symbol string  `json:"symbol"`
	Volume float64 `json:"volume_24h"`
}

OsmosisTokenResponse defines the response structure for an Osmosis token request.

type Provider

type Provider interface {
	// GetTickerPrices returns the tickerPrices based on the provided pairs.
	GetTickerPrices(...types.CurrencyPair) (map[string]types.TickerPrice, error)

	// GetCandlePrices returns the candlePrices based on the provided pairs.
	GetCandlePrices(...types.CurrencyPair) (map[string][]types.CandlePrice, error)

	// SubscribeCurrencyPairs sends subscription messages for the new currency
	// pairs and adds them to the providers subscribed pairs
	SubscribeCurrencyPairs(...types.CurrencyPair) error
}

Provider defines an interface an exchange price provider must implement.

type WebsocketController

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

WebsocketController defines a provider agnostic websocket handler that manages reconnecting, subscribing, and receiving messages.

func NewWebsocketController

func NewWebsocketController(
	parentCtx context.Context,
	providerName Name,
	url url.URL,
	subscriptionMsgs []interface{},
	messageHandler MessageHandler,
	pingDuration time.Duration,
	pingMessageType uint,
	logger zerolog.Logger,
) *WebsocketController

NewWebsocketController does nothing except initialize a new WebsocketController and provider a reminder for what fields need to be passed in.

func (*WebsocketController) AddSubscriptionMsgs

func (wsc *WebsocketController) AddSubscriptionMsgs(msgs []interface{}) error

AddSubscriptionMsgs immediately sends the new subscription messages and adds them to the subscriptionMsgs array if successful.

func (*WebsocketController) SendJSON

func (wsc *WebsocketController) SendJSON(msg interface{}) error

SendJSON sends a json message to the websocket connection using the Websocket Controller mutex to ensure multiple writes do not happen at once.

func (*WebsocketController) Start

func (wsc *WebsocketController) Start()

Start will continuously loop and attempt connecting to the websocket until a successful connection is made. It then starts the ping service and read listener in new go routines and sends subscription messages using the passed in subscription messages.

Jump to

Keyboard shortcuts

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