coincap

package module
v0.0.0-...-784a6bf Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2022 License: MIT Imports: 10 Imported by: 0

README

GoLang CoinCap API

Library for interaction with CoinCap API 2.0. Supports all methods and types of responses including WebSockets.

How to install

go get -u github.com/karalef/coincap

Testing

go test .

Usage

import "github.com/karalef/coincap"

...

client := coincap.DefaultClient
Custom client
import "github.com/gorilla/websocket"

wsDialer := websocket.Dialer{
    ...
}

client := coincap.New(&http.Client{}, &wsDialer)

Examples

Get Asset data
asset, timestamp, err := client.AssetById("bitcoin")
Get historical data
params := coincap.CandlesRequest{
    ExchangeID: "binance",
    BaseID:     "ethereum",
    QuoteID:    "bitcoin",
}

interval := coincap.IntervalParams{
    Interval: coincap.Hour,
    Start:    time.Now().Add(-time.Day*5),
    End:      time.Now(),
}

candles, timestamp, err := client.Candles(params, &interval, nil)
WebSockets
stream, err := client.Trades("binance")
if err != nil {
    ...
}

ch := stream.DataChannel()
for {
    trade, ok := <-ch
    if !ok {
        err := stream.Err()
        ...
    }
    ...
}
stream.Close()

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidInterval = errors.New("invalid interval")
	ErrInvalidTimeSpan = errors.New("invalid time span")
	ErrIntervalBigger  = errors.New("invalid interval: bigger then time span")
)

interval errors.

View Source
var DefaultClient = NewClient(nil, nil)

DefaultClient is the default client.

Functions

This section is empty.

Types

type Asset

type Asset struct {
	ID                string  `json:"id"`                       // unique identifier for asset
	Rank              int     `json:"rank,string"`              // rank in terms of the asset's market cap
	Symbol            string  `json:"symbol"`                   // most common symbol used to identify this asset on an exchange
	Name              string  `json:"name"`                     // proper name for asset
	Supply            float64 `json:"supply,string"`            // available supply for trading
	MaxSupply         float64 `json:"maxSupply,string"`         // total quantity of asset issued
	MarketCapUsd      float64 `json:"marketCapUsd,string"`      // supply x price
	VolumeUsd24Hr     float64 `json:"volumeUsd24Hr,string"`     // quantity of trading volume in USD over last 24 hours
	PriceUsd          float64 `json:"priceUsd,string"`          // volume-weighted price based on real-time market data, translated to USD
	ChangePercent24Hr float64 `json:"changePercent24Hr,string"` // the direction and value change in the last 24 hours
	Vwap24Hr          float64 `json:"vwap24Hr,string"`          // Volume Weighted Average Price in the last 24 hours
}

Asset contains CoinCap asset data from exchanges.

type AssetHistory

type AssetHistory struct {
	PriceUSD float64   `json:"priceUsd,string"` // volume-weighted price in USD based on real-time market data
	Time     Timestamp `json:"time"`            // timestamp correlating to the given price
}

AssetHistory contains the USD price of an asset at a given timestamp.

type AssetMarket

type AssetMarket struct {
	ExchangeID    string  `json:"exchangeId"`           // unique identifier for exchange
	BaseID        string  `json:"baseId"`               // unique identifier for this asset, base is asset purchased
	QuoteID       string  `json:"quoteId"`              // unique identifier for this asset, quote is asset used to purchase based
	BaseSymbol    string  `json:"baseSymbol"`           // most common symbol used to identify asset, base is asset purchased
	QuoteSymbol   string  `json:"quoteSymbol"`          // most common symbol used to identify asset, quote is asset used to purchase base
	VolumeUsd24Hr float64 `json:"volumeUsd24Hr,string"` // volume transacted on this market in last 24 hours
	PriceUsd      float64 `json:"priceUsd,string"`      // the amount of quote asset traded for one unit of base asset
	VolumePercent float64 `json:"volumePercent,string"` // percent of quote asset volume
}

AssetMarket contains the markets info of an asset.

type Candle

type Candle struct {
	Open   float64   `json:"open,string"`   // the price (quote) at which the first transaction was completed in a given time period
	High   float64   `json:"high,string"`   // the top price (quote) at which the base was traded during the time period
	Low    float64   `json:"low,string"`    // the bottom price (quote) at which the base was traded during the time period
	Close  float64   `json:"close,string"`  // the price (quote) at which the last transaction was completed in a given time period
	Volume float64   `json:"volume,string"` // the amount of base asset traded in the given time period
	Period Timestamp `json:"period"`        // timestamp for starting of that time period
}

Candle represents historic market performance for an asset over a given time span.

type CandlesRequest

type CandlesRequest struct {
	ExchangeID string
	BaseID     string
	QuoteID    string
}

CandlesRequest contains the parameters you can use to provide a request for candles.

type Client

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

Client gives access to CoinCap API.

func NewClient

func NewClient(httpClient *http.Client, wsDialer *websocket.Dialer) Client

NewClient creates new CoinCap client.

func (*Client) AssetByID

func (c *Client) AssetByID(id string) (*Asset, Timestamp, error)

AssetByID returns an asset by its ID.

func (*Client) AssetHistory

func (c *Client) AssetHistory(id string, interval *IntervalParams) ([]AssetHistory, Timestamp, error)

AssetHistory returns USD price history of a given asset.

func (*Client) AssetMarkets

func (c *Client) AssetMarkets(id string, trim *TrimParams) ([]AssetMarket, Timestamp, error)

AssetMarkets returns markets info of a given asset.

func (*Client) Assets

func (c *Client) Assets() ([]Asset, Timestamp, error)

Assets returns a list of all CoinCap assets.

func (*Client) AssetsSearch

func (c *Client) AssetsSearch(search string, trim *TrimParams) ([]Asset, Timestamp, error)

AssetsSearch returns a list of CoinCap assets with params.

func (*Client) AssetsSearchByIDs

func (c *Client) AssetsSearchByIDs(ids []string) ([]Asset, Timestamp, error)

AssetsSearchByIDs returns a list of CoinCap assets.

func (*Client) Candles

func (c *Client) Candles(params CandlesRequest, interval *IntervalParams, trim *TrimParams) ([]Candle, Timestamp, error)

Candles returns all the market candle data for the provided exchange and parameters. The fields ExchangeID, BaseID, QuoteID, and Interval are required by the API.

func (*Client) ExchangeByID

func (c *Client) ExchangeByID(id string) (*Exchange, Timestamp, error)

ExchangeByID returns exchange data for an exchange with the given unique ID.

func (*Client) Exchanges

func (c *Client) Exchanges() ([]Exchange, Timestamp, error)

Exchanges returns information about all exchanges currently tracked by CoinCap.

func (*Client) Markets

func (c *Client) Markets(params MarketsRequest, trim *TrimParams) ([]Market, Timestamp, error)

Markets requests market data for all markets matching the criteria set in the MarketRequest params.

func (*Client) Prices

func (c *Client) Prices(assets ...string) (*Stream[map[string]float64], error)

Prices is the most accurate source of real-time changes to the global price of an asset. Each time the system receives data that moves the global price in one direction or another, this change is immediately published through the websocket. These prices correspond with the values shown in /assets - a value that may change several times per second based on market activity.

Emtpy 'assets' means prices for all assets.

func (*Client) RateByID

func (c *Client) RateByID(id string) (*Rate, Timestamp, error)

RateByID returns the USD rate for the given asset identifier.

func (*Client) Rates

func (c *Client) Rates() ([]Rate, Timestamp, error)

Rates returns currency rates standardized in USD.

func (*Client) Trades

func (c *Client) Trades(exchange string) (*Stream[*Trade], error)

Trades streams trades from other cryptocurrency exchange websockets. Users must select a specific exchange. In the /exchanges endpoint users can determine if an exchange has a socket available by noting response 'socket':true/false. The trades websocket is the only way to receive individual trade data through CoinCap.

type Exchange

type Exchange struct {
	ID                 string    `json:"exchangeId"`                // unique identifier for exchange
	Name               string    `json:"name"`                      // proper name of exchange
	Rank               int       `json:"rank,string"`               // rank in terms of total volume compared to other exchanges
	PercentTotalVolume float64   `json:"percentTotalVolume,string"` // perecent of total daily volume in relation to all exchanges
	VolumeUSD          float64   `json:"volumeUSD,string"`          // daily volume represented in USD
	TradingPairs       int       `json:"tradingPairs,string"`       // number of trading pairs offered by the exchange
	Socket             bool      `json:"socket"`                    // Whether or not a trade socket is available on this exchange
	URL                string    `json:"exchangeUrl"`               // url of exchange
	Updated            Timestamp `json:"updated"`                   // Time since information was last updated
}

Exchange contains information about a cryptocurrency exchange.

type Interval

type Interval uint8

Interval type.

const (
	Hour Interval = iota
	Minute
	FiveMinutes
	FifteenMinutes
	ThirtyMinutes
	TwoHours
	SixHours
	TwelveHours
	Day
	FourHours
	EightHours
	Week
)

Valid Intervals for historical market data Used when requesting Asset History and Candles

type IntervalParams

type IntervalParams struct {
	Interval Interval  // point-in-time interval.
	Start    time.Time // start time.
	End      time.Time // end time.
}

IntervalParams contains interval and time span parameters.

type Market

type Market struct {
	ExchangeID            string    `json:"exchangeId"`                   // unique identifier for exchange
	Rank                  int       `json:"rank,string"`                  // rank in terms of volume transacted in this market
	BaseSymbol            string    `json:"baseSymbol"`                   // most common symbol used to identify this asset
	BaseID                string    `json:"baseId"`                       // unique identifier for this asset. base is the asset purchased
	QuoteSymbol           string    `json:"quoteSymbol"`                  // most common symbol used to identify this asset
	QuoteID               string    `json:"quoteId"`                      // unique identifier for this asset. quote is the asset used to purchase base
	PriceQuote            float64   `json:"priceQuote,string"`            // amount of quote asset traded for 1 unit of base asset
	PriceUsd              float64   `json:"priceUsd,string"`              // quote price translated to USD
	VolumeUsd24Hr         float64   `json:"volumeUsd24Hr,string"`         // volume transacted in this market in the last 24 hours
	PercentExchangeVolume float64   `json:"percentExchangeVolume,string"` // amount of daily volume this market transacts compared to others on this exchange
	TradesCount24Hr       int       `json:"tradesCount24Hr,string"`       // number of trades on this market in the last 24 hours
	Updated               Timestamp `json:"updated"`                      // last time information was received from this market
}

Market contains the market data response from the api.

type MarketsRequest

type MarketsRequest struct {
	ExchangeID  string // search by unique exchange ID
	BaseSymbol  string // return all results with this base symbol
	BaseID      string // return all results with this base id
	QuoteSymbol string // return all results with this quote symbol
	QuoteID     string // return all results with this quote ID
	AssetSymbol string // return all results with this asset symbol
	AssetID     string // return all results with this asset ID
}

MarketsRequest contains the parameters you can use to provide a request for market data.

type Rate

type Rate struct {
	ID             string  `json:"id"`             // unique identifier for asset or fiat
	Symbol         string  `json:"symbol"`         // most common symbol used to identify asset or fiat
	CurrencySymbol string  `json:"currencySymbol"` // currency symbol if available
	RateUSD        float64 `json:"rateUsd,string"` // rate conversion to USD
	Type           string  `json:"type"`           // type of currency - fiat or crypto
}

Rate contains the exchange rate of a given asset in terms of USD as well as common identifiers for the asset in question and whether or not it is a fiat currency

type Stream

type Stream[T any] struct {
	// contains filtered or unexported fields
}

Stream streams data from websocket conneсtion.

func (*Stream[T]) Close

func (s *Stream[T]) Close()

Close closes stream.

func (*Stream[T]) DataChannel

func (s *Stream[T]) DataChannel() <-chan T

DataChannel returns data channel. It will be closed if there is an error or if the stream is closed.

func (*Stream[T]) Err

func (s *Stream[T]) Err() error

type Timestamp

type Timestamp int64

Timestamp represents CoinCap timestamp (UNIX time in milliseconds).

func (Timestamp) String

func (t Timestamp) String() string

func (Timestamp) Time

func (t Timestamp) Time() time.Time

Time converts CoinCap timestamp into local time.

type Trade

type Trade struct {
	Exchange  string  `json:"exchange"`
	Base      string  `json:"base"`
	Quote     string  `json:"quote"`
	Direction string  `json:"direction"`
	Price     float64 `json:"price"`
	Volume    float64 `json:"volume"`
	Timestamp int64   `json:"timestamp"`
	PriceUSD  float64 `json:"priceUds"`
}

Trade type.

type TrimParams

type TrimParams struct {
	Limit  uint // maximum number of results.
	Offset uint // skip the first N entries of the result set.
}

TrimParams contains limit and offset parameters.

Jump to

Keyboard shortcuts

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