nebula

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 21 Imported by: 0

README

Nebula Golang Client/SDK/Library

Nebula Golang Client/SDK/Library

CI Go Reference Version

Explore market conversations with Go. nebula-go is a client for the Nebula Public API: find an asset, follow changes in sentiment and attention, compare communities, explore prediction markets, or ask Nebula Agent to put the data into words.

If you're building a research dashboard, a monitoring job or an assistant, you can start with a single API key. Requests are ordinary Go structs, responses have concrete field types, and every call takes a context.Context. The SDK handles authentication, query encoding, response decoding and eligible retries.

The client covers all 41 operations in the pinned OpenAPI 1.0.2 contract. The core package uses the Go standard library. The optional x402 package connects the official payment client for applications that choose to pay per request.

Русская версия · API coverage · Pinned contract

Find your way around

Install

From your Go module:

go get github.com/tigusigalpa/nebula-go

Requires Go 1.24 or newer, including the module's x402 dependency graph. The SDK version declared in this source tree is 0.2.0. The core package does not import the payment adapter; the adapter's dependencies are still declared in the same module.

Make your API key available to your application. For a local session, set an environment variable:

# macOS / Linux
export NEBULA_API_KEY='your-api-key'
# Windows PowerShell
$env:NEBULA_API_KEY = 'your-api-key'

Keep the real key out of source control and browser code. For a web application, call Nebula from your Go backend and return the data your frontend needs. In deployment, a secret manager can supply the same value.

Start with an asset

Let's answer a small question first: “What does the recent conversation around NVIDIA look like?” Save this program as main.go and run go run . after setting your key. It makes two account-mode API calls, so normal API credits apply.

The first call finds the asset. The second uses the returned identifier and asset class to fetch a week of sentiment observations.

package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "time"

    nebula "github.com/tigusigalpa/nebula-go"
)

func main() {
    if err := run(); err != nil {
        log.Fatal(err)
    }
}

func run() error {
    client, err := nebula.New(os.Getenv("NEBULA_API_KEY"))
    if err != nil {
        return err
    }
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    assets, err := client.Lookup.ListAssets(ctx, &nebula.ListAssetsRequest{
        Query: nebula.StringPtr("NVIDIA"),
    })
    if err != nil {
        return err
    }
    if len(assets.Assets) == 0 {
        fmt.Println("No matching assets")
        return nil
    }
    first := assets.Assets[0]
    fmt.Printf("Using %s (%s, %s)\n", first.Name, first.AssetID, first.AssetClass)
    asset := nebula.AssetRef{ID: first.AssetID, Class: first.AssetClass}
    sentiment, err := client.Social.Sentiment(ctx, &nebula.SentimentRequest{
        Asset: &asset, Hours: nebula.IntPtr(168),
    })
    if err != nil {
        return err
    }
    fmt.Printf("Received %d observations\n", len(sentiment.Series))
    if len(sentiment.Series) > 0 {
        latest := sentiment.Series[len(sentiment.Series)-1]
        fmt.Printf("Latest signal: %.2f at %s\n",
            latest.SentimentSignal, latest.Timestamp.Format(time.RFC3339))
    }
    if remaining := sentiment.HTTPMetadata().CreditsRemaining; remaining != nil {
        fmt.Printf("Credits left: %d\n", *remaining)
    }
    return nil
}

This example uses the first match to keep the program short. In an application, let the user choose a result or resolve the intended asset once and retain its identifier and class. A display symbol alone may not identify the asset you mean, especially for crypto.

The sentiment signal is a decay-weighted bullish-minus-bearish measure. Positive values lean bullish; negative values lean bearish, and magnitude also depends on activity. Read it alongside the timestamps and post counts.

Unless shown as a complete function, the remaining Go snippets belong inside a function returning error and assume an initialized client and ctx. Add standard-library imports as needed. There are also compilable examples in the repository.

Choose a service

Services group related questions. Start with Lookup if you have a name but don't yet have an API identifier.

Service on client What you can ask for A place to start
Discovery Screen assets and subjects; find momentum and trending conversations Screener, TopTrending
Lookup Search, list assets, resolve people and topics ListAssets, Search
Social Sentiment, emotions, mindshare, related subjects and social momentum Sentiment, Mindshare
Forecasts Forecastable assets and 72-hour mindshare/sentiment forecasts ListAssets, Mindshare
MarketSentiment Calls and returns, conviction, fear/greed, price levels and social volume Calls, FearGreedIndex
MarketData Price history PriceHistory
Intelligence Calendar events, insights and attention CalendarEvents, Insights
Clusters Community profiles, comparisons, overlap, rotation and stances List, Comparison
Predictions Prediction markets, venue listings and outcome history ListMarkets, Market
Agent Complete or stream an OpenAI-compatible chat request CreateChatCompletion
Account Plan, rate limits and credit balance Get

The coverage matrix links each operation to its method, types, official documentation and fixture.

Configure the client

Create a client when your application starts and reuse it across goroutines. Give each call a context that reflects the lifetime of the work: for an HTTP handler, that will usually come from r.Context().

client, err := nebula.New(os.Getenv("NEBULA_API_KEY"),
    nebula.WithTimeout(45*time.Second),
    nebula.WithRetry(3, 500*time.Millisecond, 5*time.Second),
    nebula.WithLocale(nebula.LocaleRussian),
    nebula.WithAuthMode(nebula.AuthModeBearer),
)
if err != nil {
    return err
}

Use these options to adjust the defaults for your application:

Setting Default Option
API base nebula.BaseURL (/api/v1/public) WithBaseURL
Authentication X-API-Key WithAuthMode
Overall timeout per call 30 seconds WithTimeout
Eligible GET attempts 3 total, including the first WithRetry or WithRetryPolicy
Backoff 250 ms initial delay, 5 s cap, with jitter WithRetry or WithRetryPolicy
Locale Unset; uses the server default WithLocale
Locale transport X-Nebula-Locale header WithLocaleMode
User agent nebula-go/0.2.0 WithUserAgent
Debug logging Off WithLogger

Bearer mode sends Authorization: Bearer … instead of X-API-Key. JSON calls use Accept: application/json; Agent streams request text/event-stream.

WithTimeout covers all attempts, backoff and body reading for one call, including the full lifetime of a stream. A shorter context deadline or custom HTTP client timeout still wins. Zero keeps the default; negative durations are rejected. Raising only the context timeout will not extend the client's timeout, so configure both for a long Agent answer.

Bring your own HTTP client

Use WithHTTPClient to plug in your proxy, TLS settings or instrumentation. For example, if your application already owns an HTTP client, you can pass it alongside a standard Go logger:

httpClient := &http.Client{Timeout: 45 * time.Second}
client, err := nebula.New(os.Getenv("NEBULA_API_KEY"),
    nebula.WithHTTPClient(httpClient),
    nebula.WithTimeout(45*time.Second),
    nebula.WithUserAgent("market-monitor/1.0"),
    nebula.WithLogger(log.New(os.Stderr, "nebula ", log.LstdFlags)),
)
if err != nil {
    return err
}
fmt.Println("Client ready; x402 enabled:", client.X402())

The SDK copies HTTP client settings at construction; the transport and logger remain shared and must be safe for concurrent use. It blocks cross-origin redirects to protect credentials. WithBaseURL accepts the full API base, including any path prefix, so it also works with a gateway or local test server.

The debug logger records request methods and URLs with credential-like query fields redacted. Query text and asset identifiers can still appear, so choose log destinations and retention accordingly.

Choose a language

Locale controls generated text where the API supports localization. The global locale uses X-Nebula-Locale. Override it for one call without changing the shared client:

localized := nebula.WithRequestLocale(ctx, nebula.LocaleJapanese)
localized = nebula.WithRequestLocaleMode(localized, nebula.LocaleModeQuery)
answer, err := client.Agent.CreateChatCompletion(localized, &nebula.ChatCompletionRequest{
    Messages: []nebula.ChatMessage{
        {Role: nebula.ChatRoleUser, Content: "Summarize the recent NVIDIA conversation."},
    },
})
if err != nil {
    return err
}
for _, choice := range answer.Choices {
    if choice.Message != nil {
        fmt.Println(choice.Message.Content)
    }
}

WithLocaleMode(LocaleModeQuery) sets query transport globally. Locale is an extensible string type; constants cover Spanish, Italian, Turkish, Russian, Korean, Japanese and Chinese.

Build requests

Keep identifiers together

An asset and a subject are different kinds of lookup results. Use the selector that matches your result:

You want to query… Use…
One stock, commodity, index or crypto asset Asset: &nebula.AssetRef{ID: id, Class: class}
One person, account or topic Subject: &nebula.SubjectRef{ID: id}
All matching assets in one class ListAssetsRequest.AssetClass
Prediction markets associated with one class PredictionsRequest.AssetClass
Aggregate sentiment or momentum for one class SentimentRequest.AssetClass or SocialMomentumRequest.AssetClass

Keep the AssetID and AssetClass returned by lookup together. Classes are AssetClassEquity, AssetClassCommodity, AssetClassIndex and AssetClassCrypto. Use one selector at a time: an asset, a subject, or a standalone class filter where supported.

For a person or topic, search for subjects first and carry the returned ID into an analytics call:

results, err := client.Lookup.Search(ctx, &nebula.SearchRequest{
    Query: "artificial intelligence",
    Kind:  nebula.KindPtr(nebula.KindSubject),
})
if err != nil {
    return err
}
for _, result := range results.Results {
    if result.Kind != nebula.KindSubject || result.SubjectID == nil {
        continue
    }
    sentiment, err := client.Social.Sentiment(ctx, &nebula.SentimentRequest{
        Subject: &nebula.SubjectRef{ID: *result.SubjectID},
        Hours:   nebula.IntPtr(24),
    })
    if err != nil {
        return err
    }
    fmt.Printf("%s: %d observations\n", result.Name, len(sentiment.Series))
    break // Just the first usable result for this example.
}
Omitted values and explicit zeroes

Optional request fields use pointers so the API can distinguish “use your default” from “send this value”:

Request value What it means
Limit: nil Omit the parameter; let the server choose its default
Limit: nebula.IntPtr(25) Ask for 25 results
Offset: nebula.IntPtr(0) Explicitly start at the first result
Refresh: nebula.BoolPtr(false) Explicitly disable forecast refresh

Helpers include StringPtr, IntPtr, Int64Ptr, Float64Ptr, BoolPtr, TimePtr and pointers to typed constants such as AssetClassPtr. Explicit values still have to satisfy the endpoint's rules: Limit: IntPtr(0) is invalid for asset listings.

Required fields, selector conflicts, documented enums and numeric ranges are checked before the HTTP call. A ValidationError identifies the operation and field. You can pass nil for an all-optional request, such as Lookup.ListAssets(ctx, nil); operations requiring an asset or another identifier still require it.

Pagination

For paginated lists such as assets, subjects and prediction markets, use Limit, Offset and the response's HasMore. The SDK fetches one page per call, which lets your application control how much work and credit usage to allow.

Here is a bounded walk through up to three pages of equities:

const pageSize = 50
const maxPages = 3
for page := 0; page < maxPages; page++ {
    assets, err := client.Lookup.ListAssets(ctx, &nebula.ListAssetsRequest{
        AssetClass: nebula.AssetClassPtr(nebula.AssetClassEquity),
        Limit:      nebula.IntPtr(pageSize),
        Offset:     nebula.IntPtr(page * pageSize),
    })
    if err != nil {
        return err
    }
    for _, asset := range assets.Assets {
        fmt.Printf("%s: %s\n", asset.AssetID, asset.Name)
    }
    if !assets.HasMore || len(assets.Assets) == 0 {
        break
    }
}

Keep filters unchanged between pages. Page-size and offset limits differ by endpoint; use its request type and API coverage entry to find the relevant contract. A context deadline applies across the whole loop if you reuse the same context.

Arrays and time windows

Clusters: []string{"kols", "media"} becomes repeated clusters parameters. Calendar filters, insight filters and cluster asset-class lists use CSV. The SDK handles encoding.

Set Hours for a lookback window and Granularity for the requested bucket size where the operation exposes them. The available combinations depend on the endpoint. Calendar and insight date filters accept *time.Time; the SDK serializes them in UTC and preserves fractional seconds.

Read response data

Responses are typed all the way down to nested items and time-series points. Nullable scalar values use pointers, so you can distinguish an unavailable price from a real zero. For example:

prices, err := client.MarketData.PriceHistory(ctx, &nebula.PriceHistoryRequest{
    Asset:       &nebula.AssetRef{ID: "NVDA", Class: nebula.AssetClassEquity},
    Hours:       nebula.IntPtr(24),
    Granularity: nebula.GranularityPtr(nebula.Granularity1h),
})
if err != nil {
    return err
}
for _, point := range prices.Series {
    timestamp := point.Timestamp.UTC().Format(time.RFC3339)
    if point.PriceUSD == nil {
        fmt.Println(timestamp, "price unavailable")
        continue
    }
    fmt.Printf("%s: $%.2f\n", timestamp, *point.PriceUSD)
}

An empty slice is a valid result; check its length before taking the first or last item. A missing cohort or timeframe key in a map can also be normal. Avoid turning unavailable data into zero just to fill a chart.

The SDK returns API values without rounding or rescaling them. Format them when presenting them:

  • Shares and prediction prices use fractions from 0 to 1; 0.42 becomes 42% when multiplied by 100 for display.
  • Fields ending in _pct are already percentage points; 2.5 means 2.5%.
  • Sentiment post totals describe the trailing lookback. IntervalPosts and the other Interval… fields describe a single emitted bucket; summing overlapping trailing totals would count activity more than once.
  • Timestamps decode into time.Time, preserving fractional seconds. Use .UTC() or .In(location) explicitly when displaying them.

Every top-level response also has Raw, a decoded JSON object that retains fields added upstream before the SDK gains a typed field. Prefer typed fields for normal application code: numbers in Raw use Go's usual float64 JSON decoding, so large integers can lose precision there. The typed int64 fields preserve it.

Account limits and metadata

Use account data when you need the plan and balance. Use HTTP metadata when you want to understand the request you just made:

account, err := client.Account.Get(ctx)
if err != nil {
    return err
}
fmt.Println("Plan:", account.Plan)
if account.Credits != nil {
    fmt.Println("Spendable credits:", account.Credits.TotalRemaining)
}
fmt.Println("Request ID:", account.HTTPMetadata().RequestID)
if charged := account.HTTPMetadata().CreditsCharged; charged != nil {
    fmt.Println("Credits charged for this call:", *charged)
}

Every response provides HTTPMetadata(): status, headers, request ID, optional rate-limit and credit figures, retry delay and any payment receipt. Check pointers before dereferencing them; an absent header does not mean the balance or limit is zero. RateLimitReset is seconds until reset. Retry-After accepts seconds or an HTTP date.

Some JSON bodies have their own Metadata field for calculation details. HTTPMetadata() consistently accesses HTTP information; BaseResponse.Metadata remains available too. The request ID is useful when investigating an unexpected response. Decide what is safe to log before recording raw bodies or headers.

Failures and retries

Use errors.Is when deciding what your application should do and errors.As when you need details for diagnostics:

account, err := client.Account.Get(ctx)
if err != nil {
    switch {
    case errors.Is(err, nebula.ErrValidation):
        var validationErr *nebula.ValidationError
        if errors.As(err, &validationErr) {
            return fmt.Errorf("fix %s: %s: %w", validationErr.Field, validationErr.Msg, err)
        }
    case errors.Is(err, nebula.ErrUnauthorized):
        return fmt.Errorf("check NEBULA_API_KEY: %w", err)
    case errors.Is(err, nebula.ErrOutOfCredits):
        return fmt.Errorf("account credits exhausted: %w", err)
    case errors.Is(err, context.DeadlineExceeded):
        return fmt.Errorf("request deadline reached: %w", err)
    case errors.Is(err, context.Canceled):
        return err
    }
    var apiErr *nebula.APIError
    if errors.As(err, &apiErr) {
        fmt.Printf("HTTP %d; retry hint %s; request %s\n",
            apiErr.StatusCode, apiErr.RetryAfter, apiErr.Metadata.RequestID)
    }
    return err
}
fmt.Println(account.Plan)

Import the standard errors package for this example. APIError retains status, message, headers, metadata and up to 8 KiB of response body. A credit-related 402 preserves PlanRenewsAt and PurchasedCredits when supplied. TransportError wraps network failures; DecodeError reports invalid successful JSON responses. Wrapped errors preserve context cancellation.

What the SDK retries

Account-mode GETs retry on transient network errors and HTTP 429, 500, 502, 503 or 504. Delay priority: Retry-After, RateLimit-Reset, then exponential backoff with jitter. MaxDelay caps computed backoff including jitter; server hints may exceed it, bounded by the overall deadline. WithRetry(1, 0, 0) disables retries.

POST chat requests, x402 requests, other 4xx errors, decoding failures and failed body reads are never automatically retried by the SDK. If a call returns an error after eligible retries, your application receives the final failure. Adding another retry loop outside the SDK multiplies attempts, so choose a retry budget deliberately.

Forecasts

Start with Forecasts.ListAssets to discover forecast candidates. Then request a forecast for a selected asset and check its status before using the series:

forecast, err := client.Forecasts.Mindshare(ctx, &nebula.MindshareForecastRequest{
    Asset: &nebula.AssetRef{ID: "NVDA", Class: nebula.AssetClassEquity},
})
if err != nil {
    return err
}
if !forecast.IsForecastable() {
    if forecast.Reason != nil {
        fmt.Println("Forecast unavailable:", *forecast.Reason)
    }
    return nil
}
fmt.Println("Forecast points:", len(forecast.Series))

Both forecasts expose Status, Reason and IsForecastable(). A successful HTTP call can return status=not_forecastable; show the reason or an unavailable state rather than treating it as a network failure.

Refresh: BoolPtr(true) requests recomputation and can cost more credits. The pinned contract describes about 5 seconds for refresh and a cached fallback after 20 seconds; allow time for that behavior and check Refreshed. Use response credit metadata to observe charges. The forecast documentation describes the upstream pricing and limits.

Prediction markets

Search for a question, open its canonical market, then use the venue listing and outcome IDs if you need history. These IDs refer to different objects, so carry each one from its own response field:

markets, err := client.Predictions.ListMarkets(ctx, &nebula.PredictionsRequest{
    Query: nebula.StringPtr("NVIDIA"), Limit: nebula.IntPtr(10),
    AssetClass: nebula.AssetClassPtr(nebula.AssetClassEquity),
})
if err != nil {
    return err
}
if len(markets.Markets) == 0 {
    fmt.Println("No matching markets")
    return nil
}
market, err := client.Predictions.Market(ctx, &nebula.PredictionMarketRequest{
    MarketID: markets.Markets[0].ID,
})
if err != nil {
    return err
}
fmt.Println(market.Question)

Predictions.History takes both a listing ID and an outcome ID. Once you have a market from the detail call above, you can fetch the first listing's first outcome like this:

if len(market.Listings) == 0 || len(market.Listings[0].Outcomes) == 0 {
    fmt.Println("No outcome history to request")
    return nil
}
listing := market.Listings[0]
outcome := listing.Outcomes[0]
history, err := client.Predictions.History(ctx, &nebula.PredictionHistoryRequest{
    ListingID: listing.ID,
    OutcomeID: outcome.ID,
    Hours:     nebula.IntPtr(24),
})
if err != nil {
    return err
}
fmt.Printf("%s: %d observations\n", outcome.Label, len(history.Series))

Use Series for new history integrations; Points is a deprecated compatibility field. Venue listings retain their own quotes and resolution rules. Check ObservedAt for quote freshness and PriceBasis for what a price represents. Compare volume only when VolumeUnit matches: one venue can report dollars while another reports contracts.

Nebula Agent

Use the Agent when you want a written answer from Nebula. The service is stateless: your application owns the conversation and sends its full history each time. Start with a single user message:

request := &nebula.ChatCompletionRequest{
    Messages: []nebula.ChatMessage{
        {Role: nebula.ChatRoleUser, Content: "Summarize the recent NVIDIA conversation."},
    },
}
answer, err := client.Agent.CreateChatCompletion(ctx, request)
if err != nil {
    return err
}
for _, choice := range answer.Choices {
    if choice.Message != nil {
        fmt.Println(choice.Message.Content)
    }
}
if answer.Usage != nil {
    fmt.Println("Credits used:", answer.Usage.CreditsUsed)
}

To continue a conversation, append the returned assistant text and the next user message to your application's message history before making another call. Roles are system, developer, user and assistant; developer is interpreted as a server-side system instruction. Model is accepted for OpenAI compatibility and ignored by Nebula. Set ThinkingMode with ThinkingModePtr(ThinkingModeAuto) or ThinkingModePtr(ThinkingModeDeep) when needed.

Billing varies by usage, with a 10-credit minimum in the pinned contract. Inspect Usage when present. Chat POSTs are not automatically retried.

Stream an answer

For a UI that displays text as it arrives, pass the same request to StreamChatCompletion. Configure a timeout long enough for the answer before creating the client; the default 30 seconds covers the entire stream.

stream, err := client.Agent.StreamChatCompletion(ctx, request)
if err != nil {
    return err
}
defer stream.Close()
for chunk := range stream.Events() {
    for _, choice := range chunk.Choices {
        if choice.Delta != nil && choice.Delta.Content != nil {
            fmt.Print(*choice.Delta.Content)
        }
    }
}
if err := stream.Err(); err != nil {
    return err
}

Keep the defer stream.Close() even if you expect to read the whole answer: it also releases resources when your code leaves early. Cancel the context when the caller no longer needs the answer.

A closed events channel alone does not tell you whether generation completed successfully. Always check Err() after the loop: it reports malformed events, API error frames, cancellation and an unexpected end before [DONE]. Partial text may already have been displayed, so keep that state separate from a completed answer in your UI.

stream.Metadata() exposes HTTP headers. Usage-only, role and finish chunks may contain no text: check choices and pointers as above. The selected method determines streaming mode regardless of the compatibility Stream field.

x402: preview before authorizing spending

x402 can irreversibly spend real USDC on Base mainnet. API-key mode is the default. The payment client is opt-in and requires a per-payment cap and trusted recipient allowlist.

If you use an API key, you can skip this section. The adapter is for applications that explicitly choose wallet-based payment through Nebula's separate x402 API.

This preview needs no wallet or private key and does not sign a payment:

// Additional imports: "net/http" and "github.com/tigusigalpa/nebula-go/x402".
offer, err := x402.PreviewOffer(ctx, nil, http.MethodGet,
    nebula.X402BaseURL+"/assets?query=NVIDIA")
if err != nil {
    return err
}
fmt.Println("Resource:", offer.ResourceURL)
fmt.Println("Network:", offer.Network, "recipient:", offer.PayTo)
fmt.Println("Atomic USDC requested:", offer.Amount)

Pass nil or a plain, unpaid HTTP client to PreviewOffer; a payment-enabled client can itself authorize spending. Preview surfaces the first requirement and retains the full offer in Raw. It does not establish trust: verify recipients independently before adding them to SpendPolicy.AllowedRecipients.

To enable payment, supply your own x402.Signer and explicit SpendPolicy to x402.NewClient. MaxUSDCPerPayment is a decimal string with at most six decimal places; AllowedRecipients must be nonempty. This cap applies per payment, so repeated calls can spend more in total. The official client's spend controls remain enabled.

Before signing, the adapter checks x402 v2, the exact scheme, Base network, USDC asset, recipient, amount and requested resource URL. Production resources require HTTPS. All 37 eligible GETs use the separate x402 base; /account, /forecasts/mindshare, /forecasts/sentiment and chat are rejected locally. /forecasts/assets is eligible.

A lost signed response, failed signed body read, redirect or server error can return ErrPaymentUncertain. Inspect *nebula.PaymentUncertainError for the original URL, request ID and available Metadata.PaymentReceipt, then reconcile before trying again. Signed GETs also disable the standard Go transport's implicit replay after a connection failure. Tests never make live wallet payments.

Troubleshooting

What you see What to check next
New returns “empty API key” Check that the variable exists in the process running your app. A terminal, IDE and service can have different environments.
ErrValidation before a request Inspect ValidationError.Field and Msg. Check required identifiers, paired asset ID/class, conflicting selectors and endpoint ranges.
ErrUnauthorized / HTTP 401 Verify that the configured key is valid and that your gateway forwards the chosen authentication header.
ErrOutOfCredits / account HTTP 402 Inspect the account balance and any renewal information on APIError. Immediate retries will not restore credits.
ErrForbidden / HTTP 403 Read the API message. A requested history window may exceed the plan's allowance.
ErrRateLimited / HTTP 429 Reduce request concurrency and inspect retry metadata. The SDK may already have used its retry attempts.
context.DeadlineExceeded Check the SDK timeout, context deadline and custom HTTP client timeout. The earliest one ends the call.
Empty results or nil data fields Confirm the selected ID/class and time window. Treat unavailable data explicitly in your application.
not_forecastable Check Reason and use Forecasts.ListAssets to discover candidates. This is a normal forecast response.
A stream stops after showing some text Read stream.Err() and retain the distinction between a partial and completed answer.
ErrNotX402Eligible Use an account client for account details, the two forecast-generation endpoints and Agent chat.
ErrPaymentUncertain Reconcile the original signed request and any receipt before authorizing another payment.

When reporting a problem, include the SDK and Go versions, the method called, a minimal request with secrets removed, and the request ID if available. Use GitHub issues for reproducible bugs and the security policy for sensitive reports.

Development

The test suite runs without a Nebula key or wallet. It uses local HTTP servers, an in-memory transport and fixtures, so you can work on the SDK without making live API calls or payments.

Start with:

go test ./...
go vet ./...

For the broader checks used in development and CI:

go generate ./...
go test -race ./...
go run honnef.co/go/tools/cmd/staticcheck@latest ./...
go run golang.org/x/vuln/cmd/govulncheck@latest ./...
go mod tidy
go mod verify

The race detector needs a platform and C toolchain supported by Go. The analysis commands may download their tools; vulnerability checking also uses the vulnerability database. CI tests the Go 1.24 line and the stable release, and checks formatting, generated output and dependency consistency.

If you're looking for a particular part of the implementation:

Location What lives there
service_*.go, request_*.go, models_*.go Public methods, request parameters and typed responses
transport.go, stream.go HTTP execution, retries, decoding and Agent streaming
errors.go, metadata.go Error types and response headers
x402/ Opt-in payment adapter and its tests
resources/openapi/nebula-openapi.json Pinned upstream contract
testdata/ Response fixtures
request_contract_test.go, contract_test.go Contract checks through public service methods
tools/querygen/ Query-validation rule generator

The coverage guard connects all 41 operations to exercised service calls, docs, fixtures and x402 eligibility. Independent contract tests check 173 query parameters, the chat body and 750 response properties, including nullable fields, empty collections, large integers, fractional timestamps and unknown fields retained in Raw. These checks verify the pinned contract; they do not establish live API compatibility.

go generate rebuilds query-validation rules only. The original full request/response generator is not included; maintain models alongside the contract and fixtures. See Contributing for the update workflow and Changelog for changes between versions.

Contributing · Security · Changelog

Market data, sentiment, forecasts and Agent output are not investment advice.

License

MIT © Igor Sazonov · sovletig@gmail.com

Documentation

Overview

Package nebula is the Go SDK for the Nebula Public API (https://docs.hiddensystems.ai/nebula/). It covers all 41 operations of the account-authenticated API plus the separate opt-in x402 pay-per-request surface via the x402 adapter package.

client, err := nebula.New(os.Getenv("NEBULA_API_KEY"))
assets, err := client.Lookup.ListAssets(ctx, &nebula.ListAssetsRequest{
    Query: nebula.StringPtr("NVIDIA"),
})

All methods take a context.Context first. All responses carry typed data plus ResponseMetadata (rate limit and credits) via the embedded BaseResponse. Market data is not investment advice.

Index

Examples

Constants

View Source
const (
	ClusterSmartMoney      = "smart_money"
	ClusterDumbMoney       = "dumb_money"
	ClusterTopDegens       = "top_degens"
	ClusterEarlyMovers     = "early_movers"
	ClusterLateMovers      = "late_movers"
	ClusterDevelopers      = "developers"
	ClusterFounders        = "founders"
	ClusterTeamLeaders     = "team_leaders"
	ClusterProjectAccounts = "project_accounts"
	ClusterVCs             = "vcs"
	ClusterAssetManagers   = "asset_managers"
	ClusterDAOGuildFunds   = "dao_guild_funds"
	ClusterIncubators      = "incubators"
	ClusterExchanges       = "exchanges"
	ClusterKOLs            = "kols"
	ClusterCelebrities     = "celebrities"
	ClusterMedia           = "media"
	ClusterMarketer        = "marketer"
	ClusterShiller         = "shiller"
	ClusterTAAnalyst       = "ta_analyst"
	ClusterFAAnalyst       = "fa_analyst"
	ClusterMacroAnalyst    = "macro_analyst"
	ClusterOnchainAnalyst  = "onchain_analyst"
	ClusterInvestigators   = "investigators"
	ClusterPositionTrader  = "position_trader"
	ClusterSwingTrader     = "swing_trader"
	ClusterDayTrader       = "day_trader"
	ClusterPermaBull       = "perma_bull"
	ClusterDoomer          = "doomer"
	ClusterTribalist       = "tribalist"
	ClusterPolitical       = "political"
	ClusterNFT             = "nft"
	ClusterBots            = "bots"
	ClusterAutomatedAI     = "automated_ai"
	ClusterWallStreetBets  = "wallstreetbets"
	ClusterReddit          = "reddit"
)

Cluster IDs documented in the OpenAPI `clusters`/`cluster_id` descriptions. Cluster IDs are an extensible string type; these constants cover the catalog published in spec v1.0.2.

View Source
const BaseURL = "https://nebula-api.hiddensystems.ai/api/v1/public"

BaseURL is the account-authenticated API base.

View Source
const Version = "0.2.0"

Version is the SDK release.

View Source
const X402BaseURL = "https://nebula-api.hiddensystems.ai/api/v1/x402"

X402BaseURL is the pay-per-request x402 API base. Only the 37 x-x402-eligible GET operations are served there.

Variables

View Source
var (
	// ErrValidation marks client-side request validation failures raised
	// before any HTTP call (also matches *ValidationError).
	ErrValidation = errors.New("nebula: validation failed")
	// ErrTransport marks network/transport failures without an HTTP status.
	ErrTransport = errors.New("nebula: transport error")
	// ErrBadRequest maps HTTP 400.
	ErrBadRequest = errors.New("nebula: bad request")
	// ErrUnauthorized maps HTTP 401 (missing, invalid, or revoked API key).
	ErrUnauthorized = errors.New("nebula: unauthorized")
	// ErrOutOfCredits maps HTTP 402 (account credits used up).
	ErrOutOfCredits = errors.New("nebula: out of credits")
	// ErrForbidden maps HTTP 403 (history beyond the plan's window).
	ErrForbidden = errors.New("nebula: forbidden")
	// ErrNotFound maps HTTP 404.
	ErrNotFound = errors.New("nebula: not found")
	// ErrMethodNotAllowed maps HTTP 405.
	ErrMethodNotAllowed = errors.New("nebula: method not allowed")
	// ErrRateLimited maps HTTP 429.
	ErrRateLimited = errors.New("nebula: rate limited")
	// ErrServer maps HTTP 500.
	ErrServer = errors.New("nebula: internal server error")
	// ErrServiceUnavailable maps HTTP 503.
	ErrServiceUnavailable = errors.New("nebula: service unavailable")
	// ErrPaymentRequired maps x402 HTTP 402 payment offers and settlement
	// failures on the x402 surface.
	ErrPaymentRequired = errors.New("nebula: x402 payment required")
	// ErrPaymentUncertain marks a request whose payment may have settled but
	// whose response was lost (503 after signing, dropped connection).
	// Reconcile the original payment before authorizing another.
	ErrPaymentUncertain = errors.New("nebula: x402 payment state uncertain")
	// ErrNotX402Eligible marks calls to endpoints the x402 surface does not
	// serve (/account, both forecasts, /chat/completions).
	ErrNotX402Eligible = errors.New("nebula: operation not eligible for x402")
)

Sentinel errors classify failures for errors.Is. Every API error is also an *APIError for errors.As inspection.

Functions

func BoolPtr

func BoolPtr(v bool) *bool

BoolPtr returns a pointer to v for optional request fields.

func Float64Ptr

func Float64Ptr(v float64) *float64

Float64Ptr returns a pointer to v for optional request fields.

func Int64Ptr

func Int64Ptr(v int64) *int64

Int64Ptr returns a pointer to v for optional request fields.

func IntPtr

func IntPtr(v int) *int

IntPtr returns a pointer to v for optional request fields.

func IsCommunityCluster

func IsCommunityCluster(id string) bool

IsCommunityCluster reports whether id is a posting community (wallstreetbets, reddit) rather than an author cluster. Community data only exists for traditional asset classes, which the SDK validates locally.

func StringPtr

func StringPtr(v string) *string

StringPtr returns a pointer to v for optional request fields.

func TimePtr

func TimePtr(v time.Time) *time.Time

TimePtr returns a pointer to v for optional request fields.

func WithRequestLocale

func WithRequestLocale(ctx context.Context, l Locale) context.Context

WithRequestLocale returns a context that overrides the client's locale for one call, sent as X-Nebula-Locale (or ?locale= under LocaleModeQuery).

ctx := nebula.WithRequestLocale(ctx, nebula.LocaleRussian)
res, err := client.Social.Sentiment(ctx, req)

func WithRequestLocaleMode

func WithRequestLocaleMode(ctx context.Context, m LocaleMode) context.Context

WithRequestLocaleMode returns a context that overrides how the locale is transported for one call (header or query).

func X402Eligible

func X402Eligible(op string) bool

X402Eligible reports whether an operation id is served on the x402 surface. Exported for callers building eligibility UI or guards.

Types

type APIError

type APIError struct {
	// Op is the operation id, e.g. "list_assets".
	Op string
	// StatusCode is the HTTP status.
	StatusCode int
	// Message is the API's human-readable error message.
	Message string
	// Headers of the error response.
	Headers http.Header
	// Metadata parses rate-limit/credit/retry headers.
	Metadata ResponseMetadata
	// Body is the raw response body truncated to maxErrorBodyBytes.
	Body []byte
	// PlanRenewsAt is the UTC credit-renewal time reported on 402 bodies.
	PlanRenewsAt string
	// PurchasedCredits is the purchased-credit balance reported on 402 bodies.
	PurchasedCredits *int64
	// RetryAfter is the parsed Retry-After delay when present.
	RetryAfter time.Duration
}

APIError is an HTTP error response from the API. It keeps the status, the API message, headers, parsed metadata, and a bounded copy of the raw body.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is maps the status code onto the sentinel errors.

func (*APIError) PaymentOffer

func (e *APIError) PaymentOffer() bool

PaymentOffer reports whether the 402 carries a PAYMENT-REQUIRED x402 offer rather than an account out-of-credits error.

type AccountResponse

type AccountResponse struct {
	BaseResponse
	// The account's credit position this cycle; absent for keys that are not metered.
	Credits *AccountResponseCredits `json:"credits"`
	// How many days back the plan can read; null when unbounded.
	HistoryWindowDays *int `json:"history_window_days"`
	// The account's API plan, such as free or pro.
	Plan string `json:"plan"`
	// Requests allowed per minute; null when the key is not rate limited.
	RateLimitPerMinute *int `json:"rate_limit_per_minute"`
}

AccountResponse models an object of the `account` service.

type AccountResponseCredits

type AccountResponseCredits struct {
	// UTC end of the current credit cycle, when plan credits renew.
	CycleEnd time.Time `json:"cycle_end"`
	// UTC start of the current credit cycle.
	CycleStart time.Time `json:"cycle_start"`
	// Credits the plan includes this cycle.
	PlanCredits int64 `json:"plan_credits"`
	// Plan credits left this cycle.
	PlanCreditsRemaining int64 `json:"plan_credits_remaining"`
	// Plan credits spent this cycle.
	PlanCreditsUsed int64 `json:"plan_credits_used"`
	// Unexpired purchased credits left, spent after plan credits.
	PurchasedCreditsRemaining int64 `json:"purchased_credits_remaining"`
	// Everything left to spend: plan plus purchased credits.
	TotalRemaining int64 `json:"total_remaining"`
}

AccountResponseCredits models an object of the `account` service.

type AccountService

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

func (*AccountService) Get

Get - Account. GET /account Docs: https://docs.hiddensystems.ai/nebula/reference/get-account/

type AgentService

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

func (*AgentService) CreateChatCompletion

func (s *AgentService) CreateChatCompletion(ctx context.Context, req *ChatCompletionRequest) (*ChatCompletionResponse, error)

CreateChatCompletion - Nebula Agent chat completions. POST /chat/completions (non-streaming). Docs: https://docs.hiddensystems.ai/nebula/reference/post-chat-completions/

func (*AgentService) StreamChatCompletion

func (s *AgentService) StreamChatCompletion(ctx context.Context, req *ChatCompletionRequest) (*ChatStream, error)

StreamChatCompletion - Nebula Agent chat completions. POST /chat/completions with stream=true (SSE). Docs: https://docs.hiddensystems.ai/nebula/reference/post-chat-completions/

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	nebula "github.com/tigusigalpa/nebula-go"
)

func main() {
	client, err := nebula.New(os.Getenv("NEBULA_API_KEY"), nebula.WithTimeout(2*time.Minute))
	if err != nil {
		log.Fatal(err)
	}
	stream, err := client.Agent.StreamChatCompletion(context.Background(), &nebula.ChatCompletionRequest{Messages: []nebula.ChatMessage{{Role: nebula.ChatRoleUser, Content: "Summarize the recent NVIDIA conversation."}}})
	if err != nil {
		log.Fatal(err)
	}
	defer stream.Close()
	for chunk := range stream.Events() {
		for _, choice := range chunk.Choices {
			if choice.Delta != nil && choice.Delta.Content != nil {
				fmt.Print(*choice.Delta.Content)
			}
		}
	}
	if err := stream.Err(); err != nil {
		log.Print(err)
	}
}

type AssetClass

type AssetClass string

AssetClass is the class of a market asset.

const (
	AssetClassEquity    AssetClass = "equity"
	AssetClassCommodity AssetClass = "commodity"
	AssetClassIndex     AssetClass = "index"
	AssetClassCrypto    AssetClass = "crypto"
)

func AssetClassPtr

func AssetClassPtr(v AssetClass) *AssetClass

AssetClassPtr returns a pointer to v for optional request fields.

type AssetRef

type AssetRef struct {
	ID    string
	Class AssetClass
}

AssetRef selects one market asset: the pair (asset_id, asset_class) that /assets and /search return together. Carrying the pair in one value object makes it impossible to send a bare asset_id without its class.

type AuthMode

type AuthMode string

AuthMode selects how the API key is sent.

const (
	// AuthModeAPIKey sends X-API-Key: <key> (default).
	AuthModeAPIKey AuthMode = "api_key"
	// AuthModeBearer sends Authorization: Bearer <key>. Never combined with
	// X-API-Key unless the caller explicitly configures both.
	AuthModeBearer AuthMode = "bearer"
)

type BaseResponse

type BaseResponse struct {
	Metadata ResponseMetadata `json:"-"`
	// Raw keeps the decoded JSON object for forward-compatible access to
	// fields added upstream after this SDK release.
	Raw map[string]any `json:"-"`
}

BaseResponse is embedded in every typed response so transport metadata and the raw decoded body stay reachable without weakening the field types.

func (*BaseResponse) HTTPMetadata

func (b *BaseResponse) HTTPMetadata() ResponseMetadata

HTTPMetadata returns the HTTP context consistently, including for responses whose JSON body has its own Metadata field (such as Emotions).

type CalendarDomain

type CalendarDomain string

CalendarDomain is an event domain on the calendar endpoint.

const (
	CalendarDomainCrypto            CalendarDomain = "crypto"
	CalendarDomainEquities          CalendarDomain = "equities"
	CalendarDomainCommodities       CalendarDomain = "commodities"
	CalendarDomainMacro             CalendarDomain = "macro"
	CalendarDomainPolitics          CalendarDomain = "politics"
	CalendarDomainTechnology        CalendarDomain = "technology"
	CalendarDomainPredictionMarkets CalendarDomain = "prediction_markets"
)

type CalendarEventsRequest

type CalendarEventsRequest struct {
	Asset              *AssetRef
	Subject            *SubjectRef
	Limit              *int
	Offset             *int
	StartTimeAfter     *time.Time
	StartTimeBefore    *time.Time
	Domains            []CalendarDomain
	EventTypes         []EventType
	Statuses           []EventStatus
	MinImportanceScore *int
}

CalendarEventsRequest carries the query parameters of `list_calendar_events` (GET /calendar-events). Docs: https://docs.hiddensystems.ai/nebula/reference/get-calendar-events/

type CalendarEventsResponse

type CalendarEventsResponse struct {
	BaseResponse
	// Calendar events matching the supplied filters.
	CalendarEvents []CalendarEventsResponseCalendarEvent `json:"calendar_events"`
}

CalendarEventsResponse models an object of the `intelligence` service.

type CalendarEventsResponseCalendarEvent

type CalendarEventsResponseCalendarEvent struct {
	// Stable public identifier for the calendar event.
	CalendarEventID string `json:"calendar_event_id"`
	// Confidence in the event, from 1 (low) to 10 (high).
	ConfidenceScore int `json:"confidence_score"`
	// UTC time when the record was created.
	CreatedAt time.Time `json:"created_at"`
	// Market or subject domains attached to the record.
	Domains []string `json:"domains"`
	// UTC event end time when known.
	EndTime *time.Time `json:"end_time"`
	// Assets and non-asset subjects linked to this record.
	Entities []CalendarEventsResponseCalendarEventEntity `json:"entities"`
	// Event-type-specific structured metadata. Keys vary by event type.
	EventMetadata map[string]any `json:"event_metadata"`
	// More specific event classification when available.
	EventSubtype *string `json:"event_subtype"`
	// High-level event classification.
	EventType string `json:"event_type"`
	// Importance from 1 (low) to 3 (high).
	ImportanceScore int `json:"importance_score"`
	// Where the event physically takes place, when a place is known. Absent for online and on-chain events.
	Location *string `json:"location"`
	// Estimated long-term market impact, from 1 (low) to 3 (high).
	LongTermImpactScore int `json:"long_term_impact_score"`
	// Estimated macroeconomic impact, from 1 (low) to 3 (high).
	MacroImpactScore int `json:"macro_impact_score"`
	// Estimated direct price impact, from 1 (low) to 3 (high).
	PriceImpactScore int `json:"price_impact_score"`
	// Estimated short-term market impact, from 1 (low) to 3 (high).
	ShortTermImpactScore int `json:"short_term_impact_score"`
	// Number of sources supporting the event.
	SourceCount int `json:"source_count"`
	// Source records supporting the parent response.
	Sources []CalendarEventsResponseCalendarEventSource `json:"sources"`
	// UTC time when the intelligence item or event starts.
	StartTime time.Time `json:"start_time"`
	// Current lifecycle status of the event: scheduled, tentative, cancelled, or postponed.
	Status string `json:"status"`
	// Evidence-grounded summary of the intelligence item.
	Summary *string `json:"summary"`
	// Searchable labels attached to the record.
	Tags []string `json:"tags"`
	// Estimated tail-risk impact, from 1 (low) to 3 (high).
	TailRiskImpactScore int `json:"tail_risk_impact_score"`
	// Precision of the published event time: minute, hour, day, week, month, year, or unknown. A day-precision event starts at 00:00 UTC that day.
	TimePrecision string `json:"time_precision"`
	// Human-readable event title.
	Title string `json:"title"`
	// Number of supporting sources marked trusted.
	TrustedSourceCount int `json:"trusted_source_count"`
	// UTC time when the record was last updated.
	UpdatedAt time.Time `json:"updated_at"`
}

CalendarEventsResponseCalendarEvent models an object of the `intelligence` service.

type CalendarEventsResponseCalendarEventEntity

type CalendarEventsResponseCalendarEventEntity struct {
	// The asset's class, sent with asset_id.
	AssetClass *AssetClass `json:"asset_class"`
	// For a stock, commodity, index, or coin, the asset_id the asset endpoints take; absent for people, accounts, and topics, and for the rare asset Nebula cannot place.
	AssetID *string `json:"asset_id"`
	// Entity-link confidence when available.
	Confidence *float64 `json:"confidence"`
	// Nebula's id for the linked entity, such as eq:NVDA, gecko:1, or text:ai. To query the entity, use asset_id and asset_class, or subject_id, from the same object.
	EntityID string `json:"entity_id"`
	// True when this is the record's primary linked entity.
	IsPrimary bool `json:"is_primary"`
	// Human-readable name.
	Name string `json:"name"`
	// Relationship of the linked entity to the calendar event.
	Role string `json:"role"`
	// For a person, account, or topic, the subject_id the subject-aware endpoints take; absent for assets.
	SubjectID *string `json:"subject_id"`
}

CalendarEventsResponseCalendarEventEntity models an object of the `intelligence` service.

type CalendarEventsResponseCalendarEventEventMetadata

type CalendarEventsResponseCalendarEventEventMetadata struct {
}

CalendarEventsResponseCalendarEventEventMetadata models an object of the `intelligence` service.

type CalendarEventsResponseCalendarEventSource

type CalendarEventsResponseCalendarEventSource struct {
	// Identifier assigned by the external source.
	ExternalID string `json:"external_id"`
	// Upstream data provider when available.
	Provider *PredictionProvider `json:"provider"`
	// UTC publication time.
	PublishedAt time.Time `json:"published_at"`
	// Original publisher when available.
	Publisher *string `json:"publisher"`
	// Source platform or feed.
	Source string `json:"source"`
	// Source subtype.
	Subtype string `json:"subtype"`
	// Whether the source is classified as trusted.
	Trusted bool `json:"trusted"`
	// Public source URL when available.
	URL *string `json:"url"`
}

CalendarEventsResponseCalendarEventSource models an object of the `intelligence` service.

type CallReturnsRequest

type CallReturnsRequest struct {
	Asset        *AssetRef
	ResolvedDays *int
	Clusters     []string
}

CallReturnsRequest carries the query parameters of `get_call_returns` (GET /calls/returns). Docs: https://docs.hiddensystems.ai/nebula/reference/get-calls-returns/

type CallReturnsResponse

type CallReturnsResponse struct {
	BaseResponse
	// Mean direction-aligned return across resolved calls, in percentage points.
	AverageReturnPct float64 `json:"average_return_pct"`
	// Return-distribution buckets in ascending order.
	Buckets []CallReturnsResponseBucket `json:"buckets"`
	// Resolved calls with a negative direction-aligned return.
	Losses int64 `json:"losses"`
	// Median direction-aligned return across resolved calls, in percentage points.
	MedianReturnPct float64 `json:"median_return_pct"`
	// Number of calls with a resolved outcome.
	ResolvedCalls int64 `json:"resolved_calls"`
	// How many days of resolved calls the statistics include.
	ResolvedDays int `json:"resolved_days"`
	// Winning resolved calls as a percentage from 0 to 100.
	WinRatePct float64 `json:"win_rate_pct"`
	// Resolved calls with a positive direction-aligned return.
	Wins int64 `json:"wins"`
}

CallReturnsResponse models an object of the `market sentiment` service.

type CallReturnsResponseBucket

type CallReturnsResponseBucket struct {
	// Resolved calls in this return bucket.
	CallCount int64 `json:"call_count"`
	// Sum of direction-aligned returns with each call capped at ±100%, in percentage points.
	CappedTotalAlignedReturnPct float64 `json:"capped_total_aligned_return_pct"`
	// Human-readable bucket or index label.
	Label string `json:"label"`
	// Inclusive lower return bound in percentage points; null for the first, open-ended bucket.
	LowerBoundPct *float64 `json:"lower_bound_pct"`
	// Sum of direction-aligned returns in this bucket, in percentage points.
	TotalAlignedReturnPct float64 `json:"total_aligned_return_pct"`
	// Exclusive upper return bound in percentage points; null for the last, open-ended bucket.
	UpperBoundPct *float64 `json:"upper_bound_pct"`
}

CallReturnsResponseBucket models an object of the `market sentiment` service.

type CallsRequest

type CallsRequest struct {
	Asset    *AssetRef
	Hours    *int
	Clusters []string
}

CallsRequest carries the query parameters of `get_calls` (GET /calls). Docs: https://docs.hiddensystems.ai/nebula/reference/get-calls/

type CallsResponse

type CallsResponse struct {
	BaseResponse
	// Chronologically ordered observations.
	Series []CallsResponseSeriesPoint `json:"series"`
}

CallsResponse models an object of the `market sentiment` service.

type CallsResponseSeriesPoint

type CallsResponseSeriesPoint struct {
	// Number of long calls in the bucket.
	LongCalls int64 `json:"long_calls"`
	// Number of short calls in the bucket.
	ShortCalls int64 `json:"short_calls"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp string `json:"timestamp"`
}

CallsResponseSeriesPoint models an object of the `market sentiment` service.

type ChatCompletionRequest

type ChatCompletionRequest struct {
	// Messages is the complete conversation history; at least one message is
	// required and the Agent is stateless, so resend the full history each call.
	Messages []ChatMessage
	// Model is accepted for OpenAI compatibility and ignored by Nebula.
	Model *string
	// ThinkingMode selects the reasoning mode: auto or deep.
	ThinkingMode *ThinkingMode
	// Stream requests server-sent events. Callers normally leave this nil and
	// pick Agent.CreateChatCompletion or Agent.StreamChatCompletion instead.
	Stream *bool
}

ChatCompletionRequest is the OpenAI-compatible Nebula Agent request body of `create_chat_completion` (POST /chat/completions). Docs: https://docs.hiddensystems.ai/nebula/reference/post-chat-completions/

type ChatCompletionResponse

type ChatCompletionResponse struct {
	BaseResponse
	// Generated completion choices.
	Choices []ChatCompletionResponseChoice `json:"choices"`
	// Unix timestamp when the completion was created.
	Created int64 `json:"created"`
	// Unique identifier assigned to the chat completion.
	ID string `json:"id"`
	// Nebula agent model identifier.
	Model string `json:"model"`
	// OpenAI-compatible object type.
	Object string `json:"object"`
	// Credits consumed by this completion.
	Usage *ChatCompletionResponseUsage `json:"usage"`
}

ChatCompletionResponse models an object of the `agent` service.

type ChatCompletionResponseChoice

type ChatCompletionResponseChoice struct {
	// Streaming message fragment.
	Delta *ChatCompletionResponseChoiceDelta `json:"delta"`
	// Reason generation stopped when available.
	FinishReason *string `json:"finish_reason"`
	// Zero-based index of the generated completion choice.
	Index int `json:"index"`
	// Completed assistant message for a non-streaming response.
	Message *ChatCompletionResponseChoiceMessage `json:"message"`
}

ChatCompletionResponseChoice models an object of the `agent` service.

type ChatCompletionResponseChoiceDelta

type ChatCompletionResponseChoiceDelta struct {
	// Partial assistant response text in this stream fragment.
	Content *string `json:"content"`
	// Conversation role when emitted in this stream fragment.
	Role *string `json:"role"`
}

ChatCompletionResponseChoiceDelta models an object of the `agent` service.

type ChatCompletionResponseChoiceMessage

type ChatCompletionResponseChoiceMessage struct {
	// Completed assistant response text.
	Content string `json:"content"`
	// Conversation role of the completed message.
	Role string `json:"role"`
}

ChatCompletionResponseChoiceMessage models an object of the `agent` service.

type ChatCompletionResponseUsage

type ChatCompletionResponseUsage struct {
	// Nebula credits consumed by the request.
	CreditsUsed int64 `json:"credits_used"`
}

ChatCompletionResponseUsage models an object of the `agent` service.

type ChatMessage

type ChatMessage struct {
	Role    ChatRole `json:"role"`
	Content string   `json:"content"`
}

ChatMessage is one OpenAI-style conversation message.

type ChatRole

type ChatRole string

ChatRole is the role of an agent conversation message. "developer" is OpenAI's newer name for system instructions and is treated as system.

const (
	ChatRoleSystem    ChatRole = "system"
	ChatRoleDeveloper ChatRole = "developer"
	ChatRoleUser      ChatRole = "user"
	ChatRoleAssistant ChatRole = "assistant"
)

type ChatStream

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

ChatStream is a closeable server-sent-events stream of chat completion chunks. Read events from Events() until the channel closes, then check Err(). Always call Close (or cancel the context) to release the body.

stream, err := client.Agent.StreamChatCompletion(ctx, req)
if err != nil { return err }
defer stream.Close()
for chunk := range stream.Events() {
    for _, choice := range chunk.Choices {
        if d := choice.Delta; d != nil && d.Content != nil { fmt.Print(*d.Content) }
    }
}
if err := stream.Err(); err != nil { return err }

func (*ChatStream) Close

func (s *ChatStream) Close() error

Close releases the stream body and stops the reader goroutine.

func (*ChatStream) Err

func (s *ChatStream) Err() error

Err returns the terminal error, if any, after Events() closed.

func (*ChatStream) Events

func (s *ChatStream) Events() <-chan *ChatCompletionResponse

Events yields decoded chat completion chunks; the channel closes on [DONE], on stream error, or after Close/context cancellation.

func (*ChatStream) Metadata

func (s *ChatStream) Metadata() ResponseMetadata

Metadata returns the HTTP metadata of the stream's response headers.

type Client

type Client struct {
	Discovery       *DiscoveryService
	Lookup          *LookupService
	Social          *SocialService
	Forecasts       *ForecastsService
	MarketSentiment *MarketSentimentService
	MarketData      *MarketDataService
	Intelligence    *IntelligenceService
	Clusters        *ClustersService
	Agent           *AgentService
	Account         *AccountService
	Predictions     *PredictionsService
	// contains filtered or unexported fields
}

Client is the Nebula API client. Create it with New; it is immutable after construction and safe for concurrent use across goroutines.

Example

Examples without an Output directive are compiled but never call the live API during go test. Set NEBULA_API_KEY when adapting them into your application.

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	nebula "github.com/tigusigalpa/nebula-go"
)

func main() {
	client, err := nebula.New(os.Getenv("NEBULA_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	assets, err := client.Lookup.ListAssets(ctx, &nebula.ListAssetsRequest{Query: nebula.StringPtr("NVIDIA")})
	if err != nil {
		log.Fatal(err)
	}
	if len(assets.Assets) == 0 {
		return
	}
	first := assets.Assets[0]
	asset := nebula.AssetRef{ID: first.AssetID, Class: first.AssetClass}
	sentiment, err := client.Social.Sentiment(ctx, &nebula.SentimentRequest{Asset: &asset, Hours: nebula.IntPtr(168)})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(len(sentiment.Series))
	if remaining := sentiment.HTTPMetadata().CreditsRemaining; remaining != nil {
		fmt.Println(*remaining)
	}
}

func New

func New(apiKey string, opts ...Option) (*Client, error)

New creates an account-mode Client authenticated by apiKey. The key must come from a secure source (env var, secret store); it is sent as X-API-Key unless WithAuthMode selects the Bearer form.

func NewX402Client

func NewX402Client(httpClient *http.Client, opts ...Option) (*Client, error)

NewX402Client builds a client pinned to the x402 surface (/api/v1/x402) without an API key. It is used by the x402 adapter package with a payment-wrapped *http.Client; non-eligible operations (/account, forecasts, chat completions) fail locally before any HTTP call.

func (*Client) X402

func (c *Client) X402() bool

X402 reports whether the client is bound to the x402 surface.

type ClusterHypeCyclesRequest

type ClusterHypeCyclesRequest struct {
	ClusterID    string
	AssetClasses []AssetClass
	Days         *int
}

ClusterHypeCyclesRequest carries the query parameters of `get_cluster_hype_cycles` (GET /clusters/hype-cycles). Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-hype-cycles/

type ClusterHypeCyclesResponse

type ClusterHypeCyclesResponse struct {
	BaseResponse
	// The markets analysed, in the order equity, commodity, index, crypto: the asset_class values requested, or all four when asset_class was omitted.
	AssetClasses []string `json:"asset_classes"`
	// The cluster analysed, as its canonical cluster_id.
	ClusterID string `json:"cluster_id"`
	// Every cluster with a lead (5 or more cycles), earliest first, the requested one included.
	Clusters []ClusterHypeCyclesResponseCluster `json:"clusters"`
	// The average cumulative build-up, one point per day_offset from −7 to +7; empty when no cycle has completed.
	Curve []ClusterHypeCyclesResponseCurveItem `json:"curve"`
	// Completed hype cycles the cluster joined: 3 or more posts within 7 days of the peak.
	CyclesJoined int `json:"cycles_joined"`
	// Window length in complete UTC days, ending at the latest complete day.
	Days int `json:"days"`
	// How far ahead of everyone else the cluster's posts arrive within 24 hours of the market's peak hour, in days. Positive is early; null under 20 cycles.
	LeadDays *float64 `json:"lead_days"`
}

ClusterHypeCyclesResponse models an object of the `clusters` service.

type ClusterHypeCyclesResponseCluster

type ClusterHypeCyclesResponseCluster struct {
	// The cluster, as its canonical cluster_id.
	ClusterID string `json:"cluster_id"`
	// Completed hype cycles in which the cluster posted within 24 hours of the market's peak hour.
	CyclesJoined int `json:"cycles_joined"`
	// The cluster's lead in days, computed as the top-level lead_days. Positive is early.
	LeadDays float64 `json:"lead_days"`
	// High end of the likely range of lead_days.
	LeadHighDays float64 `json:"lead_high_days"`
	// Low end of the likely range of lead_days.
	LeadLowDays float64 `json:"lead_low_days"`
}

ClusterHypeCyclesResponseCluster models an object of the `clusters` service.

type ClusterHypeCyclesResponseCurveItem

type ClusterHypeCyclesResponseCurveItem struct {
	// Percentage of the cluster's posts in the 15 days around the peak made by the end of this day, averaged over cycles; 100 at day_offset 7.
	ClusterCumulativePct float64 `json:"cluster_cumulative_pct"`
	// Days from the market peak: negative before it, 0 on the peak day, positive after it.
	DayOffset int `json:"day_offset"`
	// The same for the market, over the same cycles.
	MarketCumulativePct float64 `json:"market_cumulative_pct"`
}

ClusterHypeCyclesResponseCurveItem models an object of the `clusters` service.

type ClusterOverlapRequest

type ClusterOverlapRequest struct {
	ClusterID    string
	AssetClasses []AssetClass
	Days         *int
}

ClusterOverlapRequest carries the query parameters of `get_cluster_overlap` (GET /clusters/overlap). Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-overlap/

type ClusterOverlapResponse

type ClusterOverlapResponse struct {
	BaseResponse
	// The markets analysed, in the order equity, commodity, index, crypto: the asset_class values requested, or all four when asset_class was omitted.
	AssetClasses []string `json:"asset_classes"`
	// The cluster analysed, as its canonical cluster_id.
	ClusterID string `json:"cluster_id"`
	// Window length in complete UTC days, ending at the latest complete day.
	Days int `json:"days"`
	// Every other active cluster, most-overlapping first.
	Peers []ClusterOverlapResponsePeer `json:"peers"`
	// Size of each cluster's focus set: its most-discussed assets, up to this many.
	TopAssetCount int `json:"top_asset_count"`
}

ClusterOverlapResponse models an object of the `clusters` service.

type ClusterOverlapResponsePeer

type ClusterOverlapResponsePeer struct {
	// Compared assets on which both clusters lean the same way relative to the market.
	AgreeingAssetCount int `json:"agreeing_asset_count"`
	// Canonical author-cluster identifier.
	ClusterID string `json:"cluster_id"`
	// Shared assets, across the whole overlap, on which both clusters lean at least 0.05 from the market's stance.
	ComparedAssetCount int `json:"compared_asset_count"`
	// On shared assets where both clusters lean at least 0.05 from the market's stance, the share where they lean the same way: agreeing_asset_count ÷ compared_asset_count. Null under 3
	DirectionAgreementShare *float64 `json:"direction_agreement_share"`
	// Share of this cluster's focus set also in the peer's, from 0 to 1.
	OverlapShare float64 `json:"overlap_share"`
	// Up to 5 assets in both focus sets, in this cluster's order of attention.
	SharedAssets []ClusterOverlapResponsePeerSharedAsset `json:"shared_assets"`
	// This cluster's stance minus the peer's, averaged over shared assets both have a stance on, from −2 to +2. Positive means this cluster is more bullish. Null under 3 assets.
	StanceGap *float64 `json:"stance_gap"`
}

ClusterOverlapResponsePeer models an object of the `clusters` service.

type ClusterOverlapResponsePeerSharedAsset

type ClusterOverlapResponsePeerSharedAsset struct {
	// The asset's class: equity (stocks and ETFs), commodity, index, or crypto. Send it with asset_id on every asset-scoped request.
	AssetClass AssetClass `json:"asset_class"`
	// Canonical public asset identifier: the ticker or market symbol for stocks, commodities, and indices, and the CoinGecko slug (or, without one, a numeric id) for crypto.
	AssetID string `json:"asset_id"`
	// This cluster's net stance on the asset, from −1 to +1. Null under 3 bullish or bearish posts.
	ClusterStance *float64 `json:"cluster_stance"`
	// The market's net stance on the asset, from −1 to +1: the baseline both leans are measured against. Null under 3 bullish or bearish posts.
	MarketStance *float64 `json:"market_stance"`
	// Human-readable name.
	Name string `json:"name"`
	// The peer's net stance on the asset, from −1 to +1. Null under 3 bullish or bearish posts.
	PeerStance *float64 `json:"peer_stance"`
	// Display ticker or market symbol.
	Symbol string `json:"symbol"`
}

ClusterOverlapResponsePeerSharedAsset models an object of the `clusters` service.

type ClusterProfileRequest

type ClusterProfileRequest struct {
	ClusterID    string
	AssetClasses []AssetClass
	Days         *int
}

ClusterProfileRequest carries the query parameters of `get_cluster_profile` (GET /clusters/profile). Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-profile/

type ClusterProfileResponse

type ClusterProfileResponse struct {
	BaseResponse
	// Clusters active in the window: the population traits are ranked within.
	ActiveClusters int `json:"active_clusters"`
	// The markets analysed, in the order equity, commodity, index, crypto: the asset_class values requested, or all four when asset_class was omitted.
	AssetClasses []string `json:"asset_classes"`
	// The cluster analysed, as its canonical cluster_id.
	ClusterID string `json:"cluster_id"`
	// Window length in complete UTC days, ending at the latest complete day.
	Days int `json:"days"`
	// Market hype cycles in the window: assets whose posts peaked at 50 or more in a day and at least 3× their median day.
	HypeCycles int `json:"hype_cycles"`
	// One entry per trait, in the order earliness, contrarian, hype_fade, conviction, focus, breadth, bullishness, discovery, turnover, coverage.
	Traits []ClusterProfileResponseTrait `json:"traits"`
}

ClusterProfileResponse models an object of the `clusters` service.

type ClusterProfileResponseTrait

type ClusterProfileResponseTrait struct {
	// Every other cluster's value for this trait, ascending.
	PeerValues []float64 `json:"peer_values"`
	// From 0 (lowest) to 1 (highest) among clusters with a value. Null when value is null.
	Percentile *float64 `json:"percentile"`
	// 1 is the highest value; tied clusters share the better rank. Null when value is null.
	Rank *int `json:"rank"`
	// The trait measured; the operation description defines each one.
	Trait string `json:"trait"`
	// days, share (0 to 1) or count; fixed per trait.
	Unit string `json:"unit"`
	// The cluster's value for this trait, in unit; null when the cluster has too little data for it.
	Value *float64 `json:"value"`
}

ClusterProfileResponseTrait models an object of the `clusters` service.

type ClusterRotationRequest

type ClusterRotationRequest struct {
	ClusterID    string
	AssetClasses []AssetClass
	Hours        *int
	Limit        *int
}

ClusterRotationRequest carries the query parameters of `get_cluster_rotation` (GET /clusters/rotation). Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-rotation/

type ClusterRotationResponse

type ClusterRotationResponse struct {
	BaseResponse
	// The markets analysed, in the order equity, commodity, index, crypto: the asset_class values requested, or all four when asset_class was omitted.
	AssetClasses []string `json:"asset_classes"`
	// The cluster analysed, as its canonical cluster_id.
	ClusterID string `json:"cluster_id"`
	// Assets whose share of the cluster's posts rose most, largest gain first. Only assets whose share rose are listed.
	Gainers []ClusterRotationResponseGainer `json:"gainers"`
	// Lookback window represented by the response, in hours.
	Hours int `json:"hours"`
	// Assets whose share of the cluster's posts fell most, largest fall first. Only assets whose share fell are listed.
	Losers []ClusterRotationResponseGainer `json:"losers"`
	// Each topic's share of the current window and its change against the previous one, in the order equity, commodity, index, crypto, people, events.
	TopicChanges []ClusterRotationResponseTopicChange `json:"topic_changes"`
	// Each topic's share of the cluster's posts per complete UTC day, oldest first.
	TopicSeries []ClusterRotationResponseTopicSeriesPoint `json:"topic_series"`
}

ClusterRotationResponse models an object of the `clusters` service.

type ClusterRotationResponseGainer

type ClusterRotationResponseGainer struct {
	// The asset's class: equity (stocks and ETFs), commodity, index, or crypto. Send it with asset_id on every asset-scoped request.
	AssetClass AssetClass `json:"asset_class"`
	// Canonical public asset identifier: the ticker or market symbol for stocks, commodities, and indices, and the CoinGecko slug (or, without one, a numeric id) for crypto.
	AssetID string `json:"asset_id"`
	// Posts as a fraction of all the cluster's posts about the selected asset classes in the current window, from 0 to 1.
	CurrentShare float64 `json:"current_share"`
	// Human-readable name.
	Name string `json:"name"`
	// The asset's posts as a fraction of all the cluster's posts in the comparison window, from 0 to 1.
	PreviousShare float64 `json:"previous_share"`
	// current_share minus the share in the comparison window, in basis points: 100 is one percentage point. Negative means the share fell.
	ShareChangeBps int `json:"share_change_bps"`
	// Display ticker or market symbol.
	Symbol string `json:"symbol"`
}

ClusterRotationResponseGainer models an object of the `clusters` service.

type ClusterRotationResponseTopicChange

type ClusterRotationResponseTopicChange struct {
	// The topic's share of the cluster's posts in the current window, from 0 to 1.
	CurrentShare float64 `json:"current_share"`
	// Change in share against the previous window, in basis points (100 is one percentage point).
	ShareChangeBps int `json:"share_change_bps"`
	// equity, commodity, index, crypto, people (people and their accounts) or events (places, themes and events).
	Topic string `json:"topic"`
}

ClusterRotationResponseTopicChange models an object of the `clusters` service.

type ClusterRotationResponseTopicSeriesPoint

type ClusterRotationResponseTopicSeriesPoint struct {
	// UTC start of the day: 00:00.
	Timestamp time.Time `json:"timestamp"`
	// Each topic's share of the cluster's posts that day, in the order of topic_changes. The shares add up to 1 when the cluster posted that day.
	Topics []ClusterRotationResponseTopicSeriesPointTopic `json:"topics"`
}

ClusterRotationResponseTopicSeriesPoint models an object of the `clusters` service.

type ClusterRotationResponseTopicSeriesPointTopic

type ClusterRotationResponseTopicSeriesPointTopic struct {
	// equity, commodity, index, crypto, people (people and their accounts) or events (places, themes and events).
	Topic string `json:"topic"`
	// The topic's share of the cluster's posts that day, from 0 to 1.
	TopicShare float64 `json:"topic_share"`
}

ClusterRotationResponseTopicSeriesPointTopic models an object of the `clusters` service.

type ClusterStancesRequest

type ClusterStancesRequest struct {
	ClusterID    string
	AssetClasses []AssetClass
	Days         *int
	Limit        *int
}

ClusterStancesRequest carries the query parameters of `get_cluster_stances` (GET /clusters/stances). Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-stances/

type ClusterStancesResponse

type ClusterStancesResponse struct {
	BaseResponse
	// The markets analysed, in the order equity, commodity, index, crypto: the asset_class values requested, or all four when asset_class was omitted.
	AssetClasses []string `json:"asset_classes"`
	// The cluster's most-discussed eligible assets (3 or more cluster posts, 20 or more market posts), up to limit.
	Assets []ClusterStancesResponseAsset `json:"assets"`
	// The cluster analysed, as its canonical cluster_id.
	ClusterID string `json:"cluster_id"`
	// Share of eligible assets on which the cluster and the market lean opposite ways, both at least 0.1 from neutral. Null under 5 assets.
	ContrarianShare *float64 `json:"contrarian_share"`
	// Window length in complete UTC days, ending at the latest complete day.
	Days int `json:"days"`
	// contrarian_share averaged over the other clusters; null when none has one.
	PeerAverageContrarianShare *float64 `json:"peer_average_contrarian_share"`
}

ClusterStancesResponse models an object of the `clusters` service.

type ClusterStancesResponseAsset

type ClusterStancesResponseAsset struct {
	// The asset's class: equity (stocks and ETFs), commodity, index, or crypto. Send it with asset_id on every asset-scoped request.
	AssetClass AssetClass `json:"asset_class"`
	// Canonical public asset identifier: the ticker or market symbol for stocks, commodities, and indices, and the CoinGecko slug (or, without one, a numeric id) for crypto.
	AssetID string `json:"asset_id"`
	// The cluster's posts about the asset over the window.
	ClusterPosts int64 `json:"cluster_posts"`
	// The cluster's net stance on the asset over the window: (bullish − bearish) / (bullish + bearish) posts, from −1 (all bearish) to +1 (all bullish).
	ClusterStance float64 `json:"cluster_stance"`
	// The market's net stance on the same asset over the same window, on the same −1 to +1 scale, from every author except bots.
	MarketStance float64 `json:"market_stance"`
	// Human-readable name.
	Name string `json:"name"`
	// Display ticker or market symbol.
	Symbol string `json:"symbol"`
}

ClusterStancesResponseAsset models an object of the `clusters` service.

type ClustersComparisonRequest

type ClustersComparisonRequest struct {
	AssetClasses []AssetClass
	Days         *int
}

ClustersComparisonRequest carries the query parameters of `compare_clusters` (GET /clusters/comparison). Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-comparison/

type ClustersComparisonResponse

type ClustersComparisonResponse struct {
	BaseResponse
	// The markets analysed, in the order equity, commodity, index, crypto: the asset_class values requested, or all four when asset_class was omitted.
	AssetClasses []string `json:"asset_classes"`
	// Every cluster with posts in the window, most posts first.
	Clusters []ClustersComparisonResponseCluster `json:"clusters"`
	// Window length in complete UTC days, ending at the latest complete day.
	Days int `json:"days"`
}

ClustersComparisonResponse models an object of the `clusters` service.

type ClustersComparisonResponseCluster

type ClustersComparisonResponseCluster struct {
	// Percent change in posts against the previous window of equal length (76 posts after 84 is -9.52); absent when no comparison is possible.
	ActivityChangePct *float64 `json:"activity_change_pct"`
	// The cluster's bearish posts over the window.
	BearishPosts int64 `json:"bearish_posts"`
	// The cluster's bullish posts over the window.
	BullishPosts int64 `json:"bullish_posts"`
	// The cluster's bullish ÷ (bullish + bearish) posts over the window, from 0 to 1. Null with no bullish or bearish posts.
	ClusterBullishShare *float64 `json:"cluster_bullish_share"`
	// Canonical author-cluster identifier.
	ClusterID string `json:"cluster_id"`
	// The same share for the market the cluster reads, over the same days and asset classes (the equity market for a posting community): the baseline cluster_bullish_share compares with.
	MarketBullishShare *float64 `json:"market_bullish_share"`
	// The cluster's posts over the window.
	Posts int64 `json:"posts"`
	// Every complete UTC day of the window, oldest first, days without posts included.
	Series []ClustersComparisonResponseClusterSeriesPoint `json:"series"`
	// The asset the cluster turned to more than the market did over the last 7 complete days; null when there is none.
	TrendingAsset *ClustersComparisonResponseClusterTrendingAsset `json:"trending_asset"`
}

ClustersComparisonResponseCluster models an object of the `clusters` service.

type ClustersComparisonResponseClusterSeriesPoint

type ClustersComparisonResponseClusterSeriesPoint struct {
	// The cluster's bearish posts on the day.
	BearishPosts int64 `json:"bearish_posts"`
	// The cluster's bullish posts on the day.
	BullishPosts int64 `json:"bullish_posts"`
	// The cluster's posts on the day.
	Posts int64 `json:"posts"`
	// UTC start of the day: 00:00.
	Timestamp time.Time `json:"timestamp"`
}

ClustersComparisonResponseClusterSeriesPoint models an object of the `clusters` service.

type ClustersComparisonResponseClusterTrendingAsset

type ClustersComparisonResponseClusterTrendingAsset struct {
	// The asset's class: equity (stocks and ETFs), commodity, index, or crypto. Send it with asset_id on every asset-scoped request.
	AssetClass AssetClass `json:"asset_class"`
	// Canonical public asset identifier: the ticker or market symbol for stocks, commodities, and indices, and the CoinGecko slug (or, without one, a numeric id) for crypto.
	AssetID string `json:"asset_id"`
	// Human-readable name.
	Name string `json:"name"`
	// Display ticker or market symbol.
	Symbol string `json:"symbol"`
}

ClustersComparisonResponseClusterTrendingAsset models an object of the `clusters` service.

type ClustersRequest

type ClustersRequest struct {
	AssetClass *AssetClass
	Hours      *int
}

ClustersRequest carries the query parameters of `list_clusters` (GET /clusters). Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters/

type ClustersResponse

type ClustersResponse struct {
	BaseResponse
	// Author-cluster summaries for the selected asset class.
	Clusters []ClustersResponseCluster `json:"clusters"`
	// Lookback window represented by the response, in hours.
	Hours int `json:"hours"`
}

ClustersResponse models an object of the `clusters` service.

type ClustersResponseCluster

type ClustersResponseCluster struct {
	// Percent change in posts against the previous window of equal length (76 posts after 84 is -9.52); absent when no comparison is possible.
	ActivityChangePct *float64 `json:"activity_change_pct"`
	// Posts classified as bearish.
	BearishPosts float64 `json:"bearish_posts"`
	// Posts classified as bullish.
	BullishPosts float64 `json:"bullish_posts"`
	// Canonical author-cluster identifier.
	ClusterID string `json:"cluster_id"`
	// Posts classified as neutral.
	NeutralPosts float64 `json:"neutral_posts"`
	// Post count in the immediately preceding window of equal length.
	PreviousTotalPosts float64 `json:"previous_total_posts"`
	// The latest value of the hourly sentiment series: the most recent hour with posts.
	RecentSentimentSignal float64 `json:"recent_sentiment_signal"`
	// Chronologically ordered observations.
	Series []ClustersResponseClusterSeriesPoint `json:"series"`
	// Post count over the metric's active lookback window.
	TotalPosts float64 `json:"total_posts"`
	// Net bullish sentiment signal over the complete requested window.
	WindowSentimentSignal float64 `json:"window_sentiment_signal"`
}

ClustersResponseCluster models an object of the `clusters` service.

type ClustersResponseClusterSeriesPoint

type ClustersResponseClusterSeriesPoint struct {
	// Posts classified as bearish.
	BearishPosts float64 `json:"bearish_posts"`
	// Posts classified as bullish.
	BullishPosts float64 `json:"bullish_posts"`
	// Decay-weighted net bullish posts: bullish minus bearish. Positive is bullish, negative is bearish, and magnitude grows with activity.
	SentimentSignal float64 `json:"sentiment_signal"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
	// Post count over the metric's active lookback window.
	TotalPosts float64 `json:"total_posts"`
}

ClustersResponseClusterSeriesPoint models an object of the `clusters` service.

type ClustersService

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

func (*ClustersService) Comparison

Comparison - Cluster comparison. GET /clusters/comparison Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-comparison/

func (*ClustersService) ComparisonHypeCycles

ComparisonHypeCycles - Hype cycle arrivals. GET /clusters/comparison/hype-cycles Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-comparison-hype-cycles/

func (*ClustersService) ComparisonTraits

ComparisonTraits - Cluster trait comparison. GET /clusters/comparison/traits Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-comparison-traits/

func (*ClustersService) DivisiveAssets

DivisiveAssets - Divisive assets. GET /clusters/comparison/divisive-assets Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-comparison-divisive-assets/

func (*ClustersService) HypeCycles

HypeCycles - Cluster hype cycles. GET /clusters/hype-cycles Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-hype-cycles/

func (*ClustersService) List

List - Author clusters. GET /clusters Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters/

func (*ClustersService) Overlap

Overlap - Cluster overlap. GET /clusters/overlap Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-overlap/

func (*ClustersService) Profile

Profile - Cluster profile. GET /clusters/profile Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-profile/

func (*ClustersService) Rotation

Rotation - Cluster rotation. GET /clusters/rotation Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-rotation/

func (*ClustersService) Stances

Stances - Cluster stances. GET /clusters/stances Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-stances/

type ComparisonHypeCyclesRequest

type ComparisonHypeCyclesRequest struct {
	AssetClasses []AssetClass
	Days         *int
	Limit        *int
}

ComparisonHypeCyclesRequest carries the query parameters of `compare_hype_cycles` (GET /clusters/comparison/hype-cycles). Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-comparison-hype-cycles/

type ComparisonHypeCyclesResponse

type ComparisonHypeCyclesResponse struct {
	BaseResponse
	// The markets analysed, in the order equity, commodity, index, crypto: the asset_class values requested, or all four when asset_class was omitted.
	AssetClasses []string `json:"asset_classes"`
	// The window's biggest hype cycles, most recent peak first, up to limit.
	Cycles []ComparisonHypeCyclesResponseCycle `json:"cycles"`
	// Window length in complete UTC days, ending at the latest complete day.
	Days int `json:"days"`
}

ComparisonHypeCyclesResponse models an object of the `clusters` service.

type ComparisonHypeCyclesResponseCycle

type ComparisonHypeCyclesResponseCycle struct {
	// Every cluster with 3 or more posts in the 48 hours around the peak hour, earliest first.
	Arrivals []ComparisonHypeCyclesResponseCycleArrival `json:"arrivals"`
	// The asset's class: equity (stocks and ETFs), commodity, index, or crypto. Send it with asset_id on every asset-scoped request.
	AssetClass AssetClass `json:"asset_class"`
	// Canonical public asset identifier: the ticker or market symbol for stocks, commodities, and indices, and the CoinGecko slug (or, without one, a numeric id) for crypto.
	AssetID string `json:"asset_id"`
	// Human-readable name.
	Name string `json:"name"`
	// The market's posts on the asset on the peak day, bots left out.
	PeakDayPosts int64 `json:"peak_day_posts"`
	// UTC start of the market's busiest hour on the peak day.
	PeakTimestamp time.Time `json:"peak_timestamp"`
	// The market's posts on the asset hour by hour, from 24 hours before the peak hour to 23 hours after it: 48 observations.
	Series []ComparisonHypeCyclesResponseCycleSeriesPoint `json:"series"`
	// Display ticker or market symbol.
	Symbol string `json:"symbol"`
}

ComparisonHypeCyclesResponseCycle models an object of the `clusters` service.

type ComparisonHypeCyclesResponseCycleArrival

type ComparisonHypeCyclesResponseCycleArrival struct {
	// Canonical author-cluster identifier.
	ClusterID string `json:"cluster_id"`
	// Hours from the market's peak hour to the posts-weighted average hour of the cluster's posts in the 48 hours around it. Negative is before the peak.
	OffsetHours float64 `json:"offset_hours"`
	// The cluster's posts on the asset in the 48 hours around the peak hour.
	Posts int64 `json:"posts"`
}

ComparisonHypeCyclesResponseCycleArrival models an object of the `clusters` service.

type ComparisonHypeCyclesResponseCycleSeriesPoint

type ComparisonHypeCyclesResponseCycleSeriesPoint struct {
	// The market's posts on the asset in the hour, bots left out.
	Posts int `json:"posts"`
	// UTC start of the hour.
	Timestamp time.Time `json:"timestamp"`
}

ComparisonHypeCyclesResponseCycleSeriesPoint models an object of the `clusters` service.

type ComparisonTraitsRequest

type ComparisonTraitsRequest struct {
	AssetClasses []AssetClass
	Days         *int
}

ComparisonTraitsRequest carries the query parameters of `compare_cluster_traits` (GET /clusters/comparison/traits). Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-comparison-traits/

type ComparisonTraitsResponse

type ComparisonTraitsResponse struct {
	BaseResponse
	// Clusters active in the window: the population traits are ranked within.
	ActiveClusters int `json:"active_clusters"`
	// The markets analysed, in the order equity, commodity, index, crypto: the asset_class values requested, or all four when asset_class was omitted.
	AssetClasses []string `json:"asset_classes"`
	// Window length in complete UTC days, ending at the latest complete day.
	Days int `json:"days"`
	// Market hype cycles in the window: assets whose posts peaked at 50 or more in a day and at least 3× their median day.
	HypeCycles int `json:"hype_cycles"`
	// One entry per trait, in the order earliness, contrarian, hype_fade, conviction, focus, breadth, bullishness, discovery, turnover, coverage.
	Traits []ComparisonTraitsResponseTrait `json:"traits"`
}

ComparisonTraitsResponse models an object of the `clusters` service.

type ComparisonTraitsResponseTrait

type ComparisonTraitsResponseTrait struct {
	// Every cluster with a value for the trait, highest first.
	Clusters []ComparisonTraitsResponseTraitCluster `json:"clusters"`
	// The trait measured; the operation description defines each one.
	Trait string `json:"trait"`
	// days, share (0 to 1) or count; fixed per trait.
	Unit string `json:"unit"`
}

ComparisonTraitsResponseTrait models an object of the `clusters` service.

type ComparisonTraitsResponseTraitCluster

type ComparisonTraitsResponseTraitCluster struct {
	// Canonical author-cluster identifier.
	ClusterID string `json:"cluster_id"`
	// The cluster's value for the trait, in unit.
	Value float64 `json:"value"`
}

ComparisonTraitsResponseTraitCluster models an object of the `clusters` service.

type ConvictionIndexRequest

type ConvictionIndexRequest struct {
	Asset       *AssetRef
	Hours       *int
	Granularity *Granularity
}

ConvictionIndexRequest carries the query parameters of `get_conviction_index` (GET /conviction-index). Docs: https://docs.hiddensystems.ai/nebula/reference/get-conviction-index/

type ConvictionIndexResponse

type ConvictionIndexResponse struct {
	BaseResponse
	// Chronologically ordered observations.
	Series []ConvictionIndexResponseSeriesPoint `json:"series"`
}

ConvictionIndexResponse models an object of the `market sentiment` service.

type ConvictionIndexResponseSeriesPoint

type ConvictionIndexResponseSeriesPoint struct {
	// Nebula index value on a 0–100 scale.
	Index float64 `json:"index"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
}

ConvictionIndexResponseSeriesPoint models an object of the `market sentiment` service.

type DecodeError

type DecodeError struct {
	Op  string
	Err error
}

DecodeError means a successful HTTP response did not contain the expected JSON.

func (*DecodeError) Error

func (e *DecodeError) Error() string

func (*DecodeError) Unwrap

func (e *DecodeError) Unwrap() error

type DiscoveryService

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

Service group structs.

func (*DiscoveryService) Screener

Screener - Screener. GET /screener Docs: https://docs.hiddensystems.ai/nebula/reference/get-screener/

func (*DiscoveryService) TopMomentum

TopMomentum - Top momentum. GET /top-momentum Docs: https://docs.hiddensystems.ai/nebula/reference/get-top-momentum/

func (*DiscoveryService) TopTrending

TopTrending - Top trending. GET /top-trending Docs: https://docs.hiddensystems.ai/nebula/reference/get-top-trending/

type DivisiveAssetsRequest

type DivisiveAssetsRequest struct {
	AssetClasses []AssetClass
	Days         *int
	Limit        *int
}

DivisiveAssetsRequest carries the query parameters of `get_divisive_assets` (GET /clusters/comparison/divisive-assets). Docs: https://docs.hiddensystems.ai/nebula/reference/get-clusters-comparison-divisive-assets/

type DivisiveAssetsResponse

type DivisiveAssetsResponse struct {
	BaseResponse
	// The markets analysed, in the order equity, commodity, index, crypto: the asset_class values requested, or all four when asset_class was omitted.
	AssetClasses []string `json:"asset_classes"`
	// The divisive assets, most evenly split first, up to limit.
	Assets []DivisiveAssetsResponseAsset `json:"assets"`
	// Window length in complete UTC days, ending at the latest complete day.
	Days int `json:"days"`
}

DivisiveAssetsResponse models an object of the `clusters` service.

type DivisiveAssetsResponseAsset

type DivisiveAssetsResponseAsset struct {
	// The asset's class: equity (stocks and ETFs), commodity, index, or crypto. Send it with asset_id on every asset-scoped request.
	AssetClass AssetClass `json:"asset_class"`
	// Canonical public asset identifier: the ticker or market symbol for stocks, commodities, and indices, and the CoinGecko slug (or, without one, a numeric id) for crypto.
	AssetID string `json:"asset_id"`
	// Clusters leaning bearish on the asset by 0.1 or more.
	BearishClusterCount int `json:"bearish_cluster_count"`
	// Clusters leaning bullish on the asset by 0.1 or more.
	BullishClusterCount int `json:"bullish_cluster_count"`
	// Every cluster with a stance on the asset (8 or more bullish or bearish posts), most bearish first.
	ClusterStances []DivisiveAssetsResponseAssetClusterStance `json:"cluster_stances"`
	// The market's net stance on the same asset over the same window, on the same −1 to +1 scale, from every author except bots.
	MarketStance float64 `json:"market_stance"`
	// The smaller side's share of the clusters leaning clearly bullish or bearish (0.1 or more either way), from 0 (all one way) to 0.5 (an even split). Assets are ranked by it.
	MinorityShare float64 `json:"minority_share"`
	// Human-readable name.
	Name string `json:"name"`
	// The interquartile range of the clusters' stances, from 0 to 2: how far apart the middle half of the clusters sit. Breaks ties in minority_share.
	StanceIqr float64 `json:"stance_iqr"`
	// Display ticker or market symbol.
	Symbol string `json:"symbol"`
}

DivisiveAssetsResponseAsset models an object of the `clusters` service.

type DivisiveAssetsResponseAssetClusterStance

type DivisiveAssetsResponseAssetClusterStance struct {
	// Canonical author-cluster identifier.
	ClusterID string `json:"cluster_id"`
	// The cluster's posts on the asset over the window.
	Posts int64 `json:"posts"`
	// The cluster's net stance on the asset: (bullish − bearish) ÷ (bullish + bearish) posts, from −1 to +1.
	Stance float64 `json:"stance"`
}

DivisiveAssetsResponseAssetClusterStance models an object of the `clusters` service.

type EmotionsRequest

type EmotionsRequest struct {
	Asset       *AssetRef
	Subject     *SubjectRef
	Hours       *int
	Granularity *Granularity
}

EmotionsRequest carries the query parameters of `get_emotions` (GET /emotions). Docs: https://docs.hiddensystems.ai/nebula/reference/get-emotions/

type EmotionsResponse

type EmotionsResponse struct {
	BaseResponse
	// Methodology and request-window metadata needed to interpret the response.
	Metadata *EmotionsResponseMetadata `json:"metadata"`
	// Emotion observations keyed by the detected emotion label.
	Series map[string][]EmotionsResponseSeriesEntry `json:"series"`
}

EmotionsResponse models an object of the `social` service.

type EmotionsResponseMetadata

type EmotionsResponseMetadata struct {
	// How clients should interpret buckets omitted or emitted without data.
	EmptyBucketPolicy string `json:"empty_bucket_policy"`
	// Number of buckets with no qualifying data.
	EmptyBuckets int `json:"empty_buckets"`
	// Time bucket size used by the returned series.
	Granularity Granularity `json:"granularity"`
	// Lookback window represented by the response, in hours.
	Hours int `json:"hours"`
	// Most recent UTC bucket with no qualifying data.
	LatestEmptyBucket *time.Time `json:"latest_empty_bucket"`
}

EmotionsResponseMetadata models an object of the `social` service.

type EmotionsResponseSeries

type EmotionsResponseSeries struct {
}

EmotionsResponseSeries models an object of the `social` service.

type EmotionsResponseSeriesEntry

type EmotionsResponseSeriesEntry struct {
	// Raw number of posts carrying this emotion in the bucket.
	PostCount int64 `json:"post_count"`
	// This emotion's share of all emotion tags in the bucket, from 0 to 1.
	Proportion float64 `json:"proportion"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
}

EmotionsResponseSeriesEntry models an object of the `social` service.

type EventStatus

type EventStatus string

EventStatus is a calendar event lifecycle state.

const (
	EventStatusScheduled EventStatus = "scheduled"
	EventStatusTentative EventStatus = "tentative"
	EventStatusCancelled EventStatus = "cancelled"
	EventStatusPostponed EventStatus = "postponed"
)

type EventType

type EventType string

EventType is a calendar event classification. See the OpenAPI spec for the full set; the constants below enumerate every value documented in v1.0.2.

const (
	EventTypeEarnings                   EventType = "earnings"
	EventTypeGuidance                   EventType = "guidance"
	EventTypeInvestorDay                EventType = "investor_day"
	EventTypeShareholderMeeting         EventType = "shareholder_meeting"
	EventTypeDividend                   EventType = "dividend"
	EventTypeStockSplit                 EventType = "stock_split"
	EventTypeBuyback                    EventType = "buyback"
	EventTypeSpinOff                    EventType = "spin_off"
	EventTypeAcquisition                EventType = "acquisition"
	EventTypeFundraising                EventType = "fundraising"
	EventTypeBankruptcy                 EventType = "bankruptcy"
	EventTypeLayoffs                    EventType = "layoffs"
	EventTypePartnership                EventType = "partnership"
	EventTypeAppointment                EventType = "appointment"
	EventTypePricingChange              EventType = "pricing_change"
	EventTypeClinicalTrial              EventType = "clinical_trial"
	EventTypeCorporateAction            EventType = "corporate_action"
	EventTypeIPO                        EventType = "ipo"
	EventTypeListing                    EventType = "listing"
	EventTypeDelisting                  EventType = "delisting"
	EventTypeIndexRebalance             EventType = "index_rebalance"
	EventTypeContractExpiry             EventType = "contract_expiry"
	EventTypeMarketHoliday              EventType = "market_holiday"
	EventTypeETF                        EventType = "etf"
	EventTypeEconomicRelease            EventType = "economic_release"
	EventTypeMonetaryPolicy             EventType = "monetary_policy"
	EventTypeCentralBankSpeech          EventType = "central_bank_speech"
	EventTypeBudget                     EventType = "budget"
	EventTypeDebtAuction                EventType = "debt_auction"
	EventTypeTradePolicy                EventType = "trade_policy"
	EventTypeSanctions                  EventType = "sanctions"
	EventTypeElection                   EventType = "election"
	EventTypeReferendum                 EventType = "referendum"
	EventTypeVote                       EventType = "vote"
	EventTypeHearing                    EventType = "hearing"
	EventTypeSummit                     EventType = "summit"
	EventTypeTreaty                     EventType = "treaty"
	EventTypePolicyDeadline             EventType = "policy_deadline"
	EventTypeRegulatoryDecision         EventType = "regulatory_decision"
	EventTypeRegulatoryDeadline         EventType = "regulatory_deadline"
	EventTypeFilingDeadline             EventType = "filing_deadline"
	EventTypeCourtRuling                EventType = "court_ruling"
	EventTypeLegal                      EventType = "legal"
	EventTypeUnlock                     EventType = "unlock"
	EventTypeBurn                       EventType = "burn"
	EventTypeMigration                  EventType = "migration"
	EventTypeSnapshot                   EventType = "snapshot"
	EventTypeAirdrop                    EventType = "airdrop"
	EventTypeTokenSale                  EventType = "token_sale"
	EventTypeStaking                    EventType = "staking"
	EventTypeHalving                    EventType = "halving"
	EventTypeMainnet                    EventType = "mainnet"
	EventTypeTestnet                    EventType = "testnet"
	EventTypeFork                       EventType = "fork"
	EventTypeUpgrade                    EventType = "upgrade"
	EventTypeGovernance                 EventType = "governance"
	EventTypeLaunch                     EventType = "launch"
	EventTypeConference                 EventType = "conference"
	EventTypeHackathon                  EventType = "hackathon"
	EventTypeAMA                        EventType = "ama"
	EventTypeCompetition                EventType = "competition"
	EventTypePredictionMarketResolution EventType = "prediction_market_resolution"
	EventTypeDeadline                   EventType = "deadline"
	EventTypeSports                     EventType = "sports"
	EventTypeOther                      EventType = "other"
)

type FearGreedIndexRequest

type FearGreedIndexRequest struct {
	Asset       *AssetRef
	Hours       *int
	Granularity *Granularity
}

FearGreedIndexRequest carries the query parameters of `get_fear_greed_index` (GET /fear-greed-index). Docs: https://docs.hiddensystems.ai/nebula/reference/get-fear-greed-index/

type FearGreedIndexResponse

type FearGreedIndexResponse struct {
	BaseResponse
	// Most recent value for each returned series or the current index reading.
	Current *FearGreedIndexResponseCurrent `json:"current"`
	// Methodology and request-window metadata needed to interpret the response.
	Metadata *FearGreedIndexResponseMetadata `json:"metadata"`
	// Chronologically ordered observations.
	Series []FearGreedIndexResponseSeriesPoint `json:"series"`
}

FearGreedIndexResponse models an object of the `market sentiment` service.

type FearGreedIndexResponseCurrent

type FearGreedIndexResponseCurrent struct {
	// Nebula index value on a 0–100 scale.
	Index float64 `json:"index"`
	// Human-readable bucket or index label.
	Label string `json:"label"`
}

FearGreedIndexResponseCurrent models an object of the `market sentiment` service.

type FearGreedIndexResponseMetadata

type FearGreedIndexResponseMetadata struct {
	// Weighted components used to calculate the index.
	Components []FearGreedIndexResponseMetadataComponent `json:"components"`
	// Lookback window represented by the response, in hours.
	Hours int `json:"hours"`
	// Ordered labels used to interpret index ranges.
	Labels []string `json:"labels"`
	// Published scale or interpretation of the metric.
	Scale string `json:"scale"`
}

FearGreedIndexResponseMetadata models an object of the `market sentiment` service.

type FearGreedIndexResponseMetadataComponent

type FearGreedIndexResponseMetadataComponent struct {
	// Human-readable explanation of this component.
	Description string `json:"description"`
	// Human-readable name.
	Name string `json:"name"`
	// Component weight as a decimal fraction.
	Weight float64 `json:"weight"`
}

FearGreedIndexResponseMetadataComponent models an object of the `market sentiment` service.

type FearGreedIndexResponseSeriesPoint

type FearGreedIndexResponseSeriesPoint struct {
	// Nebula index value on a 0–100 scale.
	Index float64 `json:"index"`
	// Human-readable bucket or index label.
	Label string `json:"label"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
}

FearGreedIndexResponseSeriesPoint models an object of the `market sentiment` service.

type ForecastAssetsRequest

type ForecastAssetsRequest struct {
	AssetClass *AssetClass
	Limit      *int
	Offset     *int
}

ForecastAssetsRequest carries the query parameters of `list_forecast_assets` (GET /forecasts/assets). Docs: https://docs.hiddensystems.ai/nebula/reference/get-forecasts-assets/

type ForecastAssetsResponse

type ForecastAssetsResponse struct {
	BaseResponse
	// Assets with a current forecast: stocks, commodities, and indices first, then crypto; most-discussed first within each class.
	Assets []ForecastAssetsResponseAsset `json:"assets"`
	// True when another page is available after the returned records.
	HasMore bool `json:"has_more"`
	// Maximum records requested.
	Limit int `json:"limit"`
	// Number of matching records skipped.
	Offset int `json:"offset"`
	// How many assets match the request across every page.
	Total int `json:"total"`
}

ForecastAssetsResponse models an object of the `forecasts` service.

type ForecastAssetsResponseAsset

type ForecastAssetsResponseAsset struct {
	// UTC start of the asset's current forecast: the end of the last complete 15 minutes it was computed from.
	AsOf time.Time `json:"as_of"`
	// The asset's class: equity (stocks and ETFs), commodity, index, or crypto. Send it with asset_id on every asset-scoped request.
	AssetClass AssetClass `json:"asset_class"`
	// Canonical public asset identifier: the ticker or market symbol for stocks, commodities, and indices, and the CoinGecko slug (or, without one, a numeric id) for crypto.
	AssetID string `json:"asset_id"`
	// Human-readable name.
	Name string `json:"name"`
	// Display ticker or market symbol.
	Symbol string `json:"symbol"`
}

ForecastAssetsResponseAsset models an object of the `forecasts` service.

type ForecastReason

type ForecastReason string

ForecastReason explains why an asset cannot be forecast.

const (
	ForecastReasonTooLittleHistory ForecastReason = "too_little_history"
	ForecastReasonStaleData        ForecastReason = "stale_data"
	ForecastReasonMissingPrice     ForecastReason = "missing_price"
)

type ForecastStatus

type ForecastStatus string

ForecastStatus discriminates a forecast response.

const (
	ForecastStatusOK              ForecastStatus = "ok"
	ForecastStatusNotForecastable ForecastStatus = "not_forecastable"
)

type ForecastsService

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

func (*ForecastsService) ListAssets

ListAssets - Forecastable assets. GET /forecasts/assets Docs: https://docs.hiddensystems.ai/nebula/reference/get-forecasts-assets/

func (*ForecastsService) Mindshare

Mindshare - Mindshare forecast. GET /forecasts/mindshare Docs: https://docs.hiddensystems.ai/nebula/reference/get-forecasts-mindshare/

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	nebula "github.com/tigusigalpa/nebula-go"
)

func main() {
	client, err := nebula.New(os.Getenv("NEBULA_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}
	forecast, err := client.Forecasts.Mindshare(context.Background(), &nebula.MindshareForecastRequest{Asset: &nebula.AssetRef{ID: "NVDA", Class: nebula.AssetClassEquity}})
	if err != nil {
		log.Fatal(err)
	}
	if !forecast.IsForecastable() {
		if forecast.Reason != nil {
			fmt.Println(*forecast.Reason)
		}
		return
	}
	fmt.Println(len(forecast.Series))
}

func (*ForecastsService) Sentiment

Sentiment - Sentiment forecast. GET /forecasts/sentiment Docs: https://docs.hiddensystems.ai/nebula/reference/get-forecasts-sentiment/

type Granularity

type Granularity string

Granularity is the bucket size of a time series.

const (
	Granularity1h  Granularity = "1h"
	Granularity2h  Granularity = "2h"
	Granularity4h  Granularity = "4h"
	Granularity12h Granularity = "12h"
	Granularity1d  Granularity = "1d"
)

func GranularityPtr

func GranularityPtr(v Granularity) *Granularity

GranularityPtr returns a pointer to v for optional request fields.

type InsightAttentionRequest

type InsightAttentionRequest struct {
	InsightID int
}

InsightAttentionRequest carries the query parameters of `get_insight_attention` (GET /insights/attention). Docs: https://docs.hiddensystems.ai/nebula/reference/get-insight-attention/

type InsightAttentionResponse

type InsightAttentionResponse struct {
	BaseResponse
	// Conversation and impact readout for the requested intelligence item.
	Attention *InsightAttentionResponseAttention `json:"attention"`
	// Stable identifier for the intelligence item.
	InsightID int64 `json:"insight_id"`
	// Price reactions for priceable entities linked to the intelligence item.
	PriceReactions []InsightAttentionResponsePriceReaction `json:"price_reactions"`
}

InsightAttentionResponse models an object of the `intelligence` service.

type InsightAttentionResponseAttention

type InsightAttentionResponseAttention struct {
	// Subject id used to anchor the attention scan.
	AnchorSubjectID string `json:"anchor_subject_id"`
	// Distinct authors represented by the matching posts.
	Authors int64 `json:"authors"`
	// Arithmetic mean of the posts' sentiment scores, on the −100 (very bearish) to +100 (very bullish) scale.
	AverageSentimentScore float64 `json:"average_sentiment_score"`
	// Posts classified as bearish.
	BearishPosts int64 `json:"bearish_posts"`
	// Width of each bucket in hours.
	BucketHours int `json:"bucket_hours"`
	// Attention buckets in chronological order.
	Buckets []InsightAttentionResponseAttentionBucket `json:"buckets"`
	// Posts classified as bullish.
	BullishPosts int64 `json:"bullish_posts"`
	// Author-cluster mix for the matching posts, ranked by authors.
	ClusterMix []InsightAttentionResponseAttentionClusterMixItem `json:"cluster_mix"`
	// Distinct author clusters represented by the matching posts.
	Clusters int64 `json:"clusters"`
	// Inclusive UTC start of the measured window.
	From time.Time `json:"from"`
	// Structured impact assessment for the intelligence item.
	Impact *InsightAttentionResponseAttentionImpact `json:"impact"`
	// UTC time of the latest matching post in the requested window.
	LastPostAt *time.Time `json:"last_post_at"`
	// Posts classified as neutral.
	NeutralPosts int64 `json:"neutral_posts"`
	// Subject ids where matching posts had to mention at least one; empty means no optional side was required.
	OptionalSubjects []string `json:"optional_subjects"`
	// Matching post count over the requested window.
	Posts int64 `json:"posts"`
	// Subject ids that all matching posts had to mention.
	RequiredSubjects []string `json:"required_subjects"`
	// Subject ids actually used for the returned attention window after any fallback.
	SubjectsUsed []string `json:"subjects_used"`
	// Exclusive UTC end of the measured window.
	To time.Time `json:"to"`
	// Window placement around the insight: before or around.
	WindowKind string `json:"window_kind"`
}

InsightAttentionResponseAttention models an object of the `intelligence` service.

type InsightAttentionResponseAttentionBucket

type InsightAttentionResponseAttentionBucket struct {
	// Distinct authors represented by the matching posts.
	Authors int64 `json:"authors"`
	// Arithmetic mean of the posts' sentiment scores, on the −100 (very bearish) to +100 (very bullish) scale.
	AverageSentimentScore float64 `json:"average_sentiment_score"`
	// Posts classified as bearish.
	BearishPosts int64 `json:"bearish_posts"`
	// Posts classified as bullish.
	BullishPosts int64 `json:"bullish_posts"`
	// Posts classified as neutral.
	NeutralPosts int64 `json:"neutral_posts"`
	// Matching post count over the requested window.
	Posts int64 `json:"posts"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
}

InsightAttentionResponseAttentionBucket models an object of the `intelligence` service.

type InsightAttentionResponseAttentionClusterMixItem

type InsightAttentionResponseAttentionClusterMixItem struct {
	// Distinct authors represented by the matching posts.
	Authors int64 `json:"authors"`
	// Canonical author-cluster identifier.
	ClusterID string `json:"cluster_id"`
	// Matching post count over the requested window.
	Posts *int64 `json:"posts"`
	// Share of eligible social attention as a decimal fraction from 0 to 1.
	Share float64 `json:"share"`
}

InsightAttentionResponseAttentionClusterMixItem models an object of the `intelligence` service.

type InsightAttentionResponseAttentionImpact

type InsightAttentionResponseAttentionImpact struct {
	// Maximum possible score for each impact vector.
	MaxScore int `json:"max_score"`
	// Signed sentiment score; positive is bullish and negative is bearish.
	SentimentScore int `json:"sentiment_score"`
	// Impact vectors behind the item-level impact assessment.
	Vectors []InsightAttentionResponseAttentionImpactVector `json:"vectors"`
}

InsightAttentionResponseAttentionImpact models an object of the `intelligence` service.

type InsightAttentionResponseAttentionImpactVector

type InsightAttentionResponseAttentionImpactVector struct {
	// Stable machine-readable key for this impact vector.
	Key string `json:"key"`
	// Human-readable bucket or index label.
	Label string `json:"label"`
	// Score for this impact vector.
	Score int `json:"score"`
}

InsightAttentionResponseAttentionImpactVector models an object of the `intelligence` service.

type InsightAttentionResponsePriceReaction

type InsightAttentionResponsePriceReaction struct {
	// UTC time used as the baseline for the price reaction.
	InsightAt time.Time `json:"insight_at"`
	// Stable identifier for the intelligence item.
	InsightID int64 `json:"insight_id"`
	// Latest price change versus the insight baseline, present for recent insights.
	LivePct *float64 `json:"live_pct"`
	// Fixed-horizon price moves once each horizon has elapsed.
	Moves []InsightAttentionResponsePriceReactionMove `json:"moves"`
	// Chronologically ordered observations.
	Series []InsightAttentionResponsePriceReactionSeriesPoint `json:"series"`
	// Canonical identifier for a non-asset person, account, or topic.
	SubjectID string `json:"subject_id"`
}

InsightAttentionResponsePriceReaction models an object of the `intelligence` service.

type InsightAttentionResponsePriceReactionMove

type InsightAttentionResponsePriceReactionMove struct {
	// Percentage-point price change versus the baseline at the insight time.
	ChangePct float64 `json:"change_pct"`
	// Lookback window represented by the response, in hours.
	Hours int `json:"hours"`
}

InsightAttentionResponsePriceReactionMove models an object of the `intelligence` service.

type InsightAttentionResponsePriceReactionSeriesPoint

type InsightAttentionResponsePriceReactionSeriesPoint struct {
	// Percentage-point price change versus the baseline at the insight time.
	ChangePct float64 `json:"change_pct"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
}

InsightAttentionResponsePriceReactionSeriesPoint models an object of the `intelligence` service.

type InsightDomain

type InsightDomain string

InsightDomain is an event domain on the insights endpoint.

const (
	InsightDomainCrypto            InsightDomain = "crypto"
	InsightDomainEquities          InsightDomain = "equities"
	InsightDomainCommodities       InsightDomain = "commodities"
	InsightDomainMacro             InsightDomain = "macro"
	InsightDomainPolitics          InsightDomain = "politics"
	InsightDomainTechnology        InsightDomain = "technology"
	InsightDomainSports            InsightDomain = "sports"
	InsightDomainPredictionMarkets InsightDomain = "prediction_markets"
)

type InsightOrderBy

type InsightOrderBy string

InsightOrderBy is the ordering of the insights list.

const (
	InsightOrderByStartTimeAsc        InsightOrderBy = "start_time_asc"
	InsightOrderByStartTimeDesc       InsightOrderBy = "start_time_desc"
	InsightOrderByUpdatedAtAsc        InsightOrderBy = "updated_at_asc"
	InsightOrderByUpdatedAtDesc       InsightOrderBy = "updated_at_desc"
	InsightOrderByCreatedAtAsc        InsightOrderBy = "created_at_asc"
	InsightOrderByCreatedAtDesc       InsightOrderBy = "created_at_desc"
	InsightOrderByImportanceScoreAsc  InsightOrderBy = "importance_score_asc"
	InsightOrderByImportanceScoreDesc InsightOrderBy = "importance_score_desc"
)

func InsightOrderByPtr

func InsightOrderByPtr(v InsightOrderBy) *InsightOrderBy

InsightOrderByPtr returns a pointer to v for optional request fields.

type InsightsRequest

type InsightsRequest struct {
	Asset           *AssetRef
	Subject         *SubjectRef
	Limit           *int
	Offset          *int
	StartTimeAfter  *time.Time
	StartTimeBefore *time.Time
	Tags            []string
	ExcludeTags     []string
	Categories      []string
	Domains         []InsightDomain
	OrderBy         *InsightOrderBy
}

InsightsRequest carries the query parameters of `list_insights` (GET /insights). Docs: https://docs.hiddensystems.ai/nebula/reference/get-insights/

type InsightsResponse

type InsightsResponse struct {
	BaseResponse
	// Curated intelligence items matching the supplied filters.
	Insights []InsightsResponseInsight `json:"insights"`
}

InsightsResponse models an object of the `intelligence` service.

type InsightsResponseInsight

type InsightsResponseInsight struct {
	// Primary intelligence category when assigned.
	Category *string `json:"category"`
	// Market or subject domains attached to the record.
	Domains []string `json:"domains"`
	// Assets and non-asset subjects linked to this record.
	Entities []InsightsResponseInsightEntity `json:"entities"`
	// Concise intelligence headline.
	Headline string `json:"headline"`
	// Importance from 1 (low) to 3 (high).
	ImportanceScore int `json:"importance_score"`
	// Stable identifier for the intelligence item.
	InsightID int64 `json:"insight_id"`
	// Signed sentiment score; positive is bullish and negative is bearish.
	SentimentScore int `json:"sentiment_score"`
	// UTC time when the intelligence item or event starts.
	StartTime *time.Time `json:"start_time"`
	// Evidence-grounded summary of the intelligence item.
	Summary string `json:"summary"`
	// Searchable labels attached to the record.
	Tags []string `json:"tags"`
	// UTC time when the record was last updated.
	UpdatedAt *time.Time `json:"updated_at"`
}

InsightsResponseInsight models an object of the `intelligence` service.

type InsightsResponseInsightEntity

type InsightsResponseInsightEntity struct {
	// The asset's class, sent with asset_id.
	AssetClass *AssetClass `json:"asset_class"`
	// For a stock, commodity, index, or coin, the asset_id the asset endpoints take; absent for people, accounts, and topics, and for the rare asset Nebula cannot place.
	AssetID *string `json:"asset_id"`
	// Nebula's id for the linked entity, such as eq:NVDA, gecko:1, or text:ai. To query the entity, use asset_id and asset_class, or subject_id, from the same object.
	EntityID string `json:"entity_id"`
	// Knowledge-graph classifications for the linked entity.
	EntityTypes []string `json:"entity_types"`
	// True when the record directly concerns this linked entity.
	IsDirect bool `json:"is_direct"`
	// True when this is the record's primary linked entity.
	IsPrimary bool `json:"is_primary"`
	// Human-readable name.
	Name string `json:"name"`
	// Relationship of the linked entity to the intelligence item.
	Role string `json:"role"`
	// For a person, account, or topic, the subject_id the subject-aware endpoints take; absent for assets.
	SubjectID *string `json:"subject_id"`
}

InsightsResponseInsightEntity models an object of the `intelligence` service.

type IntelligenceService

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

func (*IntelligenceService) CalendarEvents

CalendarEvents - Calendar events. GET /calendar-events Docs: https://docs.hiddensystems.ai/nebula/reference/get-calendar-events/

func (*IntelligenceService) InsightAttention

InsightAttention - Insight attention. GET /insights/attention Docs: https://docs.hiddensystems.ai/nebula/reference/get-insight-attention/

func (*IntelligenceService) Insights

Insights - Intelligence. GET /insights Docs: https://docs.hiddensystems.ai/nebula/reference/get-insights/

type Kind

type Kind string

Kind distinguishes market assets from people/topics (subjects).

const (
	KindAsset   Kind = "asset"
	KindSubject Kind = "subject"
)

func KindPtr

func KindPtr(v Kind) *Kind

KindPtr returns a pointer to v for optional request fields.

type ListAssetsRequest

type ListAssetsRequest struct {
	Asset *AssetRef
	// AssetClass filters a search or listing without selecting a specific asset.
	// Use Asset.Class instead when Asset is provided.
	AssetClass *AssetClass
	Query      *string
	Limit      *int
	Offset     *int
}

ListAssetsRequest carries the query parameters of `list_assets` (GET /assets). Docs: https://docs.hiddensystems.ai/nebula/reference/get-assets/

type ListAssetsResponse

type ListAssetsResponse struct {
	BaseResponse
	// Assets matching the supplied discovery filters.
	Assets []ListAssetsResponseAsset `json:"assets"`
	// True when another page is available after the returned records.
	HasMore bool `json:"has_more"`
	// Maximum records requested.
	Limit int `json:"limit"`
	// Number of matching records skipped.
	Offset int `json:"offset"`
}

ListAssetsResponse models an object of the `lookup` service.

type ListAssetsResponseAsset

type ListAssetsResponseAsset struct {
	// The asset's class: equity (stocks and ETFs), commodity, index, or crypto. Send it with asset_id on every asset-scoped request.
	AssetClass AssetClass `json:"asset_class"`
	// Canonical public asset identifier: the ticker or market symbol for stocks, commodities, and indices, and the CoinGecko slug (or, without one, a numeric id) for crypto.
	AssetID string `json:"asset_id"`
	// Primary social handle when available.
	Handle *string `json:"handle"`
	// Latest market capitalisation in US dollars. Reported for crypto; absent for stocks, commodities, and indices.
	MarketCapUSD *float64 `json:"market_cap_usd"`
	// Human-readable name.
	Name string `json:"name"`
	// Raw market-price change over 24 hours, in percentage points.
	PriceChange24hPct *float64 `json:"price_change_24h_pct"`
	// Latest or observed market price in US dollars.
	PriceUSD *float64 `json:"price_usd"`
	// Display ticker or market symbol.
	Symbol string `json:"symbol"`
}

ListAssetsResponseAsset models an object of the `lookup` service.

type ListSubjectsRequest

type ListSubjectsRequest struct {
	Subject *SubjectRef
	Query   *string
	Limit   *int
	Offset  *int
}

ListSubjectsRequest carries the query parameters of `list_subjects` (GET /subjects). Docs: https://docs.hiddensystems.ai/nebula/reference/get-subjects/

type ListSubjectsResponse

type ListSubjectsResponse struct {
	BaseResponse
	// True when another page is available after the returned records.
	HasMore bool `json:"has_more"`
	// Maximum records requested.
	Limit int `json:"limit"`
	// Number of matching records skipped.
	Offset int `json:"offset"`
	// Non-asset subjects matching the discovery filters.
	Subjects []ListSubjectsResponseSubject `json:"subjects"`
}

ListSubjectsResponse models an object of the `lookup` service.

type ListSubjectsResponseSubject

type ListSubjectsResponseSubject struct {
	// Human-readable name.
	Name string `json:"name"`
	// Canonical identifier for a non-asset person, account, or topic.
	SubjectID string `json:"subject_id"`
}

ListSubjectsResponseSubject models an object of the `lookup` service.

type Locale

type Locale string

Locale selects the language of generated text. Sent as X-Nebula-Locale (or the `locale` query parameter). It is an open string type: a future locale works without a new SDK release.

const (
	LocaleSpanish  Locale = "es"
	LocaleItalian  Locale = "it"
	LocaleTurkish  Locale = "tr"
	LocaleRussian  Locale = "ru"
	LocaleKorean   Locale = "ko"
	LocaleJapanese Locale = "ja"
	LocaleChinese  Locale = "zh"
)

type LocaleMode

type LocaleMode string

LocaleMode selects whether a configured locale is sent as the X-Nebula-Locale header (default) or the `locale` query parameter.

const (
	// LocaleModeHeader sends X-Nebula-Locale.
	LocaleModeHeader LocaleMode = "header"
	// LocaleModeQuery sends ?locale=.
	LocaleModeQuery LocaleMode = "query"
)

type Logger

type Logger interface {
	Printf(format string, args ...any)
}

Logger is the minimal debug sink. nil disables logging.

type LoggerFunc

type LoggerFunc func(format string, args ...any)

LoggerFunc adapts a function to Logger.

func (LoggerFunc) Printf

func (f LoggerFunc) Printf(format string, args ...any)

Printf implements Logger.

type LookupService

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

func (*LookupService) ListAssets

ListAssets - Text to asset ID. GET /assets Docs: https://docs.hiddensystems.ai/nebula/reference/get-assets/

func (*LookupService) ListSubjects

ListSubjects - Text to subject ID. GET /subjects Docs: https://docs.hiddensystems.ai/nebula/reference/get-subjects/

func (*LookupService) Search

Search - Search. GET /search Docs: https://docs.hiddensystems.ai/nebula/reference/get-search/

type MarketDataService

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

func (*MarketDataService) PriceHistory

PriceHistory - Price history. GET /price-history Docs: https://docs.hiddensystems.ai/nebula/reference/get-price-history/

type MarketSentimentService

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

func (*MarketSentimentService) CallReturns

CallReturns - Calls outcome distribution. GET /calls/returns Docs: https://docs.hiddensystems.ai/nebula/reference/get-calls-returns/

func (*MarketSentimentService) Calls

Calls - Long/short calls. GET /calls Docs: https://docs.hiddensystems.ai/nebula/reference/get-calls/

func (*MarketSentimentService) ConvictionIndex

ConvictionIndex - Conviction index. GET /conviction-index Docs: https://docs.hiddensystems.ai/nebula/reference/get-conviction-index/

func (*MarketSentimentService) FearGreedIndex

FearGreedIndex - Fear and Greed index. GET /fear-greed-index Docs: https://docs.hiddensystems.ai/nebula/reference/get-fear-greed-index/

func (*MarketSentimentService) PriceLevels

PriceLevels - Socially mentioned price levels. GET /price-levels Docs: https://docs.hiddensystems.ai/nebula/reference/get-price-levels/

func (*MarketSentimentService) SocialVolumeIndex

SocialVolumeIndex - Social vs trading volume. GET /social-volume-index Docs: https://docs.hiddensystems.ai/nebula/reference/get-social-volume-index/

func (*MarketSentimentService) SocialVolumeProfile

SocialVolumeProfile - Social volume profile. GET /social-volume-profile Docs: https://docs.hiddensystems.ai/nebula/reference/get-social-volume-profile/

type MindshareForecastRequest

type MindshareForecastRequest struct {
	Asset   *AssetRef
	Refresh *bool
}

MindshareForecastRequest carries the query parameters of `get_mindshare_forecast` (GET /forecasts/mindshare). Docs: https://docs.hiddensystems.ai/nebula/reference/get-forecasts-mindshare/

type MindshareForecastResponse

type MindshareForecastResponse struct {
	BaseResponse
	// UTC start of the forecast: the end of the last complete 15 minutes it was computed from. Null when the asset has never been scored.
	AsOf *time.Time `json:"as_of"`
	// The chance the share is higher than current_share in 72 hours, from 0 to 1.
	ChanceHigher72h *float64 `json:"chance_higher_72h"`
	// The asset's share at as_of, from 0 to 1: where every path starts, and the value the chances are measured against.
	CurrentShare *float64 `json:"current_share"`
	// How far ahead the forecast runs, in hours: always 72.
	HorizonHours int `json:"horizon_hours"`
	// The 90th percentile of the share in 72 hours: a 90% chance of ending below it.
	LikelyHighShare *float64 `json:"likely_high_share"`
	// The 10th percentile of the share in 72 hours: a 90% chance of ending above it.
	LikelyLowShare *float64 `json:"likely_low_share"`
	// Why the asset cannot be forecast: too_little_history, stale_data, or missing_price. Null when status is ok.
	Reason *ForecastReason `json:"reason"`
	// True when this request re-ran the forecast (refresh=true and the re-run finished in time); false when it is the latest scheduled five-minute forecast.
	Refreshed bool `json:"refreshed"`
	// 24 possible paths for the share, each aligned with series. Draw them to show the spread of outcomes.
	SamplePaths [][]float64 `json:"sample_paths"`
	// The forecast distribution every 4 hours from as_of: 18 steps, oldest first.
	Series []MindshareForecastResponseSeriesPoint `json:"series"`
	// ok, or not_forecastable when the asset cannot be forecast (the summary fields are then null and the series empty; reason says why).
	Status ForecastStatus `json:"status"`
	// The chance of a sudden surge in attention on the asset within 72 hours, from 0 to 1. Null when there is no estimate.
	TakeoffChance72h *float64 `json:"takeoff_chance_72h"`
}

MindshareForecastResponse models an object of the `forecasts` service.

func (*MindshareForecastResponse) IsForecastable

func (r *MindshareForecastResponse) IsForecastable() bool

IsForecastable reports whether the result contains a usable forecast. A not_forecastable result is a successful business response, not an API error.

type MindshareForecastResponseSeriesPoint

type MindshareForecastResponseSeriesPoint struct {
	// The expected share at this step.
	MeanShare float64 `json:"mean_share"`
	// The 10th percentile of the share at this step, from 0 to 1.
	P10Share float64 `json:"p10_share"`
	// The 25th percentile of the share at this step, from 0 to 1.
	P25Share float64 `json:"p25_share"`
	// The 50th percentile of the share at this step, from 0 to 1.
	P50Share float64 `json:"p50_share"`
	// The 75th percentile of the share at this step, from 0 to 1.
	P75Share float64 `json:"p75_share"`
	// The 90th percentile of the share at this step, from 0 to 1.
	P90Share float64 `json:"p90_share"`
	// 21 quantiles of the share at this step: the 0th, 5th, 10th, ... 100th percentiles, lowest first. Interpolate between them for the chance of landing in any range.
	QuantileShares []float64 `json:"quantile_shares"`
	// UTC time the step forecasts: as_of plus 4, 8, ... 72 hours.
	Timestamp time.Time `json:"timestamp"`
}

MindshareForecastResponseSeriesPoint models an object of the `forecasts` service.

type MindshareRequest

type MindshareRequest struct {
	Asset       *AssetRef
	Subject     *SubjectRef
	Hours       *int
	Granularity *Granularity
	Clusters    []string
}

MindshareRequest carries the query parameters of `get_mindshare` (GET /mindshare). Docs: https://docs.hiddensystems.ai/nebula/reference/get-mindshare/

type MindshareResponse

type MindshareResponse struct {
	BaseResponse
	// Chronologically ordered observations.
	Series []MindshareResponseSeriesPoint `json:"series"`
}

MindshareResponse models an object of the `social` service.

type MindshareResponseSeriesPoint

type MindshareResponseSeriesPoint struct {
	// Share of eligible social attention as a decimal fraction from 0 to 1.
	Share float64 `json:"share"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
}

MindshareResponseSeriesPoint models an object of the `social` service.

type Option

type Option func(*config) error

Option configures a Client at New() time.

func WithAuthMode

func WithAuthMode(m AuthMode) Option

WithAuthMode switches between X-API-Key (default) and Authorization: Bearer <key>. The two are never sent together.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL overrides the account API base URL (testing / gateways). The URL must be absolute; it is joined with endpoint paths safely.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient supplies the *http.Client used for requests. Pass an x402-wrapped client (see the x402 adapter package) or a custom-instrumented client here; nil keeps a default client.

func WithLocale

func WithLocale(l Locale) Option

WithLocale sets the global generated-text locale (X-Nebula-Locale by default; see WithLocaleMode for the ?locale= variant).

func WithLocaleMode

func WithLocaleMode(m LocaleMode) Option

WithLocaleMode selects header or query transport for the locale.

func WithLogger

func WithLogger(l Logger) Option

WithLogger installs a debug logger. Transport logs redact API keys, bearer tokens and payment headers.

func WithRetry

func WithRetry(maxAttempts int, base, max time.Duration) Option

WithRetry configures automatic retries of idempotent GET requests. maxAttempts is the total tries including the first (1 = no retries); base is the initial backoff, max the cap. The delay honors the server's Retry-After and RateLimit-Reset hints before the computed backoff.

func WithRetryPolicy

func WithRetryPolicy(p RetryPolicy) Option

WithRetryPolicy installs a fully specified retry policy.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the overall request timeout. The deadline covers all retry attempts and response-body reading of one call, including streams. Zero keeps the 30-second default; negative durations are rejected.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent overrides the User-Agent header. The SDK still defaults to nebula-go/<version> when unset.

type PaymentUncertainError

type PaymentUncertainError struct {
	Op       string
	URL      string
	Metadata ResponseMetadata
	Err      error
}

PaymentUncertainError retains the request identity and any settlement receipt when a signed payment request fails. Reconcile it before paying again.

func (*PaymentUncertainError) Error

func (e *PaymentUncertainError) Error() string

func (*PaymentUncertainError) Is

func (e *PaymentUncertainError) Is(target error) bool

func (*PaymentUncertainError) Unwrap

func (e *PaymentUncertainError) Unwrap() error

type PredictionHistoryRequest

type PredictionHistoryRequest struct {
	ListingID string
	OutcomeID string
	Hours     *int
}

PredictionHistoryRequest carries the query parameters of `get_prediction_history` (GET /predictions/history). Docs: https://docs.hiddensystems.ai/nebula/reference/get-prediction-history/

type PredictionHistoryResponse

type PredictionHistoryResponse struct {
	BaseResponse
	// Venue-prefixed native market identity.
	ListingID string `json:"listing_id"`
	// Native outcome identity within the listing.
	OutcomeID string `json:"outcome_id"`
	// Deprecated compatibility mirror of series, using time instead of timestamp. Use series for new integrations.
	Points []PredictionHistoryResponsePoint `json:"points"`
	// Historical observations in chronological order, with an explicit price basis; no invented samples.
	Series []PredictionHistoryResponseSeriesPoint `json:"series"`
}

PredictionHistoryResponse models an object of the `predictions` service.

type PredictionHistoryResponsePoint

type PredictionHistoryResponsePoint struct {
	// Price as a fraction from 0 to 1. Current quotes use valid bid-ask midpoints; history may include provider prices as identified by price_basis. Not subject sentiment.
	Price float64 `json:"price"`
	// midpoint or unavailable for current quotes; historical series may also use provider for venue history of unspecified quote basis.
	PriceBasis string `json:"price_basis"`
	// UTC observation time.
	Time time.Time `json:"time"`
}

PredictionHistoryResponsePoint models an object of the `predictions` service.

type PredictionHistoryResponseSeriesPoint

type PredictionHistoryResponseSeriesPoint struct {
	// Price as a fraction from 0 to 1. Current quotes use valid bid-ask midpoints; history may include provider prices as identified by price_basis. Not subject sentiment.
	Price float64 `json:"price"`
	// midpoint or unavailable for current quotes; historical series may also use provider for venue history of unspecified quote basis.
	PriceBasis string `json:"price_basis"`
	// Observation time in UTC RFC 3339.
	Timestamp time.Time `json:"timestamp"`
}

PredictionHistoryResponseSeriesPoint models an object of the `predictions` service.

type PredictionMarketRequest

type PredictionMarketRequest struct {
	MarketID string
}

PredictionMarketRequest carries the query parameters of `get_prediction_market` (GET /predictions/market). Docs: https://docs.hiddensystems.ai/nebula/reference/get-prediction-market/

type PredictionMarketResponse

type PredictionMarketResponse struct {
	BaseResponse
	// Linked identities for existing analytics endpoints. Assets carry asset_id and asset_class; non-assets carry subject_id. An identity without selectors is not yet available for analy
	Entities []PredictionMarketResponseEntity `json:"entities"`
	// Stable identity within this object type.
	ID string `json:"id"`
	// Venue listings with separately retained rules and quotes.
	Listings []PredictionMarketResponseListing `json:"listings"`
	// Original contract question.
	Question string `json:"question"`
	// Legacy attachment metadata retained for compatibility. Use entities for analytics selectors.
	Subjects []PredictionMarketResponseSubject `json:"subjects"`
}

PredictionMarketResponse models an object of the `predictions` service.

type PredictionMarketResponseEntity

type PredictionMarketResponseEntity struct {
	// Asset class: equity, commodity, index or crypto.
	AssetClass *AssetClass `json:"asset_class"`
	// Asset identifier accepted by asset analytics endpoints.
	AssetID *string `json:"asset_id"`
	// Canonical subject display name.
	Name string `json:"name"`
	// Non-asset subject identifier accepted by subject analytics endpoints. Mutually exclusive with asset selectors.
	SubjectID *string `json:"subject_id"`
}

PredictionMarketResponseEntity models an object of the `predictions` service.

type PredictionMarketResponseListing

type PredictionMarketResponseListing struct {
	// Venue trading close in UTC; not necessarily event occurrence or settlement.
	ClosesAt *time.Time `json:"closes_at"`
	// Venue event identifier, or empty if absent.
	EventID string `json:"event_id"`
	// Stable identity within this object type.
	ID string `json:"id"`
	// Venue-reported liquidity in US dollars; null when unavailable.
	LiquidityUSD *float64 `json:"liquidity_usd"`
	// Canonical market identity; equivalent venue listings share it.
	MarketID string `json:"market_id"`
	// UTC time Nebula fetched this quote. Inspect freshness before comparing.
	ObservedAt time.Time `json:"observed_at"`
	// Venue open contracts; null when unavailable.
	OpenInterest *float64 `json:"open_interest"`
	// Venue opening time in UTC; null when unavailable.
	OpensAt *time.Time `json:"opens_at"`
	// Ordered native outcomes with independent price evidence.
	Outcomes []PredictionMarketResponseListingOutcome `json:"outcomes"`
	// Venue: polymarket or kalshi.
	Provider PredictionProvider `json:"provider"`
	// Native venue market identifier.
	ProviderID string `json:"provider_id"`
	// Venue metadata update time; null when unavailable.
	ProviderUpdatedAt *time.Time `json:"provider_updated_at"`
	// Original contract question.
	Question string `json:"question"`
	// Venue resolution source, or empty if absent.
	ResolutionSource string `json:"resolution_source"`
	// Venue expected resolution time in UTC; null when unavailable.
	ResolvesAt *time.Time `json:"resolves_at"`
	// Venue settlement result; empty before a known result.
	Result string `json:"result"`
	// Legacy contract revision token; retained for compatibility.
	Revision string `json:"revision"`
	// Full venue resolution rules.
	Rules string `json:"rules"`
	// Original venue listing URL.
	SourceURL string `json:"source_url"`
	// Listing lifecycle: open, closed, resolved or disputed. For subjects: resolved or pending.
	Status string `json:"status"`
	// Cumulative venue volume in volume_unit; null when unavailable.
	Volume *float64 `json:"volume"`
	// Last 24-hour venue volume in volume_unit; null when unavailable.
	Volume24h *float64 `json:"volume_24h"`
	// usd for Polymarket, contracts for Kalshi. These quantities cannot be added.
	VolumeUnit string `json:"volume_unit"`
}

PredictionMarketResponseListing models an object of the `predictions` service.

type PredictionMarketResponseListingOutcome

type PredictionMarketResponseListingOutcome struct {
	// Venue ask as a fraction from 0 to 1; null when unavailable.
	Ask *float64 `json:"ask"`
	// Venue bid as a fraction from 0 to 1; null when unavailable.
	Bid *float64 `json:"bid"`
	// Stable identity within this object type.
	ID string `json:"id"`
	// Venue outcome label.
	Label string `json:"label"`
	// Last traded price from 0 to 1; null when unavailable. Kalshi No is the complement of its reported Yes last trade; Polymarket is token-specific. Observation time is not trade time.
	LastTrade *float64 `json:"last_trade"`
	// Bid-ask midpoint from 0 to 1; null when unavailable.
	Midpoint *float64 `json:"midpoint"`
	// Zero-based native outcome position.
	Position int `json:"position"`
	// Price as a fraction from 0 to 1. Current quotes use valid bid-ask midpoints; history may include provider prices as identified by price_basis. Not subject sentiment.
	Price *float64 `json:"price"`
	// midpoint or unavailable for current quotes; historical series may also use provider for venue history of unspecified quote basis.
	PriceBasis string `json:"price_basis"`
	// Provider-reported reference or settlement price from 0 to 1; null when unavailable. Retained independently of midpoint.
	ProviderPrice *float64 `json:"provider_price"`
}

PredictionMarketResponseListingOutcome models an object of the `predictions` service.

type PredictionMarketResponseSubject

type PredictionMarketResponseSubject struct {
	// Ordered backend-resolved fallback icon candidates.
	FallbackImageUrls []string `json:"fallback_image_urls"`
	// First backend-resolved subject icon candidate; empty uses fallbacks.
	ImageURL string `json:"image_url"`
	// Canonical subject display name.
	Name string `json:"name"`
	// Question attachment role: entity, topic or place.
	Role string `json:"role"`
	// Listing lifecycle: open, closed, resolved or disputed. For subjects: resolved or pending.
	Status string `json:"status"`
	// Canonical registry subject identifier; preserves existing asset or topic eligibility.
	SubjectID string `json:"subject_id"`
	// Canonical subject types from the existing identity resolver.
	Types []string `json:"types"`
}

PredictionMarketResponseSubject models an object of the `predictions` service.

type PredictionProvider

type PredictionProvider string

PredictionProvider is a prediction-market venue.

const (
	PredictionProviderPolymarket PredictionProvider = "polymarket"
	PredictionProviderKalshi     PredictionProvider = "kalshi"
)

func PredictionProviderPtr

func PredictionProviderPtr(v PredictionProvider) *PredictionProvider

PredictionProviderPtr returns a pointer to v for optional request fields.

type PredictionStatus

type PredictionStatus string

PredictionStatus is the lifecycle state of a prediction market listing.

const (
	PredictionStatusOpen     PredictionStatus = "open"
	PredictionStatusClosed   PredictionStatus = "closed"
	PredictionStatusResolved PredictionStatus = "resolved"
	PredictionStatusDisputed PredictionStatus = "disputed"
	PredictionStatusAll      PredictionStatus = "all"
)

func PredictionStatusPtr

func PredictionStatusPtr(v PredictionStatus) *PredictionStatus

PredictionStatusPtr returns a pointer to v for optional request fields.

type PredictionsRequest

type PredictionsRequest struct {
	Asset *AssetRef
	// AssetClass filters markets without selecting an individual asset.
	// Use Asset.Class instead when Asset is provided.
	AssetClass *AssetClass
	Subject    *SubjectRef
	Query      *string
	Provider   *PredictionProvider
	Status     *PredictionStatus
	Limit      *int
	Offset     *int
}

PredictionsRequest carries the query parameters of `list_prediction_markets` (GET /predictions). Docs: https://docs.hiddensystems.ai/nebula/reference/get-predictions/

type PredictionsResponse

type PredictionsResponse struct {
	BaseResponse
	// True when another page is available after the returned records.
	HasMore bool `json:"has_more"`
	// Maximum records requested.
	Limit int `json:"limit"`
	// Canonical markets, ordered by best activity rank within each venue. Venue volumes are not summed.
	Markets []PredictionMarketResponse `json:"markets"`
	// Number of matching records skipped.
	Offset int `json:"offset"`
}

PredictionsResponse models an object of the `predictions` service.

type PredictionsService

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

func (*PredictionsService) History

History - Prediction outcome history. GET /predictions/history Docs: https://docs.hiddensystems.ai/nebula/reference/get-prediction-history/

func (*PredictionsService) ListMarkets

ListMarkets - Prediction markets. GET /predictions Docs: https://docs.hiddensystems.ai/nebula/reference/get-predictions/

func (*PredictionsService) Market

Market - Prediction market detail. GET /predictions/market Docs: https://docs.hiddensystems.ai/nebula/reference/get-prediction-market/

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	nebula "github.com/tigusigalpa/nebula-go"
)

func main() {
	client, err := nebula.New(os.Getenv("NEBULA_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()
	markets, err := client.Predictions.ListMarkets(ctx, &nebula.PredictionsRequest{Query: nebula.StringPtr("NVIDIA"), Limit: nebula.IntPtr(10)})
	if err != nil {
		log.Fatal(err)
	}
	if len(markets.Markets) == 0 {
		return
	}
	market, err := client.Predictions.Market(ctx, &nebula.PredictionMarketRequest{MarketID: markets.Markets[0].ID})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(market.Question)
}

type PriceHistoryRequest

type PriceHistoryRequest struct {
	Asset       *AssetRef
	Hours       *int
	Granularity *Granularity
}

PriceHistoryRequest carries the query parameters of `get_price_history` (GET /price-history). Docs: https://docs.hiddensystems.ai/nebula/reference/get-price-history/

type PriceHistoryResponse

type PriceHistoryResponse struct {
	BaseResponse
	// Chronologically ordered observations.
	Series []PriceHistoryResponseSeriesPoint `json:"series"`
}

PriceHistoryResponse models an object of the `market data` service.

type PriceHistoryResponseSeriesPoint

type PriceHistoryResponseSeriesPoint struct {
	// Observed high price in US dollars.
	HighUSD *float64 `json:"high_usd"`
	// Observed low price in US dollars.
	LowUSD *float64 `json:"low_usd"`
	// Latest or observed market price in US dollars.
	PriceUSD *float64 `json:"price_usd"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
}

PriceHistoryResponseSeriesPoint models an object of the `market data` service.

type PriceLevelsRequest

type PriceLevelsRequest struct {
	Asset *AssetRef
	Hours *int
}

PriceLevelsRequest carries the query parameters of `get_price_levels` (GET /price-levels). Docs: https://docs.hiddensystems.ai/nebula/reference/get-price-levels/

type PriceLevelsResponse

type PriceLevelsResponse struct {
	BaseResponse
	// Socially mentioned price-level buckets.
	Levels []PriceLevelsResponseLevel `json:"levels"`
}

PriceLevelsResponse models an object of the `market sentiment` service.

type PriceLevelsResponseLevel

type PriceLevelsResponseLevel struct {
	// Price mentions in this bucket.
	Mentions int `json:"mentions"`
	// Latest or observed market price in US dollars.
	PriceUSD float64 `json:"price_usd"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
}

PriceLevelsResponseLevel models an object of the `market sentiment` service.

type RelatedSubjectsRequest

type RelatedSubjectsRequest struct {
	Asset   *AssetRef
	Subject *SubjectRef
	Hours   *int
	Limit   *int
}

RelatedSubjectsRequest carries the query parameters of `get_related_subjects` (GET /related-subjects). Docs: https://docs.hiddensystems.ai/nebula/reference/get-related-subjects/

type RelatedSubjectsResponse

type RelatedSubjectsResponse struct {
	BaseResponse
	// Distinct authors represented by the matching posts.
	Authors int64 `json:"authors"`
	// Mean sentiment score across all anchor posts in the requested window.
	AverageSentimentScore float64 `json:"average_sentiment_score"`
	// Inclusive UTC start of the measured window.
	From time.Time `json:"from"`
	// Lookback window represented by the response, in hours.
	Hours int `json:"hours"`
	// Matching post count over the requested window.
	Posts int64 `json:"posts"`
	// Non-asset subjects returned by the discovery operation.
	Subjects []RelatedSubjectsResponseSubject `json:"subjects"`
	// Exclusive UTC end of the measured window.
	To time.Time `json:"to"`
}

RelatedSubjectsResponse models an object of the `social` service.

type RelatedSubjectsResponseSubject

type RelatedSubjectsResponseSubject struct {
	// Distinct authors represented by the matching posts.
	Authors int64 `json:"authors"`
	// Posts classified as bearish.
	BearishPosts int64 `json:"bearish_posts"`
	// Posts classified as bullish.
	BullishPosts int64 `json:"bullish_posts"`
	// UTC time of the first matching post in the requested window.
	FirstPostAt *time.Time `json:"first_post_at"`
	// UTC time of the latest matching post in the requested window.
	LastPostAt *time.Time `json:"last_post_at"`
	// Human-readable name.
	Name string `json:"name"`
	// Posts classified as neutral.
	NeutralPosts int64 `json:"neutral_posts"`
	// Matching post count over the requested window.
	Posts int64 `json:"posts"`
	// Fractional change from posts_prior to posts_recent; positive values indicate growth.
	PostsDelta float64 `json:"posts_delta"`
	// Matching posts in the first half of the requested window.
	PostsPrior int64 `json:"posts_prior"`
	// Matching posts in the second half of the requested window.
	PostsRecent int64 `json:"posts_recent"`
	// Difference between sentiment_score for the shared conversation and the anchor's complete-window average.
	SentimentDelta float64 `json:"sentiment_delta"`
	// Signed sentiment score; positive is bullish and negative is bearish.
	SentimentScore float64 `json:"sentiment_score"`
	// Anchor posts that also mention this subject as a decimal fraction of all anchor posts in the window.
	Share float64 `json:"share"`
	// Canonical identifier for a non-asset person, account, or topic.
	SubjectID string `json:"subject_id"`
}

RelatedSubjectsResponseSubject models an object of the `social` service.

type ResponseMetadata

type ResponseMetadata struct {
	// StatusCode is the HTTP status of the response.
	StatusCode int
	// Headers is the full response header set.
	Headers http.Header
	// RequestID is the request id when the API sends one.
	RequestID string

	// RateLimitLimit is the requests-per-minute allowance on the key's plan.
	RateLimitLimit *int
	// RateLimitRemaining is the requests left in the current window.
	RateLimitRemaining *int
	// RateLimitReset is the seconds until the window resets.
	RateLimitReset *int
	// RetryAfterSeconds is the non-negative server delay on 429/503 responses.
	// HTTP dates are converted to seconds, rounding up.
	RetryAfterSeconds *int

	// CreditsCharged is the number of credits the request cost (0 on errors).
	CreditsCharged *int64
	// CreditsRemaining is the spendable balance after the call.
	CreditsRemaining *int64

	// PaymentReceipt is the raw PAYMENT-RESPONSE receipt header returned by
	// the x402 surface after settlement; nil on account-mode calls.
	PaymentReceipt []byte
}

ResponseMetadata carries the HTTP context of an API response: status, headers, and the parsed rate-limit / credit / payment figures Nebula reports on every call.

type RetryPolicy

type RetryPolicy struct {
	// MaxAttempts is the total number of tries including the first. 1 disables
	// retries; values < 1 are normalized to 1.
	MaxAttempts int
	// BaseDelay is the first backoff delay; each attempt doubles it up to
	// MaxDelay, with +/-25% jitter.
	BaseDelay time.Duration
	// MaxDelay caps the computed backoff including jitter, but not server hints.
	MaxDelay time.Duration
}

RetryPolicy configures automatic retries of idempotent GET requests. Retries happen only on transient transport errors, HTTP 429, and HTTP 503 (and other 5xx marked transient by the server contract). POST requests and deterministic 4xx failures are never retried automatically.

type ScreenerRequest

type ScreenerRequest struct {
	Kind                 *Kind
	AssetClass           *AssetClass
	Clusters             []string
	Sort                 *ScreenerSort
	Order                *SortOrder
	Limit                *int
	MinShare             *float64
	MaxShare             *float64
	MinShareChange       *float64
	MaxShareChange       *float64
	MinPosts             *int
	MinNetBullishPosts   *int
	MaxNetBullishPosts   *int
	MinPriceChange24hPct *float64
	MaxPriceChange24hPct *float64
}

ScreenerRequest carries the query parameters of `screener` (GET /screener). Docs: https://docs.hiddensystems.ai/nebula/reference/get-screener/

type ScreenerResponse

type ScreenerResponse struct {
	BaseResponse
	// The market whose assets were ranked; absent for subjects.
	AssetClass *AssetClass `json:"asset_class"`
	// The author clusters whose posts were counted, canonicalised; empty when every author except bots was counted.
	Clusters []string `json:"clusters"`
	// UTC start of the ranked 24 hours. The comparison window is the 24 hours before it.
	From time.Time `json:"from"`
	// What was ranked: asset or subject, as requested.
	Kind Kind `json:"kind"`
	// All posts in the ranked population over the previous 24 hours.
	PreviousTotalPosts int64 `json:"previous_total_posts"`
	// Ranked results, best first.
	Results []ScreenerResponseResult `json:"results"`
	// UTC end of the ranked 24 hours: when the ranking was computed.
	To time.Time `json:"to"`
	// All posts in the ranked population over the 24 hours: the denominator of share.
	TotalPosts int64 `json:"total_posts"`
}

ScreenerResponse models an object of the `discovery` service.

type ScreenerResponseResult

type ScreenerResponseResult struct {
	// The asset's class: equity (stocks and ETFs), commodity, index, or crypto. Send it with asset_id on every asset-scoped request.
	AssetClass *AssetClass `json:"asset_class"`
	// Canonical public asset identifier: the ticker or market symbol for stocks, commodities, and indices, and the CoinGecko slug (or, without one, a numeric id) for crypto.
	AssetID *string `json:"asset_id"`
	// Posts classified as bearish.
	BearishPosts int64 `json:"bearish_posts"`
	// Posts classified as bullish.
	BullishPosts int64 `json:"bullish_posts"`
	// What the result is: asset (query it with asset_id and asset_class) or subject (query it with subject_id).
	Kind Kind `json:"kind"`
	// Human-readable name.
	Name string `json:"name"`
	// Posts classified as neutral.
	NeutralPosts int64 `json:"neutral_posts"`
	// This result's posts over the ranked 24 hours.
	Posts int64 `json:"posts"`
	// This result's posts in the immediately preceding window of equal length.
	PreviousPosts int64 `json:"previous_posts"`
	// Raw market-price change over 24 hours, in percentage points.
	PriceChange24hPct *float64 `json:"price_change_24h_pct"`
	// This result's posts as a fraction of all posts in the ranked population over the same 24 hours, from 0 to 1.
	Share float64 `json:"share"`
	// Change in share against the previous window, as a decimal fraction: 0.01 is one percentage point. Absent only when the population had no posts in the previous window.
	ShareChange *float64 `json:"share_change"`
	// The change in share relative to the previous window's share, in percent. Absent when the result had no posts in the previous window.
	ShareChangePct *float64 `json:"share_change_pct"`
	// Canonical identifier for a non-asset person, account, or topic.
	SubjectID *string `json:"subject_id"`
	// Display ticker or market symbol.
	Symbol *string `json:"symbol"`
}

ScreenerResponseResult models an object of the `discovery` service.

type ScreenerSort

type ScreenerSort string

ScreenerSort is the ranking measure of the screener.

const (
	ScreenerSortShare             ScreenerSort = "share"
	ScreenerSortShareChange       ScreenerSort = "share_change"
	ScreenerSortShareChangePct    ScreenerSort = "share_change_pct"
	ScreenerSortPosts             ScreenerSort = "posts"
	ScreenerSortNetBullishPosts   ScreenerSort = "net_bullish_posts"
	ScreenerSortPriceChange24hPct ScreenerSort = "price_change_24h_pct"
)

func ScreenerSortPtr

func ScreenerSortPtr(v ScreenerSort) *ScreenerSort

ScreenerSortPtr returns a pointer to v for optional request fields.

type SearchRequest

type SearchRequest struct {
	Query string
	Kind  *Kind
	Limit *int
}

SearchRequest carries the query parameters of `search` (GET /search). Docs: https://docs.hiddensystems.ai/nebula/reference/get-search/

type SearchResponse

type SearchResponse struct {
	BaseResponse
	// The free-text string that was resolved, echoed back.
	Query string `json:"query"`
	// Ranked results, best first.
	Results []SearchResponseResult `json:"results"`
}

SearchResponse models an object of the `lookup` service.

type SearchResponseResult

type SearchResponseResult struct {
	// The asset's class: equity (stocks and ETFs), commodity, index, or crypto. Send it with asset_id on every asset-scoped request.
	AssetClass *AssetClass `json:"asset_class"`
	// Canonical public asset identifier: the ticker or market symbol for stocks, commodities, and indices, and the CoinGecko slug (or, without one, a numeric id) for crypto.
	AssetID *string `json:"asset_id"`
	// What the result is: asset (query it with asset_id and asset_class) or subject (query it with subject_id).
	Kind Kind `json:"kind"`
	// The name or alias that matched the query, so you can show why a search landed where it did.
	MatchedAlias *string `json:"matched_alias"`
	// Human-readable name.
	Name string `json:"name"`
	// Canonical identifier for a non-asset person, account, or topic.
	SubjectID *string `json:"subject_id"`
	// Display ticker or market symbol.
	Symbol *string `json:"symbol"`
}

SearchResponseResult models an object of the `lookup` service.

type SentimentForecastRequest

type SentimentForecastRequest struct {
	Asset   *AssetRef
	Refresh *bool
}

SentimentForecastRequest carries the query parameters of `get_sentiment_forecast` (GET /forecasts/sentiment). Docs: https://docs.hiddensystems.ai/nebula/reference/get-forecasts-sentiment/

type SentimentForecastResponse

type SentimentForecastResponse struct {
	BaseResponse
	// UTC start of the forecast: the end of the last complete 15 minutes it was computed from. Null when the asset has never been scored.
	AsOf *time.Time `json:"as_of"`
	// The chance the sentiment signal is higher than current_sentiment_signal in 24 hours, from 0 to 1.
	ChanceHigher24h *float64 `json:"chance_higher_24h"`
	// True when chance_higher_24h is under 0.3 or over 0.7: the forecast leans clearly one way. Nearer 0.5, read it as no clear direction.
	ChanceHigher24hConfident *bool `json:"chance_higher_24h_confident"`
	// The chance the sentiment signal is higher than current_sentiment_signal in 72 hours, from 0 to 1.
	ChanceHigher72h *float64 `json:"chance_higher_72h"`
	// True when chance_higher_72h is under 0.3 or over 0.7: the forecast leans clearly one way. Nearer 0.5, read it as no clear direction.
	ChanceHigher72hConfident *bool `json:"chance_higher_72h_confident"`
	// The sentiment signal at as_of, on the /sentiment scale: bullish minus bearish posts over the trailing 24 hours, recent posts weighted more. Every path starts here, and the chances
	CurrentSentimentSignal *float64 `json:"current_sentiment_signal"`
	// How far ahead the forecast runs, in hours: always 72.
	HorizonHours int `json:"horizon_hours"`
	// Why the asset cannot be forecast: too_little_history, stale_data, or missing_price. Null when status is ok.
	Reason *ForecastReason `json:"reason"`
	// True when this request re-ran the forecast (refresh=true and the re-run finished in time); false when it is the latest scheduled forecast.
	Refreshed bool `json:"refreshed"`
	// 24 possible paths for the sentiment signal, each aligned with series. Draw them to show the spread of outcomes.
	SamplePaths [][]float64 `json:"sample_paths"`
	// The forecast every 4 hours from as_of: 18 steps, oldest first.
	Series []SentimentForecastResponseSeriesPoint `json:"series"`
	// ok, or not_forecastable when the asset cannot be forecast (the summary fields are then null and the series empty; reason says why).
	Status ForecastStatus `json:"status"`
	// 1 while sentiment is turning bullish (the last few hours lean clearly more bullish than the last day), -1 while it is turning bearish, 0 otherwise.
	Turning *int `json:"turning"`
}

SentimentForecastResponse models an object of the `forecasts` service.

func (*SentimentForecastResponse) IsForecastable

func (r *SentimentForecastResponse) IsForecastable() bool

IsForecastable reports whether the result contains a usable forecast.

type SentimentForecastResponseSeriesPoint

type SentimentForecastResponseSeriesPoint struct {
	// The bearish posts expected in this 4-hour step alone, bots excluded: like /sentiment's interval posts, not its trailing 24-hour counts.
	BearishPosts *SentimentForecastResponseSeriesPointBearishPosts `json:"bearish_posts"`
	// The bullish posts expected in this 4-hour step alone, bots excluded: like /sentiment's interval posts, not its trailing 24-hour counts.
	BullishPosts *SentimentForecastResponseSeriesPointBearishPosts `json:"bullish_posts"`
	// The neutral posts expected in this 4-hour step alone, bots excluded: like /sentiment's interval posts, not its trailing 24-hour counts.
	NeutralPosts *SentimentForecastResponseSeriesPointBearishPosts `json:"neutral_posts"`
	// The sentiment signal at the end of the step, on the /sentiment scale: where the line is likely to be.
	SentimentSignal *SentimentForecastResponseSeriesPointSentimentSignal `json:"sentiment_signal"`
	// UTC time the step ends: as_of plus 4, 8, ... 72 hours.
	Timestamp time.Time `json:"timestamp"`
	// The posts (bullish, bearish, and neutral together) expected in this 4-hour step alone, bots excluded: like /sentiment's interval posts, not its trailing 24-hour counts. Its percent
	TotalPosts *SentimentForecastResponseSeriesPointBearishPosts `json:"total_posts"`
}

SentimentForecastResponseSeriesPoint models an object of the `forecasts` service.

type SentimentForecastResponseSeriesPointBearishPosts

type SentimentForecastResponseSeriesPointBearishPosts struct {
	// The expected number of bearish posts in the step.
	Mean float64 `json:"mean"`
	// The 10th percentile of the bearish posts in the step.
	P10 float64 `json:"p10"`
	// The 25th percentile of the bearish posts in the step.
	P25 float64 `json:"p25"`
	// The 50th percentile of the bearish posts in the step.
	P50 float64 `json:"p50"`
	// The 75th percentile of the bearish posts in the step.
	P75 float64 `json:"p75"`
	// The 90th percentile of the bearish posts in the step.
	P90 float64 `json:"p90"`
}

SentimentForecastResponseSeriesPointBearishPosts models an object of the `forecasts` service.

type SentimentForecastResponseSeriesPointSentimentSignal

type SentimentForecastResponseSeriesPointSentimentSignal struct {
	// The expected sentiment signal at the end of the step.
	Mean float64 `json:"mean"`
	// The 10th percentile of the sentiment signal at the end of the step.
	P10 float64 `json:"p10"`
	// The 50th percentile of the sentiment signal at the end of the step.
	P50 float64 `json:"p50"`
	// The 90th percentile of the sentiment signal at the end of the step.
	P90 float64 `json:"p90"`
	// 21 quantiles of the sentiment signal at the end of the step: the 0th, 5th, 10th, ... 100th percentiles, lowest first. Interpolate between them for the chance of landing in any rang
	Quantiles []float64 `json:"quantiles"`
}

SentimentForecastResponseSeriesPointSentimentSignal models an object of the `forecasts` service.

type SentimentRequest

type SentimentRequest struct {
	Asset *AssetRef
	// AssetClass selects the aggregate market when Asset and Subject are nil.
	AssetClass  *AssetClass
	Subject     *SubjectRef
	Hours       *int
	Granularity *Granularity
	Clusters    []string
}

SentimentRequest carries the query parameters of `get_sentiment` (GET /sentiment). Docs: https://docs.hiddensystems.ai/nebula/reference/get-sentiment/

type SentimentResponse

type SentimentResponse struct {
	BaseResponse
	// The same measure for other author groups: bots, and top_callers when that population is available. The non-bot population is series itself.
	Cohorts map[string][]SentimentResponseCohortsEntry `json:"cohorts"`
	// Chronologically ordered observations.
	Series []SentimentResponseCohortsEntry `json:"series"`
}

SentimentResponse models an object of the `social` service.

type SentimentResponseCohorts

type SentimentResponseCohorts struct {
}

SentimentResponseCohorts models an object of the `social` service.

type SentimentResponseCohortsEntry

type SentimentResponseCohortsEntry struct {
	// Bearish posts over the trailing 24 hours ending at this point; interval_bearish_posts is the bucket's.
	BearishPosts float64 `json:"bearish_posts"`
	// Bullish posts over the trailing 24 hours ending at this point; interval_bullish_posts is the bucket's.
	BullishPosts float64 `json:"bullish_posts"`
	// Bearish posts in this emitted time bucket.
	IntervalBearishPosts *float64 `json:"interval_bearish_posts"`
	// Bullish posts in this emitted time bucket.
	IntervalBullishPosts *float64 `json:"interval_bullish_posts"`
	// Neutral posts in this emitted time bucket.
	IntervalNeutralPosts *float64 `json:"interval_neutral_posts"`
	// Posts in this emitted time bucket, before lookback accumulation.
	IntervalPosts *float64 `json:"interval_posts"`
	// Neutral posts over the trailing 24 hours ending at this point; interval_neutral_posts is the bucket's.
	NeutralPosts float64 `json:"neutral_posts"`
	// Decay-weighted net bullish posts: bullish minus bearish. Positive is bullish, negative is bearish, and magnitude grows with activity.
	SentimentSignal float64 `json:"sentiment_signal"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
	// Posts over the trailing 24 hours ending at this point, not this bucket alone; interval_posts is the bucket's.
	TotalPosts float64 `json:"total_posts"`
}

SentimentResponseCohortsEntry models an object of the `social` service.

type SentimentTimeframesRequest

type SentimentTimeframesRequest struct {
	Asset       *AssetRef
	Subject     *SubjectRef
	Hours       *int
	Granularity *Granularity
}

SentimentTimeframesRequest carries the query parameters of `get_sentiment_timeframes` (GET /sentiment/timeframes). Docs: https://docs.hiddensystems.ai/nebula/reference/get-sentiment-timeframes/

type SentimentTimeframesResponse

type SentimentTimeframesResponse struct {
	BaseResponse
	// Latest sentiment reading for each available timeframe horizon.
	Current map[string]float64 `json:"current"`
	// Methodology and request-window metadata needed to interpret the response.
	Metadata *SentimentTimeframesResponseMetadata `json:"metadata"`
	// Sentiment series keyed by short_term, medium_term, and long_term horizon.
	Series map[string][]SentimentTimeframesResponseSeriesEntry `json:"series"`
}

SentimentTimeframesResponse models an object of the `social` service.

type SentimentTimeframesResponseCurrent

type SentimentTimeframesResponseCurrent struct {
}

SentimentTimeframesResponseCurrent models an object of the `social` service.

type SentimentTimeframesResponseMetadata

type SentimentTimeframesResponseMetadata struct {
	// UTC time at which the metric was calculated.
	AsOf *time.Time `json:"as_of"`
	// Short name for the calculation method.
	Calculation *string `json:"calculation"`
	// Human-readable formula for the calculation.
	Formula *string `json:"formula"`
	// Despite the name, the length of the linear decay window, in hours: a post counts fully when new, half at the midpoint, and not at all once it is this old.
	HalfLifeHours *float64 `json:"half_life_hours"`
	// Historical lookback used by the calculation, in days.
	LookbackDays *int `json:"lookback_days"`
	// Published scale or interpretation of the metric.
	Scale *string `json:"scale"`
}

SentimentTimeframesResponseMetadata models an object of the `social` service.

type SentimentTimeframesResponseSeries

type SentimentTimeframesResponseSeries struct {
}

SentimentTimeframesResponseSeries models an object of the `social` service.

type SentimentTimeframesResponseSeriesEntry

type SentimentTimeframesResponseSeriesEntry struct {
	// Posts in this emitted time bucket, before lookback accumulation.
	IntervalPosts *float64 `json:"interval_posts"`
	// Decay-weighted net bullish posts: bullish minus bearish. Positive is bullish, negative is bearish, and magnitude grows with activity.
	SentimentSignal float64 `json:"sentiment_signal"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
	// Post count over the metric's active lookback window.
	TotalPosts *float64 `json:"total_posts"`
}

SentimentTimeframesResponseSeriesEntry models an object of the `social` service.

type SocialMomentumRequest

type SocialMomentumRequest struct {
	Asset *AssetRef
	// AssetClass selects the aggregate market when Asset and Subject are nil.
	AssetClass  *AssetClass
	Subject     *SubjectRef
	Hours       *int
	Granularity *Granularity
	Clusters    []string
}

SocialMomentumRequest carries the query parameters of `get_social_momentum` (GET /social-momentum). Docs: https://docs.hiddensystems.ai/nebula/reference/get-social-momentum/

type SocialMomentumResponse

type SocialMomentumResponse struct {
	BaseResponse
	// Social-momentum series keyed by canonical author-cluster identifier.
	Clusters map[string][]SocialMomentumResponseClustersEntry `json:"clusters"`
}

SocialMomentumResponse models an object of the `social` service.

type SocialMomentumResponseClusters

type SocialMomentumResponseClusters struct {
}

SocialMomentumResponseClusters models an object of the `social` service.

type SocialMomentumResponseClustersEntry

type SocialMomentumResponseClustersEntry struct {
	// Arithmetic mean of the posts' sentiment scores, on the −100 (very bearish) to +100 (very bullish) scale.
	AverageSentimentScore float64 `json:"average_sentiment_score"`
	// Posts classified as bearish.
	BearishPosts int64 `json:"bearish_posts"`
	// Posts classified as bullish.
	BullishPosts int64 `json:"bullish_posts"`
	// Posts classified as neutral.
	NeutralPosts int64 `json:"neutral_posts"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
	// Post count over the metric's active lookback window.
	TotalPosts int64 `json:"total_posts"`
	// Distinct posting accounts in the bucket; at coarser-than-hourly granularity this is an upper bound summed from hourly counts.
	UniquePosters int64 `json:"unique_posters"`
}

SocialMomentumResponseClustersEntry models an object of the `social` service.

type SocialService

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

func (*SocialService) Emotions

Emotions - Emotion distribution. GET /emotions Docs: https://docs.hiddensystems.ai/nebula/reference/get-emotions/

func (*SocialService) Mindshare

Mindshare - Mindshare. GET /mindshare Docs: https://docs.hiddensystems.ai/nebula/reference/get-mindshare/

func (*SocialService) RelatedSubjects

RelatedSubjects - Related subjects. GET /related-subjects Docs: https://docs.hiddensystems.ai/nebula/reference/get-related-subjects/

func (*SocialService) Sentiment

Sentiment - Sentiment. GET /sentiment Docs: https://docs.hiddensystems.ai/nebula/reference/get-sentiment/

func (*SocialService) SentimentTimeframes

SentimentTimeframes - Sentiment by timeframe. GET /sentiment/timeframes Docs: https://docs.hiddensystems.ai/nebula/reference/get-sentiment-timeframes/

func (*SocialService) SocialMomentum

SocialMomentum - Social momentum. GET /social-momentum Docs: https://docs.hiddensystems.ai/nebula/reference/get-social-momentum/

type SocialVolumeIndexRequest

type SocialVolumeIndexRequest struct {
	Asset *AssetRef
	Hours *int
}

SocialVolumeIndexRequest carries the query parameters of `get_social_volume_index` (GET /social-volume-index). Docs: https://docs.hiddensystems.ai/nebula/reference/get-social-volume-index/

type SocialVolumeIndexResponse

type SocialVolumeIndexResponse struct {
	BaseResponse
	// Chronologically ordered observations.
	Series []SocialVolumeIndexResponseSeriesPoint `json:"series"`
}

SocialVolumeIndexResponse models an object of the `market sentiment` service.

type SocialVolumeIndexResponseSeriesPoint

type SocialVolumeIndexResponseSeriesPoint struct {
	// The asset's posts on the day itself, bots left out.
	Posts float64 `json:"posts"`
	// The asset's posts over the trailing 7 days as a multiple of its median 7-day post count over the previous 90 days; 1 is usual.
	SocialRelative float64 `json:"social_relative"`
	// UTC RFC 3339 timestamp for the observation or bucket start.
	Timestamp time.Time `json:"timestamp"`
	// The asset's dollar trading volume over the trailing 7 days as a multiple of its median 7-day volume over the previous 90 days; 1 is usual.
	TradingRelative float64 `json:"trading_relative"`
	// From 0 to 100: 50 means trading and conversation are equally elevated against their normal; above 50 trading is ahead of the conversation, below 50 the conversation is ahead of tra
	VolumeIndex float64 `json:"volume_index"`
	// The asset's dollar trading volume on the day itself; 0 on a day without trading, such as a weekend for a stock.
	VolumeUSD float64 `json:"volume_usd"`
}

SocialVolumeIndexResponseSeriesPoint models an object of the `market sentiment` service.

type SocialVolumeProfileRequest

type SocialVolumeProfileRequest struct {
	Asset    *AssetRef
	Hours    *int
	Bins     *int
	Clusters []string
}

SocialVolumeProfileRequest carries the query parameters of `get_social_volume_profile` (GET /social-volume-profile). Docs: https://docs.hiddensystems.ai/nebula/reference/get-social-volume-profile/

type SocialVolumeProfileResponse

type SocialVolumeProfileResponse struct {
	BaseResponse
	// Price bins ordered from low to high.
	Bins []SocialVolumeProfileResponseBin `json:"bins"`
	// Post count in the busiest price bin.
	MaximumPostsInBin float64 `json:"maximum_posts_in_bin"`
	// Highest profile price in US dollars.
	MaximumPriceUSD float64 `json:"maximum_price_usd"`
	// Methodology and request-window metadata needed to interpret the response.
	Metadata *SocialVolumeProfileResponseMetadata `json:"metadata"`
	// Lowest profile price in US dollars.
	MinimumPriceUSD float64 `json:"minimum_price_usd"`
	// Zero-based index of the busiest bin; absent when the profile is empty.
	PointOfControlBinIndex *int `json:"point_of_control_bin_index"`
	// Post count over the metric's active lookback window.
	TotalPosts float64 `json:"total_posts"`
}

SocialVolumeProfileResponse models an object of the `market sentiment` service.

type SocialVolumeProfileResponseBin

type SocialVolumeProfileResponseBin struct {
	// How evenly activity is split between directions, from 0 to 1.
	BalanceScore float64 `json:"balance_score"`
	// Posts classified as bearish.
	BearishPosts float64 `json:"bearish_posts"`
	// Bearish share of directional posts in this bin, from 0 to 1.
	BearishShare float64 `json:"bearish_share"`
	// Posts classified as bullish.
	BullishPosts float64 `json:"bullish_posts"`
	// Bullish share of directional posts in this bin, from 0 to 1.
	BullishShare float64 `json:"bullish_share"`
	// How slowly price moved while in the bin, from 0 to 1.
	CompressionScore float64 `json:"compression_score"`
	// Directional post imbalance (bullish − bearish) / (bullish + bearish), from −1 to 1; absent with no directional posts.
	DirectionalImbalance *float64 `json:"directional_imbalance"`
	// True for the bin containing the greatest post activity.
	IsPointOfControl bool `json:"is_point_of_control"`
	// Posts classified as neutral.
	NeutralPosts float64 `json:"neutral_posts"`
	// Exclusive upper edge of the price bin in US dollars.
	PriceHighUSD float64 `json:"price_high_usd"`
	// Inclusive lower edge of the price bin in US dollars.
	PriceLowUSD float64 `json:"price_low_usd"`
	// Midpoint of the price bin in US dollars.
	PriceMidUSD float64 `json:"price_mid_usd"`
	// Composite prominence score for the bin, from 0 to 1.
	SignificanceScore float64 `json:"significance_score"`
	// Post count over the metric's active lookback window.
	TotalPosts float64 `json:"total_posts"`
	// Post count relative to the busiest bin, from 0 to 1.
	TotalShare float64 `json:"total_share"`
	// Separate times the market price entered this bin during the window.
	VisitCount int `json:"visit_count"`
}

SocialVolumeProfileResponseBin models an object of the `market sentiment` service.

type SocialVolumeProfileResponseMetadata

type SocialVolumeProfileResponseMetadata struct {
	// UTC time at which the metric was calculated.
	AsOf *time.Time `json:"as_of"`
	// Number of requested price bins.
	BinCount int `json:"bin_count"`
	// Results keyed or grouped by canonical author-cluster identifier.
	Clusters []string `json:"clusters"`
	// Lookback window represented by the response, in hours.
	Hours int `json:"hours"`
	// Sentiment buckets successfully matched to a market price.
	PricedBuckets int `json:"priced_buckets"`
	// Sentiment buckets omitted because no nearby market price was available.
	UnpricedBuckets int `json:"unpriced_buckets"`
}

SocialVolumeProfileResponseMetadata models an object of the `market sentiment` service.

type SortOrder

type SortOrder string

SortOrder is a result ordering direction.

const (
	SortOrderDesc SortOrder = "desc"
	SortOrderAsc  SortOrder = "asc"
)

func SortOrderPtr

func SortOrderPtr(v SortOrder) *SortOrder

SortOrderPtr returns a pointer to v for optional request fields.

type StreamError

type StreamError struct {
	Op  string
	Err error
}

StreamError terminates a chat stream abnormally (malformed event, transport drop, or an API error frame).

func (*StreamError) Error

func (e *StreamError) Error() string

func (*StreamError) Unwrap

func (e *StreamError) Unwrap() error

type SubjectRef

type SubjectRef struct {
	ID string
}

SubjectRef selects one non-asset person, account, or topic by subject_id.

type ThinkingMode

type ThinkingMode string

ThinkingMode selects the Agent reasoning mode.

const (
	ThinkingModeAuto ThinkingMode = "auto"
	ThinkingModeDeep ThinkingMode = "deep"
)

func ThinkingModePtr

func ThinkingModePtr(v ThinkingMode) *ThinkingMode

ThinkingModePtr returns a pointer to v for optional request fields.

type TopMomentumRequest

type TopMomentumRequest struct {
	Kind       *Kind
	AssetClass *AssetClass
	Clusters   []string
	Limit      *int
}

TopMomentumRequest carries the query parameters of `get_top_momentum` (GET /top-momentum). Docs: https://docs.hiddensystems.ai/nebula/reference/get-top-momentum/

type TopTrendingRequest

type TopTrendingRequest struct {
	Kind       *Kind
	AssetClass *AssetClass
	Clusters   []string
	Limit      *int
}

TopTrendingRequest carries the query parameters of `get_top_trending` (GET /top-trending). Docs: https://docs.hiddensystems.ai/nebula/reference/get-top-trending/

type TransportError

type TransportError struct {
	Op  string
	Err error
}

TransportError wraps network-level failures (DNS, TLS, timeouts, refused connections) that produced no HTTP response.

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) Is

func (e *TransportError) Is(target error) bool

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

type ValidationError

type ValidationError struct {
	Op    string
	Field string
	Msg   string
}

ValidationError is raised before the network call when a request breaks a documented client-side rule (required pair, range, enum, exclusivity).

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Is

func (e *ValidationError) Is(target error) bool

Is supports errors.Is(err, ErrValidation).

Directories

Path Synopsis
tools
querygen command
querygen derives query validation rules from the vendored OpenAPI contract.
querygen derives query validation rules from the vendored OpenAPI contract.
Package x402 is the opt-in adapter that plugs the official x402 v2 client (github.com/x402-foundation/x402/go/v2) into the Nebula SDK.
Package x402 is the opt-in adapter that plugs the official x402 v2 client (github.com/x402-foundation/x402/go/v2) into the Nebula SDK.

Jump to

Keyboard shortcuts

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