Documentation
¶
Overview ¶
Package glassnode is a client for the Glassnode API (https://docs.glassnode.com).
Create a Client with NewClient and reuse it; it is safe for concurrent use. Every method takes a context.Context, which controls cancellation and the overall deadline of the call, including retries:
client, err := glassnode.NewClient(apiKey)
if err != nil {
return err
}
points, err := client.GetTimeSeries(ctx, "market/price_usd_close", &glassnode.MetricParams{
Asset: "BTC",
Interval: "24h",
})
Timestamps are Unix seconds, and missing values are nil pointers. Methods such as GetTimeSeries, GetObjectTimeSeries and GetBulkMetric cover the common response shapes; GetMetric, Get and Raw handle everything else.
The package reads no environment variables or files: all configuration, including credentials, is passed to NewClient as options. Errors can be inspected with errors.As for APIError, InputError, TransportError, DecodeError and AuthError.
Index ¶
- Constants
- Variables
- type APIAddon
- type APIError
- type APIUsage
- type Allowance
- type AllowancePeriod
- type Asset
- type AssetsResponse
- type AuthError
- type Blockchain
- type BulkDataPoint
- type BulkEntry
- type Client
- func (c *Client) Get(ctx context.Context, endpoint string, params url.Values, dst any) error
- func (c *Client) GetAPIUsage(ctx context.Context) (*APIUsage, error)
- func (c *Client) GetBulkMetric(ctx context.Context, path string, params *MetricParams) ([]BulkDataPoint, error)
- func (c *Client) GetMetric(ctx context.Context, path string, params *MetricParams, dst any) error
- func (c *Client) GetMetricCSV(ctx context.Context, path string, params *MetricParams, w io.Writer) error
- func (c *Client) GetMetricMetadata(ctx context.Context, path string, params *MetricParams) (*MetricMetadata, error)
- func (c *Client) GetMetricStats(ctx context.Context, path string, params *MetricParams) (*MetricStats, error)
- func (c *Client) GetObjectTimeSeries(ctx context.Context, path string, params *MetricParams) ([]ObjectTimeSeriesPoint, error)
- func (c *Client) GetTimeSeries(ctx context.Context, path string, params *MetricParams) ([]TimeSeriesPoint, error)
- func (c *Client) ListAssetBlockchains(ctx context.Context, filter string) ([]string, error)
- func (c *Client) ListAssetCategories(ctx context.Context, filter string) ([]string, error)
- func (c *Client) ListAssetTags(ctx context.Context, filter string) ([]string, error)
- func (c *Client) ListAssets(ctx context.Context, filter string) ([]Asset, error)
- func (c *Client) ListExchanges(ctx context.Context) ([]string, error)
- func (c *Client) ListMetricTags(ctx context.Context) ([]string, error)
- func (c *Client) ListMetrics(ctx context.Context, params *MetricParams) ([]string, error)
- func (c *Client) ListMiners(ctx context.Context) ([]string, error)
- func (c *Client) ListNames(ctx context.Context, endpoint, filter string) ([]string, error)
- func (c *Client) ListNetworks(ctx context.Context) ([]string, error)
- func (c *Client) Raw(ctx context.Context, endpoint string, params url.Values) ([]byte, error)
- type DecodeError
- type InputError
- type LagPercentiles
- type MetricDescriptors
- type MetricLagEntry
- type MetricMetadata
- type MetricParams
- type MetricStats
- type MetricVariant
- type NameEntry
- type NamesResponse
- type ObjectTimeSeriesPoint
- type Option
- func WithAPIKeyInQuery() Option
- func WithBaseURL(raw string) Option
- func WithBearerToken(token string) Option
- func WithHTTPClient(client *http.Client) Option
- func WithMaxResponseBytes(limit int64) Option
- func WithRetryPolicy(policy RetryPolicy) Option
- func WithTimeout(timeout time.Duration) Option
- func WithTokenSource(source TokenSource) Option
- func WithUserAgent(agent string) Option
- type Refs
- type ResponseTooLargeError
- type RetryPolicy
- type TimeRange
- type TimeSeriesPoint
- type TokenRefresher
- type TokenSource
- type TokenSourceFunc
- type TransportError
Examples ¶
Constants ¶
const DefaultBaseURL = "https://api.glassnode.com"
DefaultBaseURL is the standard Glassnode API endpoint.
Variables ¶
var ErrResponseTooLarge = errors.New("response exceeds the configured size limit")
ErrResponseTooLarge is the cause of every ResponseTooLargeError, for errors.Is.
Functions ¶
This section is empty.
Types ¶
type APIAddon ¶
type APIAddon struct {
Value int `json:"value"`
Period AllowancePeriod `json:"period,omitempty"`
RPM int `json:"rpm,omitempty"`
}
APIAddon is an API allowance returned by the usage endpoint: Value units per Period, at most RPM requests per minute when the API reports it.
type APIError ¶
APIError describes a non-2xx response. Detail is bounded and credential-redacted. RetryAfter is how long the server asked the client to wait, taken from the Retry-After header or, for 429 responses, from x-rate-limit-reset. It is zero when the server gave no such hint.
type APIUsage ¶
type APIUsage struct {
CreditsUsed int `json:"creditsUsed"`
DailyRequestsUsed int `json:"dailyRequestsUsed"`
APIAddons []APIAddon `json:"apiAddons"`
}
APIUsage reports usage and subscribed API allowances. CreditsUsed counts credits this month and DailyRequestsUsed counts requests today; each is the counter for an allowance of the matching period.
func (*APIUsage) Allowance ¶ added in v0.2.0
Allowance returns the account's allowance with the usage of the matching period. ok is false when the account has no add-on, an add-on reports a period the client does not know, or add-ons of different periods are combined, since no single counter then applies; callers should not guess.
func (*APIUsage) CreditsPerMonth
deprecated
func (*APIUsage) UnmarshalJSON ¶
UnmarshalJSON requires creditsUsed and tolerates missing add-ons.
type Allowance ¶ added in v0.2.0
type Allowance struct {
Limit int
Period AllowancePeriod
Used int
}
Allowance is an account's API allowance and the usage counted against it. On a daily allowance the unit is requests and Used is today's requests; on a monthly allowance the unit is credits and Used is this month's credits.
type AllowancePeriod ¶ added in v0.2.0
type AllowancePeriod string
AllowancePeriod is the period an API allowance is granted over.
const ( AllowanceDaily AllowancePeriod = "daily" AllowanceMonthly AllowancePeriod = "monthly" )
Allowance periods reported by the usage endpoint. An add-on without a period predates the field and is monthly.
type Asset ¶
type Asset struct {
ID string `json:"id"`
ExternalIDs map[string]string `json:"external_ids,omitempty"`
Symbol string `json:"symbol"`
Name string `json:"name"`
AssetType string `json:"asset_type"`
Blockchains []Blockchain `json:"blockchains"`
Categories []string `json:"categories,omitempty"`
LogoURL string `json:"logo_url,omitempty"`
SemanticTags []string `json:"semantic_tags,omitempty"`
DefaultNetwork string `json:"default_network,omitempty"`
}
Asset describes a supported blockchain asset or token.
type AssetsResponse ¶
type AssetsResponse struct {
Data []Asset `json:"data"`
}
AssetsResponse is the wire envelope for asset metadata.
type AuthError ¶
type AuthError struct{ Err error }
AuthError describes a token-source failure or an invalid token. It is never retried. Messages redact credentials used in the call; the token source must avoid returning errors containing other credentials unknown to the SDK. Unwrapped causes may contain secrets and should not be logged indiscriminately.
type Blockchain ¶
type Blockchain struct {
Blockchain string `json:"blockchain"`
Address string `json:"address,omitempty"`
Decimals int `json:"decimals,omitempty"`
OnChainSupport bool `json:"on_chain_support"`
}
Blockchain describes a token deployment and on-chain support.
type BulkDataPoint ¶
BulkDataPoint groups asset values at a Unix timestamp in seconds.
func (*BulkDataPoint) UnmarshalJSON ¶
func (p *BulkDataPoint) UnmarshalJSON(data []byte) error
UnmarshalJSON requires the timestamp and bulk entries.
type BulkEntry ¶
BulkEntry is one value of a bulk response. Params holds every selector that identifies the entry, such as "a", "e", "network" or, for object metrics, "category"; which selectors appear depends on the metric. Asset and Network read the common ones.
Selector values are strings in the API. Should a selector arrive as another JSON type, Params holds its JSON text (5 becomes "5"); use GetMetric with your own type when exact types matter.
func (BulkEntry) MarshalJSON ¶
MarshalJSON encodes the entry with the selectors next to "v", as the API does. Every selector is written as a JSON string, since Params cannot tell a numeric selector from an asset such as "1".
func (*BulkEntry) UnmarshalJSON ¶
UnmarshalJSON requires v and keeps every other field as a selector.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client calls the Glassnode API. Its configuration is immutable after construction and it is safe for concurrent use.
func NewClient ¶
NewClient constructs a client with header API-key authentication, a one-minute timeout per attempt and two GET retries. Configure exactly one of an API key, WithBearerToken or WithTokenSource. Explicit WithTimeout overrides a supplied HTTP client timeout regardless of option order; other options apply in order.
func (*Client) Get ¶
Get decodes a GET response into dst. Use a non-nil pointer (including *json.RawMessage). Dynamic values decode as json.Number rather than float64. Custom UnmarshalJSON methods allow application-specific validation.
The response is read completely, with retries, before anything is decoded, so dst is written to at most once, from a successful attempt. A failed request or invalid JSON leaves dst untouched; a type mismatch may leave it partially filled, as json.Unmarshal does.
func (*Client) GetAPIUsage ¶
GetAPIUsage fetches the current authenticated user's API usage.
func (*Client) GetBulkMetric ¶
func (c *Client) GetBulkMetric(ctx context.Context, path string, params *MetricParams) ([]BulkDataPoint, error)
GetBulkMetric fetches the bulk variant of a metric and unwraps the data envelope. Pass the base metric path, without a /bulk suffix. The API requires Since and limits the time range per request (31 days at 24h resolution). Each asset and selector combination is billed like a separate request, and omitting Assets selects every asset, so set the selectors explicitly.
func (*Client) GetMetric ¶
GetMetric decodes a metric response into dst. Use this for custom/nested shapes or lossless json.RawMessage; common shapes have convenience methods.
func (*Client) GetMetricCSV ¶
func (c *Client) GetMetricCSV(ctx context.Context, path string, params *MetricParams, w io.Writer) error
GetMetricCSV requests a metric in CSV and copies the response to w as it arrives, without decoding it. The columns are the API's: timestamp and value, the object keys for object metrics, plus computed_at for point-in-time metrics. Bulk metrics are not available in CSV.
Failures before any byte reaches w (transport errors, 429, 5xx, a connection lost right after the headers) are retried as usual. A failure after output has been written is not, since a retry would duplicate it; neither is a body over WithMaxResponseBytes. An error from w itself is returned wrapped, so errors.Is against it works, and is never retried.
The per-attempt timeout (one minute by default) covers reading the whole body. For a large download over a slow link, raise it with WithTimeout or disable it with WithTimeout(0) and bound the call with a context deadline; a timeout in mid-body is reported as a TransportError noting that partial output was written.
func (*Client) GetMetricMetadata ¶
func (c *Client) GetMetricMetadata(ctx context.Context, path string, params *MetricParams) (*MetricMetadata, error)
GetMetricMetadata describes a metric's selectors, variants and availability.
func (*Client) GetMetricStats ¶
func (c *Client) GetMetricStats(ctx context.Context, path string, params *MetricParams) (*MetricStats, error)
GetMetricStats fetches metric data-lag percentiles.
func (*Client) GetObjectTimeSeries ¶
func (c *Client) GetObjectTimeSeries(ctx context.Context, path string, params *MetricParams) ([]ObjectTimeSeriesPoint, error)
GetObjectTimeSeries fetches a metric whose o field is a numeric breakdown.
func (*Client) GetTimeSeries ¶
func (c *Client) GetTimeSeries(ctx context.Context, path string, params *MetricParams) ([]TimeSeriesPoint, error)
GetTimeSeries fetches a scalar metric with nullable values.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"time"
glassnode "github.com/glassnode/glassnode-api-go-client"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `[{"t":1700000000,"v":42000},{"t":1700086400,"v":null}]`)
}))
defer server.Close()
client, err := glassnode.NewClient("example-key", glassnode.WithBaseURL(server.URL))
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
points, err := client.GetTimeSeries(ctx, "market/price_usd_close", &glassnode.MetricParams{Asset: "BTC"})
if err != nil {
panic(err)
}
for _, point := range points {
if point.Value == nil {
fmt.Println("gap")
} else {
fmt.Printf("%.0f\n", *point.Value)
}
}
}
Output: 42000 gap
func (*Client) ListAssetBlockchains ¶
ListAssetBlockchains lists asset blockchains, optionally scoped by a CEL filter.
func (*Client) ListAssetCategories ¶
ListAssetCategories lists asset categories, optionally scoped by a CEL filter.
func (*Client) ListAssetTags ¶
ListAssetTags lists asset tags, optionally scoped by a CEL filter.
func (*Client) ListAssets ¶
ListAssets lists asset metadata, optionally scoped by a CEL filter.
func (*Client) ListExchanges ¶
ListExchanges lists the supported exchanges.
func (*Client) ListMetricTags ¶
ListMetricTags lists the available metric tags.
func (*Client) ListMetrics ¶
ListMetrics lists metric paths, optionally filtered by asset and other selectors.
func (*Client) ListMiners ¶
ListMiners lists the supported miners.
func (*Client) ListNetworks ¶
ListNetworks lists the supported networks.
type DecodeError ¶
DecodeError describes a response that does not match the destination Go type. It is never retried. SDK-generated messages redact credentials, including custom decoder errors. Unwrap exposes the original error for inspection.
func (*DecodeError) Error ¶
func (e *DecodeError) Error() string
func (*DecodeError) Unwrap ¶
func (e *DecodeError) Unwrap() error
type InputError ¶
type InputError struct{ Field, Message string }
InputError describes invalid configuration or arguments, before any request.
func (*InputError) Error ¶
func (e *InputError) Error() string
type LagPercentiles ¶
type LagPercentiles struct {
P50 *float64 `json:"p50,omitempty"`
P90 *float64 `json:"p90,omitempty"`
P95 *float64 `json:"p95,omitempty"`
P99 *float64 `json:"p99,omitempty"`
}
LagPercentiles are durations in the enclosing MetricLagEntry.Unit. Pointers distinguish missing percentiles from measurements of zero.
type MetricDescriptors ¶
type MetricDescriptors struct {
Name string `json:"name,omitempty"`
ShortName string `json:"short_name,omitempty"`
Group string `json:"group,omitempty"`
Tags []string `json:"tags,omitempty"`
Description map[string]string `json:"description,omitempty"`
DataSharingGroup string `json:"data_sharing_group,omitempty"`
}
MetricDescriptors contains human-readable metric descriptions.
type MetricLagEntry ¶
type MetricLagEntry struct {
Unit string `json:"unit"`
Window string `json:"window"`
Resolution map[string]LagPercentiles `json:"resolution"`
}
MetricLagEntry contains data lag over a measurement window by resolution.
type MetricMetadata ¶
type MetricMetadata struct {
Path string `json:"path,omitempty"`
Tier int `json:"tier,omitempty"`
IsPIT bool `json:"is_pit,omitempty"`
Parameters map[string][]string `json:"parameters"`
ParametersDefaults map[string][]string `json:"parameters_defaults,omitempty"`
Queried map[string]string `json:"queried,omitempty"`
Refs Refs `json:"refs,omitempty"`
BulkSupported bool `json:"bulk_supported"`
TimeRange *TimeRange `json:"timerange,omitempty"`
Modified int64 `json:"modified,omitempty"`
Descriptors *MetricDescriptors `json:"descriptors,omitempty"`
}
MetricMetadata describes a metric, its selectors and available variants.
func (*MetricMetadata) UnmarshalJSON ¶
func (m *MetricMetadata) UnmarshalJSON(data []byte) error
UnmarshalJSON accepts each parameters_defaults value either as a list, as the API currently returns it, or as a single string, as the API documentation describes it.
type MetricParams ¶
type MetricParams struct {
Asset string
Assets []string
Exchanges []string
Since time.Time
Until time.Time
Interval string
Currency string
Extra url.Values
}
MetricParams selects data or filters metadata. Zero fields are omitted. Asset is a convenience for one asset; Assets and Exchanges encode repeated query parameters (a=BTC&a=ETH). Do not set both Asset and Assets. Extra accepts additional documented selectors such as network, quote_symbol, bps, side, size, miner and maturity; it must not duplicate a typed field.
type MetricStats ¶
type MetricStats struct {
Lag []MetricLagEntry `json:"lag"`
}
MetricStats contains the API's lag statistics. Lag values are durations, not timestamps; use each entry's Unit when interpreting them.
type MetricVariant ¶
type MetricVariant struct {
Base *string `json:"base,omitempty"`
Bulk *string `json:"bulk,omitempty"`
PIT *string `json:"pit,omitempty"`
}
MetricVariant links the base, bulk and point-in-time metric paths.
type NameEntry ¶
type NameEntry struct {
Name string `json:"name"`
}
NameEntry is a single named value in a names response.
type NamesResponse ¶
type NamesResponse struct {
Data []NameEntry `json:"data"`
}
NamesResponse is the response of the metadata list endpoints (/v1/metadata/tags, /v1/metadata/assets/tags, ...): {"data":[{"name":"..."},...]}.
type ObjectTimeSeriesPoint ¶
type ObjectTimeSeriesPoint struct {
Timestamp int64 `json:"t"`
Object map[string]*float64 `json:"o"`
ComputedAt *int64 `json:"computed_at,omitempty"`
}
ObjectTimeSeriesPoint is an object metric point (OHLC or a breakdown). Object values are nullable; nested shapes can be decoded with GetMetric. ComputedAt is set for point-in-time metrics, as in TimeSeriesPoint.
func (*ObjectTimeSeriesPoint) UnmarshalJSON ¶
func (p *ObjectTimeSeriesPoint) UnmarshalJSON(data []byte) error
UnmarshalJSON requires the timestamp and object, tolerating new fields.
type Option ¶
Option configures a Client at construction time.
func WithAPIKeyInQuery ¶
func WithAPIKeyInQuery() Option
WithAPIKeyInQuery sends api_key in the URL instead of X-Api-Key. Prefer the default header authentication to keep credentials out of proxy/access logs.
func WithBaseURL ¶
WithBaseURL selects an API origin, optionally with a path prefix. Credentials, query strings and fragments are forbidden. HTTP is allowed for local testing.
func WithBearerToken ¶
WithBearerToken uses an existing OAuth access token. Pass an empty API key to NewClient. For refreshable tokens, use WithTokenSource instead.
func WithHTTPClient ¶
WithHTTPClient uses a copy of the supplied client's configuration. Its transport and jar remain shared. Redirects are always disabled to prevent credential forwarding. Configure the transport before sharing the client.
func WithMaxResponseBytes ¶
WithMaxResponseBytes rejects response bodies larger than limit with a ResponseTooLargeError instead of decoding them. The default, zero, is no limit, as the API's full-history responses can legitimately be large. Use it to bound memory where a failed call is preferable to an unbounded one.
func WithRetryPolicy ¶
func WithRetryPolicy(policy RetryPolicy) Option
WithRetryPolicy replaces the default two retries with full-jitter backoff from one second to 65 seconds, which covers the API's one-minute rate-limit window. Delays must be positive when enabled.
func WithTimeout ¶
WithTimeout sets the per-attempt HTTP timeout. Zero disables it. Use a context deadline to bound the entire operation, including all retries and waits. This overrides WithHTTPClient's timeout regardless of option order.
func WithTokenSource ¶
func WithTokenSource(source TokenSource) Option
WithTokenSource uses OAuth tokens supplied at request time. Pass an empty API key to NewClient. Each token is redacted from that call's error messages.
func WithUserAgent ¶
WithUserAgent identifies the calling application. The SDK's default is glassnode-api-go-client. A blank value or one containing control characters is rejected.
type Refs ¶
type Refs struct {
Docs string `json:"docs,omitempty"`
Studio string `json:"studio,omitempty"`
MetricVariant *MetricVariant `json:"metric_variant,omitempty"`
}
Refs links API documentation, Studio and related metric variants.
type ResponseTooLargeError ¶
ResponseTooLargeError reports a successful response whose body exceeds the WithMaxResponseBytes limit. It is a decision of the client's configuration, not a transport or decoding failure, and the call is not retried.
func (*ResponseTooLargeError) Error ¶
func (e *ResponseTooLargeError) Error() string
func (*ResponseTooLargeError) Unwrap ¶
func (e *ResponseTooLargeError) Unwrap() error
Unwrap returns ErrResponseTooLarge.
type RetryPolicy ¶
RetryPolicy controls GET retries. MaxRetries excludes the initial attempt. Retry-After is a minimum delay; a value above MaxDelay stops retries rather than retrying before the server permits it. Zero MaxRetries disables retries.
type TimeSeriesPoint ¶
type TimeSeriesPoint struct {
Timestamp int64 `json:"t"`
Value *float64 `json:"v"`
ComputedAt *int64 `json:"computed_at,omitempty"`
}
TimeSeriesPoint is a scalar metric point. Value is nil for a gap (JSON null). Timestamp is Unix seconds, not milliseconds. ComputedAt is the Unix time at which a point-in-time metric computed the value; it is nil for other metrics.
func (*TimeSeriesPoint) UnmarshalJSON ¶
func (p *TimeSeriesPoint) UnmarshalJSON(data []byte) error
UnmarshalJSON requires the timestamp and scalar value, tolerating new fields.
type TokenRefresher ¶
type TokenRefresher interface {
TokenSource
Refresh(ctx context.Context) (string, error)
}
TokenRefresher is a TokenSource that can replace a token the API rejected. When a request gets a 401, the client calls Refresh once and repeats the request with the new token if it differs from the rejected one; a second 401 is returned to the caller. Returning the same token means nothing newer exists, and the 401 is returned as is. Refresh errors and an empty or malformed token are reported as AuthError. Concurrent calls rejected with the same token share one Refresh.
type TokenSource ¶
TokenSource supplies an OAuth access token for each HTTP attempt. Implementations own refresh and storage, must honor ctx and must be safe for concurrent calls. Token-source errors are never retried. A 401 response is returned as is unless the source also implements TokenRefresher.
type TokenSourceFunc ¶
TokenSourceFunc adapts a function to TokenSource.
type TransportError ¶
TransportError describes a failure in transit. SDK-generated error messages include the credential-redacted cause. Unwrap retains the original cause. The cause may contain credentials and should not be logged indiscriminately.
func (*TransportError) Error ¶
func (e *TransportError) Error() string
func (*TransportError) Unwrap ¶
func (e *TransportError) Unwrap() error