### Import WebSocket Client Packages Source: https://github.com/massive-com/client-go/blob/master/README.md Import the necessary WebSocket client and models packages to get started with real-time data. ```go import ( massivews "github.com/massive-com/client-go/v3/websocket" "github.com/massive-com/client-go/v3/websocket/models" ) ``` -------------------------------- ### Download and Install Dependencies Source: https://github.com/massive-com/client-go/blob/master/README.md Ensures the go.mod file reflects all dependencies used in the project by downloading and installing them. ```bash go mod tidy ``` -------------------------------- ### Create a WebSocket Client Source: https://context7.com/massive-com/client-go/llms.txt Details on how to create a WebSocket client using `massivews.New`. It covers the necessary configuration options such as `APIKey`, `Feed`, `Market`, and optional parameters like `Log` and `MaxRetries`. The example shows client creation, error handling, and setting up a `ReconnectCallback`. ```APIDOC ## massivews.New — Create a WebSocket client Validates the `Config` and returns a ready-to-connect `*Client`. The connection itself is not opened until `Connect()` is called. Returns an error if `APIKey` is empty. ```go import ( massivews "github.com/massive-com/client-go/v3/websocket" "github.com/sirupsen/logrus" ) log := logrus.New() log.SetLevel(logrus.DebugLevel) c, err := massivews.New(massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.RealTime, // wss://socket.massive.com Market: massivews.Stocks, Log: log, // optional; any massivews.Logger implementation // MaxRetries: massivews.Ptr[uint64](5), // omit for infinite retries ReconnectCallback: func(err error) { if err != nil { log.Errorf("reconnect attempt failed: %v", err) } else { log.Info("reconnected successfully") } }, }) if err != nil { log.Fatal(err) } deffer c.Close() ``` ``` -------------------------------- ### (*Client).Connect Source: https://context7.com/massive-com/client-go/llms.txt Opens the WebSocket connection to the server. This method handles dialing, authentication, and starting internal goroutines for data processing. ```APIDOC ## `(*Client).Connect` — Open the WebSocket connection Dials the server using exponential back-off, authenticates with the API key, sends any pre-queued subscription messages, then starts the internal read/write/process goroutines. Must be called after `Subscribe()` calls (subscriptions can be registered before `Connect`). ```go c, _ := massivews.New(massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.RealTime, Market: massivews.Stocks, }) deferr c.Close() // Register subscriptions before connecting (optional but idiomatic) _ = c.Subscribe(massivews.StocksTrades, "SPY", "AAPL") _ = c.Subscribe(massivews.StocksQuotes, "SPY") if err := c.Connect(); err != nil { log.Fatal(err) } // Connection is now open; data flows into c.Output() ``` ``` -------------------------------- ### Get Stocks Aggregates Source: https://github.com/massive-com/client-go/blob/master/README.md Fetches daily aggregates for a given stock ticker with optional parameters for adjustment, sorting, and limit. Supports pagination. ```APIDOC ## GetStocksAggregatesWithResponse ### Description Fetches historical daily stock aggregates for a specified ticker symbol. This method supports custom parameters for filtering and sorting, and can be used with pagination. ### Method `GetStocksAggregatesWithResponse` ### Parameters #### Path Parameters - **ticker** (string) - Required - The stock ticker symbol (e.g., "AAPL"). - **multiplier** (int) - Required - The size of the timespan aggregates are aggregated into (e.g., 1 for daily, 5 for 5-minute). - **timespan** (string) - Required - The type of timespan aggregation (e.g., "day", "hour", "minute"). - **from** (string) - Required - The start date for the aggregate query (YYYY-MM-DD). - **to** (string) - Required - The end date for the aggregate query (YYYY-MM-DD). #### Query Parameters - **params** (*gen.GetStocksAggregatesParams) - Optional - A struct containing additional query parameters such as `Adjusted`, `Sort`, and `Limit`. - **Adjusted** (*bool) - Optional - Whether the results should be adjusted for splits and dividends. - **Sort** (string) - Required - The order in which to sort the results ('asc' or 'desc'). - **Limit** (*int) - Optional - The maximum number of results to return. ### Request Example ```go params := &gen.GetStocksAggregatesParams{ Adjusted: rest.Ptr(true), Sort: "asc", Limit: rest.Ptr(120), } resp, err := c.GetStocksAggregatesWithResponse(ctx, "AAPL", 1, gen.GetStocksAggregatesParamsTimespan("day"), "2025-11-03", "2025-11-28", params, ) ``` ### Response #### Success Response (200) - **resp** (*rest.Response) - The response object containing aggregate data. #### Response Example ```json { "ticker": "AAPL", "queryCount": 1, "resultsCount": 1, "adjusted": true, "results": [ { "t": 1730678400000, "o": 180.00, "h": 182.50, "l": 179.50, "c": 181.25, "v": 50000000, "vw": 181.00 } ], "next_url": "/v1/open-close/AAPL/1/day/2025-11-04/2025-11-28?adjusted=true&limit=120&sort=asc" } ``` ``` -------------------------------- ### Create REST Client with Options Source: https://context7.com/massive-com/client-go/llms.txt Initializes a REST client using `NewWithOptions`. Configure trace logging and pagination via options. Panics if no API key is found. ```go package main import ( "context" "fmt" "log" "github.com/massive-com/client-go/v3/rest" "github.com/massive-com/client-go/v3/rest/gen" ) func main() { // API key from environment variable MASSIVE_API_KEY or passed directly c := rest.NewWithOptions("YOUR_API_KEY", rest.WithTrace(true), // log every request URL, headers, and response headers rest.WithPagination(true), // iterator will follow next_url automatically ) _ = c // use client below _ = context.Background() _ = gen.GetStocksAggregatesParams{} fmt.Println("client ready") } // Output: client ready ``` -------------------------------- ### Create Project Directory and Navigate Source: https://github.com/massive-com/client-go/blob/master/README.md Commands to create a new project directory and change into it. ```bash mkdir myproject && cd myproject ``` -------------------------------- ### Create REST Client with Options Source: https://github.com/massive-com/client-go/blob/master/README.md Creates a new REST client instance with specified options like trace logging and pagination. ```go c := rest.NewWithOptions("YOUR_API_KEY", rest.WithTrace(false), // set true for full request/response logging rest.WithPagination(true), // enables automatic pagination via iterator ) ctx := context.Background() ``` -------------------------------- ### Create and Connect WebSocket Client Source: https://github.com/massive-com/client-go/blob/master/README.md Create a new WebSocket client with configuration options such as API key, feed type, and market. Ensure to close the client when done using `defer c.Close()` and handle connection errors. ```go // create a new client c, err := massivews.New(massivews.Config{ APIKey: "YOUR_API_KEY", Feed: massivews.RealTime, Market: massivews.Stocks, }) if err != nil { log.Fatal(err) } deferr c.Close() // the user of this client must close it // connect to the server if err := c.Connect(); err != nil { log.Error(err) return } ``` -------------------------------- ### Run Go Application Source: https://github.com/massive-com/client-go/blob/master/README.md Executes the Go application. ```bash go run main.go ``` -------------------------------- ### Initialize Go Module Source: https://github.com/massive-com/client-go/blob/master/README.md Initializes a new Go module, creating a go.mod file to manage dependencies. ```bash go mod init example ``` -------------------------------- ### rest.New / rest.NewWithOptions Source: https://context7.com/massive-com/client-go/llms.txt Creates a new REST client instance. `NewWithOptions` allows for custom configuration, while `New` is a backward-compatible alias with default settings. Both require an API key. ```APIDOC ## rest.New / rest.NewWithOptions ### Description Creates a new REST client instance. `NewWithOptions` allows for custom configuration, while `New` is a backward-compatible alias with default settings. Both require an API key. ### Method `rest.NewWithOptions(apiKey string, options ...rest.ClientOption)` `rest.New(apiKey string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Options (for NewWithOptions) - `rest.WithTrace(enable bool)`: Enable or disable request/response debug logging. - `rest.WithPagination(enable bool)`: Enable or disable automatic pagination. ### Request Example ```go package main import ( "context" "fmt" "log" "github.com/massive-com/client-go/v3/rest" "github.com/massive-com/client-go/v3/rest/gen" ) func main() { // API key from environment variable MASSIVE_API_KEY or passed directly c := rest.NewWithOptions("YOUR_API_KEY", rest.WithTrace(true), // log every request URL, headers, and response headers rest.WithPagination(true), // iterator will follow next_url automatically ) _ = c // use client below _ = context.Background() _ = gen.GetStocksAggregatesParams{} fmt.Println("client ready") } ``` ### Response #### Success Response (200) A configured REST client instance. #### Response Example ``` client ready ``` ``` -------------------------------- ### Connect to Massive WebSocket Source: https://context7.com/massive-com/client-go/llms.txt Establish a WebSocket connection using the configured client. Subscriptions should be registered before calling Connect. The connection uses exponential back-off for retries. Ensure to defer closing the client. ```go c, _ := massivews.New(massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.RealTime, Market: massivews.Stocks, }) defer c.Close() // Register subscriptions before connecting (optional but idiomatic) _ = c.Subscribe(massivews.StocksTrades, "SPY", "AAPL") _ = c.Subscribe(massivews.StocksQuotes, "SPY") if err := c.Connect(); err != nil { log.Fatal(err) } // Connection is now open; data flows into c.Output() ``` -------------------------------- ### Create WebSocket Client Source: https://context7.com/massive-com/client-go/llms.txt Initialize a WebSocket client using `massivews.New` with a `Config` struct. The connection is established upon calling `Connect()`. Ensure the `APIKey` is provided in the configuration. Optional parameters like `MaxRetries` and `ReconnectCallback` can be configured. ```go import ( massivews "github.com/massive-com/client-go/v3/websocket" "github.com/sirupsen/logrus" ) log := logrus.New() log.SetLevel(logrus.DebugLevel) c, err := massivews.New(massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.RealTime, // wss://socket.massive.com Market: massivews.Stocks, Log: log, // optional; any massivews.Logger implementation // MaxRetries: massivews.Ptr[uint64](5), // omit for infinite retries ReconnectCallback: func(err error) { if err != nil { log.Errorf("reconnect attempt failed: %v", err) } else { log.Info("reconnected successfully") } }, }) if err != nil { log.Fatal(err) } deffer c.Close() ``` -------------------------------- ### Configure Massive WebSocket Client Source: https://context7.com/massive-com/client-go/llms.txt Set up the configuration for the WebSocket client, including API key, feed, and market. RawData can be set to true to receive raw data or false for typed structs. MaxRetries can be set to nil for indefinite reconnection. ```go cfg := massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.RealTime, Market: massivews.Crypto, RawData: false, // deliver typed structs (default) BypassRawDataRouting: false, // only relevant when RawData=true MaxRetries: nil, // nil = reconnect indefinitely Log: nil, // nil = no logging ReconnectCallback: nil, } c, err := massivews.New(cfg) ``` -------------------------------- ### Subscribe to Launchpad Feed Values Source: https://context7.com/massive-com/client-go/llms.txt Connect to the LaunchpadFeed and subscribe to launchpad values for stocks. Requires API key and setting the LaunchpadFeed. ```go c, _ := massivews.New(massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.LaunchpadFeed, Market: massivews.Stocks, }) _ = c.Subscribe(massivews.StocksLaunchpadValue, "*") _ = c.Connect() // ... case models.LaunchpadValue: lv := out.(models.LaunchpadValue) // lv.Ticker, lv.Value, lv.Timestamp (nanoseconds) fmt.Printf("LV %s = %.4f\n", lv.Ticker, lv.Value) ``` -------------------------------- ### Create REST Client with Custom HTTP Client Source: https://github.com/massive-com/client-go/blob/master/README.md Creates a new REST client using a custom HTTP client implementation. ```go hc := http.Client{} // some custom HTTP client c := massive.NewWithClient("YOUR_API_KEY", hc) ``` -------------------------------- ### Enable Debug Mode for REST Client Source: https://github.com/massive-com/client-go/blob/master/README.md Enable debug/trace mode at client creation time by passing `rest.WithTrace(true)` to `rest.NewWithOptions`. This is useful for troubleshooting requests. ```go c := rest.NewWithOptions("YOUR_API_KEY", rest.WithTrace(true), // turn this on rest.WithPagination(true), ) ``` -------------------------------- ### Pointer Helper Functions Source: https://context7.com/massive-com/client-go/llms.txt Use `rest.Ptr[T]` and typed helpers like `rest.String`, `rest.Int`, `rest.Bool` to easily create pointers for optional API parameters, reducing boilerplate code. ```go params := &gen.GetStocksAggregatesParams{ Adjusted: rest.Ptr(true), // *bool Limit: rest.Ptr(120), // *int Sort: "asc", // string (not a pointer in this struct) } // Typed helpers also available: s := rest.String("AAPL") // *string i := rest.Int(500) // *int i64 := rest.Int64(1000) // *int64 f := rest.Float64(3.14) // *float64 b := rest.Bool(false) // *bool ``` -------------------------------- ### Subscribe to Business Fair Market Value (FMV) Source: https://context7.com/massive-com/client-go/llms.txt Connect to the BusinessFeed and subscribe to FairMarketValue data for stocks. Requires API key and setting the BusinessFeed. ```go c, _ := massivews.New(massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.BusinessFeed, Market: massivews.Stocks, }) _ = c.Subscribe(massivews.BusinessFairMarketValue, "*") _ = c.Connect() // ... case models.FairMarketValue: fmv := out.(models.FairMarketValue) // fmv.Ticker, fmv.FMV, fmv.Timestamp (nanoseconds) fmt.Printf("FMV %s = %.4f\n", fmv.Ticker, fmv.FMV) ``` -------------------------------- ### Subscribe to WebSocket Topics Source: https://context7.com/massive-com/client-go/llms.txt Subscribe to various data topics for different asset classes. Use '*' or omit tickers to subscribe to all tickers for a topic. Ensure the configured Market supports the requested topic. ```go // Subscribe to all stock second-aggregates _ = c.Subscribe(massivews.StocksSecAggs) // equivalent to passing "*" // Subscribe to minute-aggregates for specific tickers _ = c.Subscribe(massivews.StocksMinAggs, "TSLA", "GME", "NVDA") // Subscribe to trades for all options _ = c.Subscribe(massivews.OptionsTrades, "*") // Subscribe to all crypto trades _ = c.Subscribe(massivews.CryptoTrades) // Subscribe to Level 2 book for a specific crypto pair _ = c.Subscribe(massivews.CryptoL2Book, "BTC-USD") // Subscribe to all forex quotes _ = c.Subscribe(massivews.ForexQuotes) // Subscribe to Fair Market Value (requires BusinessFeed) _ = c.Subscribe(massivews.BusinessFairMarketValue, "*") // Subscribe to Launchpad values (requires LaunchpadFeed) _ = c.Subscribe(massivews.StocksLaunchpadValue, "*") ``` -------------------------------- ### Import REST API Client Packages Source: https://github.com/massive-com/client-go/blob/master/README.md Imports necessary packages for using the Massive REST API client. ```golang import ( "context" "fmt" "log" "github.com/massive-com/client-go/v3/rest" "github.com/massive-com/client-go/v3/rest/gen" ) ``` -------------------------------- ### Enable Pagination in REST Client Source: https://github.com/massive-com/client-go/blob/master/README.md Configures the REST client to automatically handle pagination by setting WithPagination to true. ```go c := rest.NewWithOptions("YOUR_API_KEY", rest.WithTrace(true), rest.WithPagination(true), // turn this on ) ``` -------------------------------- ### Set Massive API Key Environment Variable Source: https://github.com/massive-com/client-go/blob/master/README.md Commands to set the MASSIVE_API_KEY environment variable for authentication. ```bash export MASSIVE_API_KEY="" <- mac/linux xset MASSIVE_API_KEY "" <- windows ``` -------------------------------- ### Consume Streaming Data with (*Client).Output and (*Client).Error Source: https://context7.com/massive-com/client-go/llms.txt Subscribe to real-time stock trades, quotes, and aggregates. Errors are delivered on the Error() channel, and receiving a value indicates the connection is closed. The Output() channel provides typed data models. ```go import ( massivews "github.com/massive-com/client-go/v3/websocket" "github.com/massive-com/client-go/v3/websocket/models" "os" "os/signal" ) c, _ := massivews.New(massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.RealTime, Market: massivews.Stocks, }) deferr c.Close() _ = c.Subscribe(massivews.StocksTrades, "SPY") _ = c.Subscribe(massivews.StocksQuotes, "SPY") _ = c.Subscribe(massivews.StocksSecAggs, "SPY") _ = c.Connect() sigint := make(chan os.Signal, 1) signal.Notify(sigint, os.Interrupt) for { select { case <-sigint: return case err := <-c.Error(): log.Fatal(err) // auth failure or terminal reconnect exhaustion case out, more := <-c.Output(): if !more { return // channel closed — client was closed } switch v := out.(type) { case models.EquityAgg: fmt.Printf("[AGG] %s open=%.2f close=%.2f vol=%.0f\n", v.Symbol, v.Open, v.Close, v.Volume) case models.EquityTrade: fmt.Printf("[TRADE] %s price=%.2f size=%d\n", v.Symbol, v.Price, v.Size) case models.EquityQuote: fmt.Printf("[QUOTE] %s bid=%.2f ask=%.2f\n", v.Symbol, v.BidPrice, v.AskPrice) } } } // Example output: // [TRADE] SPY price=593.42 size=100 // [QUOTE] SPY bid=593.41 ask=593.43 // [AGG] SPY open=593.40 close=593.45 vol=18200 ``` -------------------------------- ### Pointer Helper Functions Source: https://context7.com/massive-com/client-go/llms.txt Provides utility functions like `rest.Ptr`, `rest.String`, `rest.Int`, etc., to easily create pointers to basic types. This is useful for setting optional parameters in API requests where pointer types are expected. ```APIDOC ## rest.Ptr[T] / rest.String / rest.Int / rest.Bool etc. — Pointer helpers The generated API types use pointer fields for all optional parameters. These helpers eliminate the boilerplate of taking the address of a literal. ```go params := &gen.GetStocksAggregatesParams{ Adjusted: rest.Ptr(true), // *bool Limit: rest.Ptr(120), // *int Sort: "asc", // string (not a pointer in this struct) } // Typed helpers also available: s := rest.String("AAPL") // *string i := rest.Int(500) // *int i64 := rest.Int64(1000) // *int64 f := rest.Float64(3.14) // *float64 b := rest.Bool(false) // *bool ``` ``` -------------------------------- ### Fetch Daily Stock Aggregates with Pagination Source: https://github.com/massive-com/client-go/blob/master/README.md Fetches daily stock aggregates for AAPL with full pagination and trace support. Requires API key and specific parameters. Ensure API key is set in MASSIVE_API_KEY environment variable or hardcoded. ```go package main import ( "context" "fmt" "log" "github.com/massive-com/client-go/v3/rest" "github.com/massive-com/client-go/v3/rest/gen" ) func main() { c := rest.NewWithOptions("YOUR_API_KEY", rest.WithTrace(false), rest.WithPagination(true), ) ctx := context.Background() params := &gen.GetStocksAggregatesParams{ Adjusted: rest.Ptr(true), Sort: "asc", Limit: rest.Ptr(120), } resp, err := c.GetStocksAggregatesWithResponse( ctx, "AAPL", 1, "day", "2026-02-16", "2026-02-20", params, ) if err != nil { log.Fatal(err) } if err := rest.CheckResponse(resp); err != nil { log.Fatal(err) } iter := rest.NewIteratorFromResponse(c, resp) for iter.Next() { item := iter.Item() fmt.Printf("%+v\n", item) } if err := iter.Err(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Enable Request/Response Debug Logging Source: https://context7.com/massive-com/client-go/llms.txt Enables detailed logging of HTTP requests and responses, including URLs, headers (with Authorization redacted), and response headers. Useful for debugging. ```go c := rest.NewWithOptions(os.Getenv("MASSIVE_API_KEY"), rest.WithTrace(true), rest.WithPagination(true), ) // All subsequent API calls print: // Request URL: https://api.massive.com/v2/aggs/ticker/AAPL/range/1/day/2025-11-03/2025-11-28?adjusted=true&limit=120&sort=asc // Request Headers: map[Authorization:[Bearer REDACTED] User-Agent:[massive-go-test]] // Response Headers: map[Content-Type:[application/json] Date:[...] ...] ``` -------------------------------- ### Consume Streaming Data with Output() and Error() Source: https://context7.com/massive-com/client-go/llms.txt The `Output()` method returns a read-only channel for streaming data, with values typed according to market and event. The `Error()` method delivers fatal errors, such as authentication failures, and signals connection closure upon receiving a value. ```APIDOC ## `(*Client).Output` / `(*Client).Error` — Consume streaming data `Output()` returns a read-only channel of `any`. Each value is a typed model struct determined by the market and event type. `Error()` delivers fatal errors (e.g., authentication failure); receiving from it means the connection is closed. ```go import ( massivews "github.com/massive-com/client-go/v3/websocket" "github.com/massive-com/client-go/v3/websocket/models" "os" "os/signal" ) c, _ := massivews.New(massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.RealTime, Market: massivews.Stocks, }) def c.Close() _ = c.Subscribe(massivews.StocksTrades, "SPY") _ = c.Subscribe(massivews.StocksQuotes, "SPY") _ = c.Subscribe(massivews.StocksSecAggs, "SPY") _ = c.Connect() sigint := make(chan os.Signal, 1) signal.Notify(sigint, os.Interrupt) for { select { case <-sigint: return case err := <-c.Error(): log.Fatal(err) // auth failure or terminal reconnect exhaustion case out, more := <-c.Output(): if !more { return // channel closed — client was closed } switch v := out.(type) { case models.EquityAgg: fmt.Printf("[AGG] %s open=%.2f close=%.2f vol=%.0f\n", v.Symbol, v.Open, v.Close, v.Volume) case models.EquityTrade: fmt.Printf("[TRADE] %s price=%.2f size=%d\n", v.Symbol, v.Price, v.Size) case models.EquityQuote: fmt.Printf("[QUOTE] %s bid=%.2f ask=%.2f\n", v.Symbol, v.BidPrice, v.AskPrice) } } } // Example output: // [TRADE] SPY price=593.42 size=100 // [QUOTE] SPY bid=593.41 ask=593.43 // [AGG] SPY open=593.40 close=593.45 vol=18200 ``` ``` -------------------------------- ### Receive Raw JSON Messages Source: https://context7.com/massive-com/client-go/llms.txt Configure the client with RawData: true to receive messages as json.RawMessage. This bypasses typed routing for data messages. ```go c, _ := massivews.New(massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.RealTime, Market: massivews.Stocks, RawData: true, BypassRawDataRouting: false, // deliver json.RawMessage per data message }) _ = c.Subscribe(massivews.StocksTrades, "AAPL") _ = c.Connect() for out := range c.Output() { raw := out.(json.RawMessage) fmt.Println(string(raw)) // {"ev":"T","sym":"AAPL","p":213.45,"s":100,"t":1732300800000,...} } ``` -------------------------------- ### massivews.Config Source: https://context7.com/massive-com/client-go/llms.txt Configuration struct for the WebSocket client. Allows selection of feed, market, and other connection parameters. ```APIDOC ## `massivews.Config` — WebSocket client configuration Full configuration struct for the WebSocket client. `Feed` selects the streaming endpoint; `Market` selects the asset class path appended to the feed URL. ```go // Available Feed constants: // massivews.RealTime → wss://socket.massive.com // massivews.Delayed → wss://delayed.massive.com // massivews.Nasdaq → wss://nasdaqfeed.massive.com // massivews.LaunchpadFeed → wss://launchpad.massive.com // massivews.BusinessFeed → wss://business.massive.com // massivews.StarterFeed → wss://starterfeed.massive.com // (and many more business/delayed variants) // Available Market constants: // massivews.Stocks, Options, Forex, Crypto, Indices // massivews.Futures, FuturesCME, FuturesCBOT, FuturesNYMEX, FuturesCOMEX cfg := massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.RealTime, Market: massivews.Crypto, RawData: false, // deliver typed structs (default) BypassRawDataRouting: false, // only relevant when RawData=true MaxRetries: nil, // nil = reconnect indefinitely Log: nil, // nil = no logging ReconnectCallback: nil, } c, err := massivews.New(cfg) ``` ``` -------------------------------- ### Enable Automatic Pagination Source: https://context7.com/massive-com/client-go/llms.txt Configures whether the `Iterator` automatically fetches subsequent pages using `next_url`. When disabled, only the first page of results is returned. ```go // Pagination on (default): iterator follows all pages c := rest.NewWithOptions("YOUR_API_KEY", rest.WithPagination(true)) // Pagination off: only the first page is returned cSingle := rest.NewWithOptions("YOUR_API_KEY", rest.WithPagination(false)) ``` -------------------------------- ### Handle Crypto Market Data Types Source: https://context7.com/massive-com/client-go/llms.txt Use type assertions to process CryptoTrade, CryptoQuote, and Level2Book messages from the crypto feed. ```go case models.CryptoTrade: ct := out.(models.CryptoTrade) fmt.Printf("CRYPTO TRADE %s @ %.2f x %.4f\n", ct.Pair, ct.Price, ct.Size) case models.CryptoQuote: cq := out.(models.CryptoQuote) fmt.Printf("CRYPTO QUOTE %s bid=%.2f ask=%.2f\n", cq.Pair, cq.BidPrice, cq.AskPrice) case models.Level2Book: l2 := out.(models.Level2Book) // l2.BidPrices and l2.AskPrices are [][]float64 (price, size pairs), depth up to 100 if len(l2.BidPrices) > 0 { fmt.Printf("L2 %s best bid=%.2f x %.4f\n", l2.Pair, l2.BidPrices[0][0], l2.BidPrices[0][1]) } ``` -------------------------------- ### Subscribe to WebSocket Topics and Process Data Source: https://github.com/massive-com/client-go/blob/master/README.md Subscribe to topics like `massivews.StocksSecAggs` or specific tickers. Process incoming data by reading from the `c.Output()` channel and checking for errors on the `c.Error()` channel. The client automatically handles reconnections and resubscriptions. ```go // passing a topic by itself will subscribe to all tickers if err := c.Subscribe(massivews.StocksSecAggs); err != nil { log.Fatal(err) } if err := c.Subscribe(massivews.StocksTrades, "TSLA", "GME"); err != nil { log.Fatal(err) } for { select { case err := <-c.Error(): // check for any fatal errors (e.g. auth failed) log.Fatal(err) case out, more := <-c.Output(): // read the next data message if !more { return } switch out.(type) { case models.EquityAgg: log.Print(out) // do something with the agg case models.EquityTrade: log.Print(out) // do something with the trade } } } ``` -------------------------------- ### Gracefully Close WebSocket Connection with (*Client).Close Source: https://context7.com/massive-com/client-go/llms.txt Use `defer c.Close()` to ensure the WebSocket connection is properly closed, including sending a close frame and cleaning up goroutines. This is safe to call even if errors occur during client initialization or connection. ```go c, err := massivews.New(massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.RealTime, Market: massivews.Indices, }) if err != nil { log.Fatal(err) } deferr c.Close() // always close, even on error paths _ = c.Subscribe(massivews.IndexValue, "*") if err := c.Connect(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Generated `*WithResponse` Methods Source: https://context7.com/massive-com/client-go/llms.txt Explains that every endpoint in the Massive OpenAPI spec has a corresponding generated `*WithResponse` method on the `*Client`. These methods simplify API calls by encoding parameters directly into the method signature and using a `*Params` struct for optional parameters. ```APIDOC ## Generated `*WithResponse` methods — Call any REST endpoint Every endpoint in the Massive OpenAPI spec has a generated `*WithResponse` method on the `*Client`. The method signature encodes required path/query parameters; optional parameters are grouped in a `*Params` struct. ```go ctx := context.Background() c := rest.NewWithOptions("YOUR_API_KEY", rest.WithPagination(true)) // --- Stocks: daily OHLCV aggregates --- aggResp, err := c.GetStocksAggregatesWithResponse(ctx, "AAPL", // ticker 1, // multiplier "day", // timespan "2025-11-03", "2025-11-28", &gen.GetStocksAggregatesParams{ Adjusted: rest.Ptr(true), Sort: "asc", Limit: rest.Ptr(120), }, ) if err != nil { log.Fatal(err) } if err := rest.CheckResponse(aggResp); err != nil { log.Fatal(err) } // --- Options: contract details --- optResp, err := c.GetOptionsContractWithResponse(ctx, "O:AAPL251219C00200000", &gen.GetOptionsContractParams{}, ) if err != nil { log.Fatal(err) } if err := rest.CheckResponse(optResp); err != nil { log.Fatal(err) } // --- Forex: grouped daily bars --- forexResp, err := c.GetForexGroupedDailyBarsWithResponse(ctx, "2025-11-05", &gen.GetForexGroupedDailyBarsParams{Adjusted: rest.Ptr(true)}), ) if err != nil { log.Fatal(err) } if err := rest.CheckResponse(forexResp); err != nil { log.Fatal(err) } fmt.Println("all three calls succeeded") ``` ``` -------------------------------- ### (*Client).Subscribe Source: https://context7.com/massive-com/client-go/llms.txt Subscribes to a specified data topic and optionally specific tickers. Subscriptions are cached for automatic re-connection. ```APIDOC ## `(*Client).Subscribe` — Subscribe to a topic Sends a subscription control message to the server and caches the subscription for automatic re-subscription after reconnect. Passing no tickers (or `"*"`) subscribes to all tickers for that topic. Returns an error if the topic is not supported by the configured `Market`. ```go // Subscribe to all stock second-aggregates _ = c.Subscribe(massivews.StocksSecAggs) // equivalent to passing "*" // Subscribe to minute-aggregates for specific tickers _ = c.Subscribe(massivews.StocksMinAggs, "TSLA", "GME", "NVDA") // Subscribe to trades for all options _ = c.Subscribe(massivews.OptionsTrades, "*") // Subscribe to all crypto trades _ = c.Subscribe(massivews.CryptoTrades) // Subscribe to Level 2 book for a specific crypto pair _ = c.Subscribe(massivews.CryptoL2Book, "BTC-USD") // Subscribe to all forex quotes _ = c.Subscribe(massivews.ForexQuotes) // Subscribe to Fair Market Value (requires BusinessFeed) _ = c.Subscribe(massivews.BusinessFairMarketValue, "*") // Subscribe to Launchpad values (requires LaunchpadFeed) _ = c.Subscribe(massivews.StocksLaunchpadValue, "*") ``` ``` -------------------------------- ### Call Generated REST Endpoints Source: https://context7.com/massive-com/client-go/llms.txt Invoke any REST endpoint using its generated `*WithResponse` method on the `*Client`. Optional parameters are passed via a `*Params` struct. Ensure to check for errors after each call using `rest.CheckResponse`. ```go ctx := context.Background() c := rest.NewWithOptions("YOUR_API_KEY", rest.WithPagination(true)) // --- Stocks: daily OHLCV aggregates --- aggResp, err := c.GetStocksAggregatesWithResponse(ctx, "AAPL", // ticker 1, // multiplier "day", // timespan "2025-11-03", "2025-11-28", &gen.GetStocksAggregatesParams{ Adjusted: rest.Ptr(true), Sort: "asc", Limit: rest.Ptr(120), }, ) if err != nil { log.Fatal(err) } if err := rest.CheckResponse(aggResp); err != nil { log.Fatal(err) } // --- Options: contract details --- optResp, err := c.GetOptionsContractWithResponse(ctx, "O:AAPL251219C00200000", &gen.GetOptionsContractParams{}, ) if err != nil { log.Fatal(err) } if err := rest.CheckResponse(optResp); err != nil { log.Fatal(err) } // --- Forex: grouped daily bars --- forexResp, err := c.GetForexGroupedDailyBarsWithResponse(ctx, "2025-11-05", &gen.GetForexGroupedDailyBarsParams{Adjusted: rest.Ptr(true)}, ) if err != nil { log.Fatal(err) } if err := rest.CheckResponse(forexResp); err != nil { log.Fatal(err) } fmt.Println("all three calls succeeded") ``` -------------------------------- ### Iterate Paginated REST Results Source: https://context7.com/massive-com/client-go/llms.txt Use `rest.NewIteratorFromResponse` to create an iterator for paginated API responses. Call `iter.Next()` in a loop to fetch subsequent pages transparently. Check `iter.Err()` after the loop for any errors. `iter.Item()` returns the current row as `map[string]any`. ```go ctx := context.Background() c := rest.NewWithOptions("YOUR_API_KEY", rest.WithPagination(true)) params := &gen.GetStocksAggregatesParams{ Adjusted: rest.Ptr(true), Sort: "asc", Limit: rest.Ptr(50000), // max per page } resp, err := c.GetStocksAggregatesWithResponse(ctx, "TSLA", 1, "day", "2020-01-01", "2025-12-31", params) if err != nil { log.Fatal(err) } if err := rest.CheckResponse(resp); err != nil { log.Fatal(err) } iter := rest.NewIteratorFromResponse(c, resp) count := 0 for iter.Next() { bar := iter.Item() // map[string]any: keys "o","h","l","c","v","vw","t","n",... count++ if count <= 3 { fmt.Printf("open=%.2f close=%.2f volume=%.0f\n", bar["o"], bar["c"], bar["v"]) } } if err := iter.Err(); err != nil { log.Fatal(err) } fmt.Printf("total bars fetched: %d\n", count) // Example output: // open=430.26 close=443.01 volume=29681040 // open=441.75 close=451.54 volume=22483200 // open=448.50 close=432.12 volume=31027100 // total bars fetched: 1510 ``` -------------------------------- ### rest.WithTrace Source: https://context7.com/massive-com/client-go/llms.txt Configures the REST client to enable or disable debug logging for HTTP requests and responses. When enabled, details like request URL, headers, and response headers are printed to standard output. ```APIDOC ## rest.WithTrace ### Description Configures the REST client to enable or disable debug logging for HTTP requests and responses. When enabled, details like request URL, headers, and response headers are printed to standard output. Useful for diagnosing issues. ### Method `rest.WithTrace(enable bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go c := rest.NewWithOptions(os.Getenv("MASSIVE_API_KEY"), rest.WithTrace(true), rest.WithPagination(true), ) // All subsequent API calls print: // Request URL: https://api.massive.com/v2/aggs/ticker/AAPL/range/1/day/2025-11-03/2025-11-28?adjusted=true&limit=120&sort=asc // Request Headers: map[Authorization:[Bearer REDACTED] User-Agent:[massive-go-test]] // Response Headers: map[Content-Type:[application/json] Date:[...] ...] ``` ### Response #### Success Response (200) No direct response, modifies client behavior. #### Response Example None ``` -------------------------------- ### Call GetStocksAggregatesWithResponse Source: https://github.com/massive-com/client-go/blob/master/README.md Makes a call to the GetStocksAggregatesWithResponse endpoint with custom parameters. Note the 'Sort' field requirement. ```go // Example with custom params (note the Sort field requirement) params := &gen.GetStocksAggregatesParams{ Adjusted: rest.Ptr(true), Sort: "asc", Limit: rest.Ptr(120), } resp, err := c.GetStocksAggregatesWithResponse(ctx, "AAPL", 1, gen.GetStocksAggregatesParamsTimespan("day"), "2025-11-03", "2025-11-28", params, ) ``` -------------------------------- ### rest.WithPagination Source: https://context7.com/massive-com/client-go/llms.txt Configures the REST client to enable or disable automatic pagination. When enabled, the `Iterator` will automatically fetch subsequent pages using `next_url`. When disabled, the iterator stops after the first page. ```APIDOC ## rest.WithPagination ### Description Configures the REST client to enable or disable automatic pagination. When enabled, the `Iterator` will automatically fetch subsequent pages using `next_url`. When disabled, the iterator stops after the first page. ### Method `rest.WithPagination(enable bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Pagination on (default): iterator follows all pages c := rest.NewWithOptions("YOUR_API_KEY", rest.WithPagination(true)) // Pagination off: only the first page is returned cSingle := rest.NewWithOptions("YOUR_API_KEY", rest.WithPagination(false)) ``` ### Response #### Success Response (200) No direct response, modifies client behavior. #### Response Example None ``` -------------------------------- ### Paginated Result Iteration Source: https://context7.com/massive-com/client-go/llms.txt Demonstrates how to use `rest.NewIteratorFromResponse` to iterate over paginated results from an API call. It shows fetching the first page, then looping through subsequent pages using `Iterator.Next()`, accessing the current item with `Iterator.Item()`, and checking for errors with `Iterator.Err()`. ```APIDOC ## rest.NewIteratorFromResponse / Iterator.Next / Iterator.Item — Paginated result iteration Extracts the first page and `next_url` from any generated `*Response` struct and returns an `Iterator`. Call `Next()` in a loop; it fetches additional pages transparently when pagination is enabled. `Item()` returns the current row as `map[string]any`. `Err()` must be checked after the loop. ```go ctx := context.Background() c := rest.NewWithOptions("YOUR_API_KEY", rest.WithPagination(true)) params := &gen.GetStocksAggregatesParams{ Adjusted: rest.Ptr(true), Sort: "asc", Limit: rest.Ptr(50000), // max per page } resp, err := c.GetStocksAggregatesWithResponse(ctx, "TSLA", 1, "day", "2020-01-01", "2025-12-31", params) if err != nil { log.Fatal(err) } if err := rest.CheckResponse(resp); err != nil { log.Fatal(err) } iter := rest.NewIteratorFromResponse(c, resp) count := 0 for iter.Next() { bar := iter.Item() // map[string]any: keys "o","h","l","c","v","vw","t","n",... count++ if count <= 3 { fmt.Printf("open=%.2f close=%.2f volume=%.0f\n", bar["o"], bar["c"], bar["v"]) } } if err := iter.Err(); err != nil { log.Fatal(err) } fmt.Printf("total bars fetched: %d\n", count) // Example output: // open=430.26 close=443.01 volume=29681040 // open=441.75 close=451.54 volume=22483200 // open=448.50 close=432.12 volume=31027100 // total bars fetched: 1510 ``` ``` -------------------------------- ### Handle Futures Market Data Types Source: https://context7.com/massive-com/client-go/llms.txt Process FuturesTrade, FuturesQuote, and FuturesAggregate messages when subscribed to FuturesCME market data. ```go c, _ := massivews.New(massivews.Config{ APIKey: os.Getenv("MASSIVE_API_KEY"), Feed: massivews.RealTime, Market: massivews.FuturesCME, }) _ = c.Subscribe(massivews.FutureTrades) _ = c.Subscribe(massivews.FutureQuotes) _ = c.Connect() // ... case models.FuturesTrade: ft := out.(models.FuturesTrade) fmt.Printf("FUTURES TRADE %s @ %.2f x %d\n", ft.Symbol, ft.Price, ft.Size) case models.FuturesQuote: fq := out.(models.FuturesQuote) fmt.Printf("FUTURES QUOTE %s bid=%.2f ask=%.2f\n", fq.Symbol, fq.BidPrice, fq.AskPrice) case models.FuturesAggregate: fa := out.(models.FuturesAggregate) fmt.Printf("FUTURES AGG %s O=%.2f C=%.2f V=%.0f\n", fa.Symbol, fa.Open, fa.Close, fa.Volume) ``` -------------------------------- ### models.EquityTrade Data Structure and Usage Source: https://context7.com/massive-com/client-go/llms.txt Represents individual stock or options trade data. Access fields like Symbol, Price, Size, and SequenceNumber when processing trade events. ```go case models.EquityTrade: t := out.(models.EquityTrade) // t.Symbol, t.Price, t.Size, t.Exchange, t.Tape, t.Conditions, t.Timestamp, t.SequenceNumber fmt.Printf("TRADE %s @ %.4f x %d (seq=%d)\n", t.Symbol, t.Price, t.Size, t.SequenceNumber) ```