client

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2024 License: MIT Imports: 20 Imported by: 0

README

Go SDK for Market Data v1.1

Access Financial Data with Ease

This is the official Go SDK for Market Data. It provides developers with a powerful, easy-to-use interface to obtain real-time and historical financial data. Ideal for building financial applications, trading bots, and investment strategies.

GoDoc Go Report Card Tests and linters Coverage License SDK Version GitHub go.mod Go version Lines of Code

Connect With The Market Data Community

Website Discord Twitter Helpdesk

Installation

To install the SDK, you can use the following command:

go get github.com/MarketDataApp/sdk-go

After installation, you can import it in your project like this:

import api "github.com/MarketDataApp/sdk-go"

Documentation

For advanced usage, review the module's complete documentation:

Get Started Quickly

1. Sign-Up For A Free Market Data Account

Signing up for a Market Data account is straightforward and grants you immediate access to our wealth of market data. We offer a free account tier that allows you to explore the capabilities of our API without any cost. Additionally, all our paid plans come with a free 30-day trial, giving you the opportunity to test out the advanced features and decide which plan best suits your needs.

  • To sign up, simply visit our website at Market Data. The process is quick and only requires your basic information. Once signed up, you can start using the API right away with the free tier or take advantage of the 30-day trial to explore our premium offerings.

Remember, no credit card is required for the free account tier, and you can upgrade, downgrade, or cancel your subscription at any time during or after the trial period.

2. Set-up Authentication

To authenticate with the Market Data API, you need to set your token, which should have been e-mailed to you when you first signed up for an account. If you do not have a token, request a new one from the Market Data Dashboard. Set the token in the environment variable MARKETDATA_TOKEN. Alternatively, you can hardcode it in your code, but please be aware that this is not secure and could pose a risk if your code is shared.

export MARKETDATA_TOKEN="<your_api_token>"   # mac/linux
setx MARKETDATA_TOKEN "<your_api_token>"     # windows
3. Make Your First Request

Check the examples folder for working examples for each request.

Get a stock quote:

import (
  "fmt"
  "log"

  api "github.com/MarketDataApp/sdk-go"
)

func main() {
  // Initialize a new request, set the symbol parameter, make the request.
	quotes, err := api.StockQuote().Symbol("AAPL").Get() 
	if err != nil {
		log.Fatalf("Failed to get stock quotes: %v", err)
	}

  // Loop over the quotes and print them out.
  for _, quote := range quotes {
		fmt.Println(quote)
	}

SDK Usage

  • All requests are initialized using the name of the endpoint and parameters are set using a builder pattern. The quickest way to get started is by viewing the examples.
  • All requests have 3 methods to get results:
    1. Use the .Get() method on any request to get a slice of objects. This is what you will use in most cases.
    2. Use the .Packed() method on any request to get a struct that models the Market Data JSON response. If you want to model the objects differently, this method could be useful for you.
    3. Use the .Raw() method on any request to *get the raw resty.Response object. This allows you to access the raw JSON or the raw *http.Response via any of Resty's methods. You can use any of the Resty methods on the response.
  • We have already implemented .String() methods for all .Get() and .Packed() responses and sorting methods for all candle objects.

Note: Since all our structs are pre-defined based on the Market Data API's standard response format, our API's optional parameters such as human, columns, dateformat, format are not supported in this SDK because they modify the API's standard JSON output. If you wish to make use of these parameters, you will need to model your own structs that can unmarshal the modified API response.

Logging

The SDK systematically logs API responses to facilitate troubleshooting and analysis, adhering to the following rules:

  • Client Errors: Responses with status codes in the range 400-499 are logged to client_error.log.
  • Server Errors: Responses with status codes in the range 500-599 are logged to server_error.log.
  • Successful Requests: If debug mode is activated, responses with status codes in the range 200-299 are logged to success.log.

All log files are formatted in JSON and stored within the /logs subdirectory. Each entry captures comprehensive details including the request URL, request headers, CF Ray ID (a unique identifier for the request), response status code, response headers, and the response body, providing a full context for each logged event.

Example of a log entry:

{
  "level":"info",
  "ts":"2024-01-25T15:34:10.642-0300",
  "msg":"Successful Request",
  "cf_ray":"84b29bd46f468d96-MIA",
  "request_url":"https://api.marketdata.app/v1/stocks/quotes/AAPL/",
  "ratelimit_consumed":0,
  "response_code":200,
  "delay_ms":254,
  "request_headers":{
    "Authorization": ["Bearer **********************************************************HMD0"],
    "User-Agent": ["sdk-go/0.0.4"]
  },
  "response_headers": {
    "Allow": ["GET, HEAD, OPTIONS"],
    "Alt-Svc": ["h3=\":443\"; ma=86400"],
    "Cf-Cache-Status": ["DYNAMIC"],
    "Cf-Ray": ["84b29bd46f468d96-MIA"],
    "Content-Type": ["application/json"],
    "Cross-Origin-Opener-Policy": ["same-origin"],
    "Date": ["Thu, 25 Jan 2024 18:34:10 GMT"],
    "Nel": ["{\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}"],
    "Referrer-Policy": ["same-origin"],
    "Report-To": ["{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=9vEr7PiX6zgR6cdNLegGNMCOzC6yy9KHd0IIzN3yPl14KDMBB9kkMV19xVP79jOdqPWBS9Ena%2B43XHWh%2B7cKqAQc7GrRCm2ZWpX4xqhXidyQeRgNoPcWsSsyv5xSD8v9ywFQdNc%3D\"}],\"group\":\"cf-nel\",\"max_age\":604800}"],
    "Server": ["cloudflare"],
    "Vary": ["Accept, Origin"],
    "X-Api-Ratelimit-Consumed": ["0"],
    "X-Api-Ratelimit-Limit": ["100000"],
    "X-Api-Ratelimit-Remaining": ["100000"],
    "X-Api-Ratelimit-Reset": ["1706279400"],
    "X-Api-Response-Log-Id": ["77524556"],
    "X-Content-Type-Options": ["nosniff"],
    "X-Frame-Options": ["DENY"]
  },
  "response_body": {
    "ask": [194.39],
    "askSize": [1],
    "bid": [194.38],
    "bidSize": [4],
    "change": [-0.11],
    "changepct": [-0.0006],
    "last": [194.39],
    "mid": [194.38],
    "s": "ok",
    "symbol": ["AAPL"],
    "updated": [1706207650],
    "volume": [29497567]
  }
}

Troubleshooting: Debug Mode

The SDK provides a debug mode that can be enabled to help you understand how the SDK is working and troubleshoot any issues you might encounter. When debug mode is enabled, the SDK will print the log to the console. This includes the full URL of the request, all request and response headers, and more.

To enable debug mode, you need to call the .Debug() method on the MarketDataClient instance and pass true as the argument.

Debug Code Example
package main

import (
  "log"
  "fmt"

	api "github.com/MarketDataApp/sdk-go"
)

func main() {
	client, err := api.GetClient()
	if err != nil {
		log.Fatalf("Failed to get client: %v", err)
	}

	client.Debug(true) // 👈 Here is where debug mode is turned on.

	quotes, err := client.StockQuotes().Symbol("AAPL").Get()
	if err != nil {
		log.Fatalf("Failed to get stock quotes: %v", err)
	}

  for _, quote := range quotes {
		fmt.Println(quote)
	}
}

Please note that the information printed in debug mode can be quite verbose. It is recommended to use this mode only when you are facing issues and need to understand what's happening under the hood. When debug mode is activated all requests are logged, not just requests that fail.

Debug mode can be particularly useful when you are first getting started with the SDK. It can help you understand how the SDK constructs requests, how it handles responses, and how it manages errors. By examining the debug output, you can gain a deeper understanding of the SDK's inner workings and be better prepared to handle any issues that might arise.

Important Information for SDK Users

Endpoint Coverage:

Market Data's Go SDK covers the vast majority of v1 endpoints. See our complete list of endpoints in the Market Data API Documentation.

Category Endpoint v1 Status v2 Status
MARKETS
Status
STOCKS
Candles
Bulk Candles
Quotes
Bulk Quotes
Earnings
Tickers
News
OPTIONS
Expirations
Lookup
Strikes
Option Chain
Quotes
INDICES
Candles
Quotes

Note on v2: Even though some v2 endpoints are available for use in this SDK, Market Data has not yet released v2 of its API for clients and v2 usage is restricted to admins only. Clients should only use v1 endpoints at this time. Even after v2 is released, we do not plan on deprecating v1 endpoints, so please build your applications with confidence using v1 endpoints.

SDK License & Data Usage Terms

The license for the Go SDK for Market Data is specifically for the SDK software and does not cover the data provided by the Market Data API. It's crucial to understand that accessing data through the SDK means you're also subject to the Market Data Terms of Service. You can review these terms at https://www.marketdata.app/terms/ to fully comprehend your rights and responsibilities concerning data usage.

Contributing to the SDK

Your contributions to the Go SDK are highly valued. Whether you're looking to add new features, rectify bugs, or enhance the documentation, we encourage you to get involved. Please submit your contributions via pull requests or issues on our GitHub repository. Your efforts play a significant role in improving the SDK for the benefit of all users.

Contact and Support

Should you need any assistance, the most effective way to reach us is through our helpdesk. We kindly ask that you use GitHub issues solely for bug reports and not for support inquiries.

Documentation

Overview

Package client provides a Go SDK for interacting with the Market Data API. It includes functionality for making API requests, handling responses, managing rate limits, and logging. The SDK supports various data types including stocks, options, and market status information.

Usage

To use the SDK, you first need to create an instance of MarketDataClient using the GetClient function. This client will then be used to make API requests to the Market Data API.

Example

client := GetClient()
client.Debug(true) // Enable debug mode to log detailed request and response information
quote, err := client.StockQuotes().Symbol("AAPL").Get()

Authentication

The SDK uses an API token for authentication. The token can be set as an environment variable (MARKETDATA_TOKEN) or directly in your code. However, storing tokens in your code is not recommended for security reasons.

Rate Limiting

The MarketDataClient automatically tracks and manages the API's rate limits. You can check if the rate limit has been exceeded with the RateLimitExceeded method.

Logging

The SDK logs all unsuccessful (400-499 and 500-599) responses to specific log files based on the response status code. Successful responses (200-299) are logged when debug mode is enabled. Logs include detailed information such as request and response headers, response status code, and the response body.

Debug Mode

Debug mode can be enabled by calling the Debug method on the MarketDataClient instance. When enabled, the SDK will log detailed information about each request and response, which is useful for troubleshooting.

Package client provides a Go SDK for interacting with the Market Data API. The Market Data Go Client includes functionality for making API requests, handling responses, managing rate limits, and logging. The SDK supports various data types including stocks, options, indices, and market status information.

Singleton Client

The MarketDataClient is a singleton client that is used to interact with the Market Data API. If you are using an environment variable to store your token, the client will be intialized automatically when the package is imported. If you are not using an environment variable, you can initialize the client manually using the NewClient method.

After you initialize it for the first time, it is not neccessary to reinitialize it again. The client is thread-safe and can be used across multiple goroutines. Do not attempt to create multiple instances of the client.

Get Started Quickly with the MarketDataClient

  1. Review the documentation on authentication to learn how to set your API token.
  2. Use GetClient to fetch the MarketDataClient instance and use MarketDataClient.Debug to log detailed request and response information to disk and the console as you learn how to use the SDK.
  3. Make a test request and review the console and the logs. The logs will contain the raw request and response details.
  4. Check the rate limit in the client to keep track of your requests and how many requests you have remaining.

Package client includes types and methods to access the Index Candles endpoint. Get historical price candles for any supported stock index.

Making Requests

Use IndicesCandlesRequest to make requests to the endpoint using any of the three supported execution methods:

| Method     | Execution     | Return Type                 | Description                                                                                                |
|------------|---------------|-----------------------------|------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct        | `[]Candle`                  | Directly returns a slice of `[]Candle`, making it straightforward to access each candle individually.      |
| **Packed** | Intermediate  | `*IndicesCandlesResponse`   | Returns a packed `*IndicesCandlesResponse` object. Must be unpacked to access the `[]Candle` slice.        |
| **Raw**    | Low-level     | `*resty.Response`           | Provides the raw `*resty.Response` for maximum flexibility. Direct access to raw JSON or `*http.Response`. |

Package client includes types and methods to access the Index Quotes endpoint. Retrieve real-time quotes for any supported index.

Making Requests

Utilize IndexQuoteRequest to make requests to the endpoint through one of the three supported execution methods:

| Method     | Execution     | Return Type                 | Description                                                                                                |
|------------|---------------|-----------------------------|------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct        | `[]IndexQuote`              | Directly returns a slice of `[]IndexQuote`, facilitating individual access to each quote.                  |
| **Packed** | Intermediate  | `*IndexQuotesResponse`      | Returns a packed `*IndexQuotesResponse` object. Must be unpacked to access the `[]IndexQuote` slice.       |
| **Raw**    | Low-level     | `*resty.Response`           | Offers the raw `*resty.Response` for utmost flexibility. Direct access to raw JSON or `*http.Response`.    |

Package client provides a collection of structs for logging. The Market Data Go SDK provides a comprehensive logging framework tailored for HTTP request and response tracking. It facilitates detailed logging of HTTP interactions, including request details, response data, error handling, and rate limit monitoring. The logging functionality is designed to support a wide range of market data types such as stocks, options, indices, and market status information, making it an essential tool for developers integrating market data into their applications.

Key Features

  • Detailed Logging: Captures and logs comprehensive details of HTTP requests and responses, including headers, status codes, and body content.
  • Error Handling: Distinguishes between client-side and server-side errors, logging them appropriately to aid in debugging and monitoring.
  • Rate Limit Management: Tracks and logs rate limit consumption for each request, helping to avoid rate limit breaches.
  • Debug Mode: Offers a debug mode that logs additional details for in-depth analysis during development and troubleshooting.
  • In-Memory Log Storage: Maintains the last log entries in memory with configurable limits on entries and memory usage, ensuring efficient log management.
  • Structured Logging: Utilizes the zap logging library for structured, high-performance logging.

Getting Started With Logging

  1. Initialize the MarketDataClient with your API token.
  2. Enable Debug mode for verbose logging during development.
  3. Perform HTTP requests and utilize the logging features to monitor request details, responses, and rate limit usage.
  4. Review the in-memory logs or structured log files to analyze HTTP interactions and troubleshoot issues.

Package client includes types and methods to access the Market Status endpoint. Retrieve current, future, and historical open / closed status information.

Making Requests

Utilize MarketStatusRequest to make requests to the endpoint through one of the three supported execution methods:

| Method     | Execution     | Return Type                 | Description                                                                                                     |
|------------|---------------|-----------------------------|-----------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct        | `[]MarketStatusReport`      | Directly returns a slice of `[]MarketStatusReport`, facilitating individual access to each market status entry. |
| **Packed** | Intermediate  | `*MarketStatusResponse`     | Returns a packed `*MarketStatusResponse` object. Must be unpacked to access the `[]MarketStatusReport` slice.   |
| **Raw**    | Low-level     | `*resty.Response`           | Offers the raw `*resty.Response` for utmost flexibility. Direct access to raw JSON or `*http.Response`.         |

Package client provides functionalities to interact with the Options Chain endpoint. Retrieve a a complete or filtered options chain for a given underlying symbol. Both real-time and historical requests are possible.

Making Requests

Utilize OptionChainRequest for querying the endpoint through one of the three available methods:

| Method     | Execution Level | Return Type                  | Description                                                                                                                      |
|------------|-----------------|------------------------------|----------------------------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct          | `[]OptionQuote`              | Immediately fetches a slice of `[]OptionQuote`, allowing direct access to the options chain data.                                |
| **Packed** | Intermediate    | `*OptionQuotesResponse`      | Delivers a `*OptionQuotesResponse` object containing the data, which requires unpacking to access the `OptionQuote` data.        |
| **Raw**    | Low-level       | `*resty.Response`            | Offers the unprocessed `*resty.Response` for those seeking full control and access to the raw JSON or `*http.Response`.          |

Package client provides functionalities to interact with the Options Expirations endpoint. Get a list of current or historical option expiration dates for an underlying symbol.

Making Requests

Utilize OptionsExpirationsRequest for querying the endpoint through one of the three available methods:

| Method     | Execution       | Return Type                   | Description                                                                                                                      |
|------------|-----------------|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct          | `[]time.Time`                 | Immediately fetches and returns a slice of `[]time.Time`, allowing direct access to each expiration date.                        |
| **Packed** | Intermediate    | `*OptionsExpirationsResponse` | Delivers a `*OptionsExpirationsResponse` object containing the data, which requires unpacking to access the `[]time.Time` slice. |
| **Raw**    | Low-level       | `*resty.Response`             | Offers the unprocessed `*resty.Response` for those seeking full control and access to the raw JSON or `*http.Response`.          |

Package client provides functionalities to interact with the Options Lookup endpoint. Lookup the OCC-formatted option symbol based on user input.

Making Requests

Utilize [OptionsLookupRequest] for querying the endpoint through one of the three available methods:

| Method     | Execution       | Return Type                  | Description                                                                                                             |
|------------|-----------------|------------------------------|-------------------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct          | `string`                     | Immediately fetches and `string`, allowing direct access to the option symbol.                                          |
| **Packed** | Intermediate    | `*OptionLookupResponse`      | Delivers a `*OptionLookupResponse` object containing the data, which requires unpacking to access the `string` data.    |
| **Raw**    | Low-level       | `*resty.Response`            | Offers the unprocessed `*resty.Response` for those seeking full control and access to the raw JSON or `*http.Response`. |

Package client provides functionalities to interact with the Options Quotes endpoint. Retrieve an option quote for a given option symbol.

Making Requests

Utilize OptionQuoteRequest for querying the endpoint through one of the three available methods:

| Method     | Execution       | Return Type                  | Description                                                                                                                |
|------------|-----------------|------------------------------|----------------------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct          | `[]OptionQuote`              | Immediately fetches a slice of `[]OptionQuote`, allowing direct access to the quote data.                                  |
| **Packed** | Intermediate    | `*OptionQuotesResponse`      | Delivers a `*OptionQuotesResponse` object containing the data, which requires unpacking to access the `OptionQuote` data.  |
| **Raw**    | Low-level       | `*resty.Response`            | Offers the unprocessed `*resty.Response` for those seeking full control and access to the raw JSON or `*http.Response`.    |

Package client provides functionalities to interact with the Option Strikes endpoint. Retrieve a complete or filtered list of option strike prices for a given underlying symbol. Both real-time and historical requests are possible.

Making Requests

Utilize OptionStrikesRequest for querying the endpoint through one of the three available methods:

| Method     | Execution       | Return Type                  | Description                                                                                                                      |
|------------|-----------------|------------------------------|----------------------------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct          | `[]OptionStrikes`           | Immediately fetches a slice of `[]OptionStrikes`, allowing direct access to the options strikes data.                           |
| **Packed** | Intermediate    | `*OptionStrikesResponse`    | Delivers a `*OptionStrikesResponse` object containing the data, which requires unpacking to access the `[]OptionStrikes` slice.|
| **Raw**    | Low-level       | `*resty.Response`            | Offers the unprocessed `*resty.Response` for those seeking full control and access to the raw JSON or `*http.Response`.          |

Package client provides functionalities to interact with the Bulk Stock Candles endpoint. Get bulk historical price data for many stock symbols at once or even obtain a full market snapshot.

Making Requests

Utilize the BulkStockCandlesRequest for querying the endpoint through one of the three available methods:

| Method     | Execution       | Return Type                 | Description                                                                                                             |
|------------|-----------------|-----------------------------|-------------------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct          | `[]Candle`                  | Immediately fetches and returns a slice of `[]Candle`, allowing direct access to each candle's data.                    |
| **Packed** | Intermediate    | `*BulkStockCandlesResponse` | Delivers a `*StockCandlesResponse` object containing the data, which requires unpacking to access the `[]Candle` slice. |
| **Raw**    | Low-level       | `*resty.Response`           | Offers the unprocessed `*resty.Response` for those seeking full control and access to the raw JSON or `*http.Response`. |

Package client includes types and methods to access the Bulk Stock Quotes endpoint. Retrieve real-time quotes for multiple stocks symbols in a single request or even get a full market snapshot with a quote for all symbols.

Making Requests

Utilize BulkStockQuotesRequest to make requests to the endpoint through one of the three supported execution methods:

| Method     | Execution     | Return Type                 | Description                                                                                                |
|------------|---------------|-----------------------------|------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct        | `[]StockQuote`              | Directly returns a slice of `[]StockQuote`, facilitating individual access to each stock quote.            |
| **Packed** | Intermediate  | `*StockQuotesResponse`      | Returns a packed `*StockQuotesResponse` object. Must be unpacked to access the `[]StockQuote` slice.       |
| **Raw**    | Low-level     | `*resty.Response`           | Offers the raw `*resty.Response` for utmost flexibility. Direct access to raw JSON or `*http.Response`.    |

Package client includes types and methods to access the Stock Candles endpoint. Retrieve historical price candles for any supported stock symbol.

Making Requests

Use StockCandlesRequest to make requests to the endpoint using any of the three supported execution methods:

| Method     | Execution     | Return Type                 | Description                                                                                                |
|------------|---------------|-----------------------------|------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct        | `[]Candle`                  | Directly returns a slice of `[]Candle`, facilitating individual access to each candle.                     |
| **Packed** | Intermediate  | `*StockCandlesResponse`     | Returns a packed `*StockCandlesResponse` object. Must be unpacked to access the `[]Candle` slice.          |
| **Raw**    | Low-level     | `*resty.Response`           | Provides the raw `*resty.Response` for maximum flexibility. Direct access to raw JSON or `*http.Response`. |

Package client includes types and methods to access the Stock Earnings endpoint. Retrieve earnings data for any supported stock symbol.

Making Requests

Use StockEarningsRequest to make requests to the endpoint using any of the three supported execution methods:

| Method     | Execution     | Return Type                 | Description                                                                                                     |
|------------|---------------|-----------------------------|-----------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct        | `[]StockEarningsReport`     | Directly returns a slice of `[]StockEarningsReport`, facilitating individual access to each earnings report.    |
| **Packed** | Intermediate  | `*StockEarningsResponse`    | Returns a packed `*StockEarningsResponse` object. Must be unpacked to access the `[]StockEarningsReport` slice. |
| **Raw**    | Low-level     | `*resty.Response`           | Provides the raw `*resty.Response` for maximum flexibility. Direct access to raw JSON or `*http.Response`.      |

Package client includes types and methods to access the Stock News endpoint. Retrieve news articles for any supported stock symbol.

Making Requests

Use StockNewsRequest to make requests to the endpoint using any of the three supported execution methods:

| Method     | Execution     | Return Type                 | Description                                                                                                |
|------------|---------------|-----------------------------|------------------------------------------------------------------------------------------------------------|
| **Get**    | Direct        | `[]StockNews  `             | Directly returns a slice of `[]StockNews`, facilitating individual access to each news article.            |
| **Packed** | Intermediate  | `*StockNewsResponse`        | Returns a packed `*StockNewsResponse` object. Must be unpacked to access the `[]StockNews` slice.          |
| **Raw**    | Low-level     | `*resty.Response`           | Provides the raw `*resty.Response` for maximum flexibility. Direct access to raw JSON or `*http.Response`. |

Package client includes types and methods to access the Stock Quotes endpoint. Retrieve real-time quotes for any supported stock symbol.

Making Requests

Utilize StockQuoteRequest to make requests to the endpoint through one of the three supported execution methods:

| Method     | Execution     | Return Type                | Description                                                                                               |
|------------|---------------|----------------------------|-----------------------------------------------------------------------------------------------------------|
| **Get**    | Direct        | `[]StockQuote`             | Directly returns a slice of `[]StockQuote`, facilitating individual access to each stock quote.           |
| **Packed** | Intermediate  | `StockQuotesResponse`      | Returns a packed `StockQuotesResponse` object. Must be unpacked to access the `[]StockQuote` slice.       |
| **Raw**    | Low-level     | `resty.Response`           | Offers the raw `resty.Response` for utmost flexibility. Direct access to raw JSON or `*http.Response`.    |

Package stocks provides the /stocks endpoints

Index

Examples

Constants

View Source
const (
	Version = "1.1.0" // Version specifies the current version of the SDK.

)

Variables

This section is empty.

Functions

This section is empty.

Types

type BulkStockCandlesRequest added in v1.0.0

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

BulkStockCandlesRequest represents a request to the /v1/stocks/bulkcandles/ endpoint. It encapsulates parameters for resolution, symbol, date, and additional stock-specific parameters to be used in the request. This struct provides methods such as Resolution(), Symbol(), Date(), From(), To(), Countback(), AdjustSplits(), AdjustDividends(), Extended(), and Exchange() to set these parameters respectively.

Generated By

  • BulkStockCandles() *BulkStockCandlesRequest: BulkStockCandles creates a new *BulkStockCandlesRequest and returns a pointer to the request allowing for method chaining.

Setter Methods

  • Resolution(string) *BulkStockCandlesRequest: Sets the resolution parameter for the request.
  • Symbol(string) *BulkStockCandlesRequest: Sets the symbol parameter for the request.
  • Date(interface{}) *BulkStockCandlesRequest: Sets the date parameter for the request.
  • AdjustSplits(bool) *BulkStockCandlesRequest: Sets the adjust splits parameter for the request.
  • AdjustDividends(bool) *BulkStockCandlesRequest: Sets the adjust dividends parameter for the request.
  • Extended(bool) *BulkStockCandlesRequest: Sets the extended hours data parameter for the request.
  • Exchange(string) *BulkStockCandlesRequest: Sets the exchange parameter for the request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() ([]Candle, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed() (*BulkStockCandlesResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
Example (Get)
symbols := []string{"AAPL", "META", "MSFT"}
bscr, err := BulkStockCandles().Resolution("D").Symbols(symbols).Date("2024-02-06").Get()
if err != nil {
	fmt.Print(err)
	return
}
for _, candle := range bscr {
	fmt.Println(candle)
}
Output:

Candle{Symbol: AAPL, Date: 2024-02-06, Open: 186.86, High: 189.31, Low: 186.7695, Close: 189.3, Volume: 43490759}
Candle{Symbol: META, Date: 2024-02-06, Open: 464, High: 467.12, Low: 453, Close: 454.72, Volume: 21653114}
Candle{Symbol: MSFT, Date: 2024-02-06, Open: 405.88, High: 407.97, Low: 402.91, Close: 405.49, Volume: 18382624}
Example (Packed)
symbols := []string{"AAPL", "META", "MSFT"}
bscr, err := BulkStockCandles().Resolution("D").Symbols(symbols).Date("2024-02-06").Packed()
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println(bscr)
Output:

BulkStockCandlesResponse{Symbol: [AAPL META MSFT], Date: [1707195600 1707195600 1707195600], Open: [186.86 464 405.88], High: [189.31 467.12 407.97], Low: [186.7695 453 402.91], Close: [189.3 454.72 405.49], Volume: [43490759 21653114 18382624]}
Example (Raw)
symbols := []string{"AAPL", "META", "MSFT"}
bscr, err := BulkStockCandles().Resolution("D").Symbols(symbols).Date("2024-02-06").Raw()
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println(bscr)
Output:

{"s":"ok","symbol":["AAPL","META","MSFT"],"o":[186.86,464.0,405.88],"h":[189.31,467.12,407.97],"l":[186.7695,453.0,402.91],"c":[189.3,454.72,405.49],"v":[43490759,21653114,18382624],"t":[1707195600,1707195600,1707195600]}

func BulkStockCandles added in v1.0.0

func BulkStockCandles(client ...*MarketDataClient) *BulkStockCandlesRequest

BulkStockCandles initializes a new BulkStockCandlesRequest with default parameters. This function prepares a request to fetch bulk stock candles data. It sets up all necessary parameters and configurations to make the request ready to be sent. The function accepts a variadic parameter that allows passing an optional MarketDataClient. If a client is provided, it will be used for the request; otherwise, a default client is initialized and used.

Parameters

  • ...*MarketDataClient: A variadic parameter that can accept zero or one MarketDataClient pointer. This allows for the optional customization of the client used for the request. If no client is provided, a default client is initialized and used.

Returns

  • *BulkStockCandlesRequest: A pointer to the newly created BulkStockCandlesRequest instance. This instance contains all the necessary parameters set to their default values and is ready to have additional parameters set or to be sent.

func (*BulkStockCandlesRequest) AdjustSplits added in v1.0.0

func (bscr *BulkStockCandlesRequest) AdjustSplits(q bool) *BulkStockCandlesRequest

AdjustSplits sets the adjust splits parameter for the BulkStockCandlesRequest. This method indicates whether the returned data should be adjusted for stock splits.

Parameters

  • bool: Whether to adjust for splits.

Returns

  • *BulkStockCandlesRequest: This method returns a pointer to the *BulkStockCandlesRequest instance it was called on. This allows for method chaining.

func (*BulkStockCandlesRequest) Date added in v1.0.0

func (bscr *BulkStockCandlesRequest) Date(q interface{}) *BulkStockCandlesRequest

Date sets the date parameter for the BulkStockCandlesRequest. This method is used to specify the date for which the stock candle data is requested.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix timestamp as an int, or any other type that the underlying dates package method can process.

Returns

  • *BulkStockCandlesRequest: This method returns a pointer to the *BulkStockCandlesRequest instance it was called on. This allows for method chaining.

func (*BulkStockCandlesRequest) Get added in v1.0.0

func (bscr *BulkStockCandlesRequest) Get() ([]models.Candle, error)

Get sends the BulkStockCandlesRequest, unpacks the StockCandlesResponse, and returns a slice of []Candle. It returns an error if the request or unpacking fails.

Returns

  • []models.Candle: A slice of []Candle containing the unpacked candle data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*BulkStockCandlesRequest) Packed added in v1.0.0

Packed sends the BulkStockCandlesRequest and returns the StockCandlesResponse.

Returns

  • *models.BulkStockCandlesResponse: A pointer to the BulkStockCandlesResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*BulkStockCandlesRequest) Raw added in v1.0.0

func (bscr *BulkStockCandlesRequest) Raw() (*resty.Response, error)

Raw executes the request and returns the raw *resty.Response. This method allows for obtaining the raw JSON or *http.Response directly from the executed request.

Returns

  • *resty.Response: The raw response from the executed request.
  • error: An error object if the request is nil or if an error occurs during the request execution.

func (*BulkStockCandlesRequest) Resolution added in v1.0.0

Resolution sets the resolution parameter for the BulkStockCandlesRequest. This method is used to specify the granularity of the candle data to be retrieved.

Parameters

  • string: The resolution to be set.

Returns

  • *BulkStockCandlesRequest: This method returns a pointer to the *BulkStockCandlesRequest instance it was called on. This allows for method chaining.

func (*BulkStockCandlesRequest) Snapshot added in v1.0.0

Snapshot sets the snapshot parameter for the BulkStockCandlesRequest. This method is used to enable or disable the snapshot feature in the request and will result in all available tickers being returned in the response.

Parameters

  • bool: A boolean value representing whether to enable or disable the snapshot feature.

Returns

  • *BulkStockCandlesRequest: This method returns a pointer to the *BulkStockCandlesRequest instance it was called on. This allows for method chaining.

func (*BulkStockCandlesRequest) Symbols added in v1.0.0

Symbols sets the symbols parameter for the BulkStockCandlesRequest. This method is used to specify multiple stock symbols for which candle data is requested.

Parameters

  • []string: A slice of []string representing the stock symbols to be set.

Returns

  • *BulkStockCandlesRequest: This method returns a pointer to the *BulkStockCandlesRequest instance it was called on. This allows for method chaining.

type BulkStockQuotesRequest added in v1.0.0

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

BulkStockQuotesRequest represents a request to the v1/stocks/bulkquotes/ endpoint. It encapsulates parameters for symbol and fifty-two-week data to be used in the request. This struct provides methods such as Symbol() and FiftyTwoWeek() to set these parameters respectively.

Generated By

  • BulkStockQuotes() *BulkStockQuotesRequest: BulkStockQuotes creates a new *BulkStockQuotesRequest and returns a pointer to the request allowing for method chaining.

Setter Methods

  • Symbol(string) *BulkStockQuotesRequest: Sets the symbol parameter for the request.
  • FiftyTwoWeek(bool) *BulkStockQuotesRequest: Sets the fifty-two-week data parameter for the request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() ([]Candle, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed() (*StockQuotesResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
Example (Get)
// This example demonstrates how to create a BulkStockQuotesRequest, set its parameters,
// and perform an actual request to fetch stock quotes for multiple symbols.

// Initialize a new BulkStockQuotesRequest and fetch stock quotes for "AAPL", "META", and "MSFT".
symbols := []string{"AAPL", "META", "MSFT"}
bsqr, err := BulkStockQuotes().Symbols(symbols).Get()
if err != nil {
	log.Fatalf("Failed to get bulk stock quotes: %v", err)
}

// Check if the response contains the symbols.
for _, quote := range bsqr {
	fmt.Printf("Symbol: %s\n", quote.Symbol)
}
Output:

Symbol: AAPL
Symbol: META
Symbol: MSFT
Example (Packed)
// This example demonstrates how to create a BulkStockQuotesRequest, set its parameters,
// and perform an actual request to fetch stock quotes for multiple symbols: "AAPL", "META", and "MSFT".

// Initialize a new BulkStockQuotesRequest and fetch stock quotes for the specified symbols.
symbols := []string{"AAPL", "META", "MSFT"}
bsqr, err := BulkStockQuotes().Symbols(symbols).Packed()
if err != nil {
	log.Fatalf("Failed to get bulk stock quotes: %v", err)
}

// Iterate and print all the symbols in the response.
for _, symbol := range bsqr.Symbol {
	fmt.Printf("Symbol: %s\n", symbol)
}
Output:

Symbol: AAPL
Symbol: META
Symbol: MSFT
Example (Raw)
// This example demonstrates how to create a BulkStockQuotesRequest, set its parameters,
// and perform an actual request to fetch stock quotes for multiple symbols: "AAPL", "META", and "MSFT".
// The response is converted to a raw string and we print out the string at the end of the test.

// Initialize a new BulkStockQuotesRequest and fetch stock quotes for "AAPL", "META", and "MSFT".
symbols := []string{"AAPL", "META", "MSFT"}
bsqr, err := BulkStockQuotes().Symbols(symbols).Raw()
if err != nil {
	log.Fatalf("Failed to get bulk stock quotes: %v", err)
}

// Convert the response to a string.
jsonStr := bsqr.String()

// Define a struct to match the JSON structure
type Response struct {
	Symbol []string `json:"symbol"`
}

// Unmarshal the JSON into the struct
var resp Response
err = json.Unmarshal([]byte(jsonStr), &resp)
if err != nil {
	log.Fatalf("Failed to parse JSON: %v", err)
}

// Print the symbols
for _, symbol := range resp.Symbol {
	fmt.Printf("Symbol: %s\n", symbol)
}
Output:

Symbol: AAPL
Symbol: META
Symbol: MSFT

func BulkStockQuotes added in v1.0.0

func BulkStockQuotes() *BulkStockQuotesRequest

BulkStockQuotes creates a new BulkStockQuotesRequest and associates it with the default client. This function initializes the request with default parameters for symbol and fifty-two-week data, and sets the request path based on the predefined endpoints for stock quotes.

Returns

  • *BulkStockQuotesRequest: A pointer to the newly created BulkStockQuotesRequest with default parameters and associated client.

func (*BulkStockQuotesRequest) Get added in v1.0.0

Get sends the BulkStockQuotesRequest, unpacks the StockQuotesResponse, and returns a slice of StockQuote. It returns an error if the request or unpacking fails.

Returns

  • []models.StockQuote: A slice of StockQuote containing the unpacked quote data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*BulkStockQuotesRequest) Packed added in v1.0.0

Packed sends the BulkStockQuotesRequest and returns the StockQuotesResponse.

Returns

  • *models.StockQuotesResponse: A pointer to the StockQuotesResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*BulkStockQuotesRequest) Raw added in v1.0.0

func (bsqr *BulkStockQuotesRequest) Raw() (*resty.Response, error)

Raw executes the request for BulkStockQuotesRequest and returns the raw *resty.Response. This method does not allow for an optional MarketDataClient to be passed.

Returns

  • *resty.Response: The raw response from the executed BulkStockQuotesRequest.
  • error: An error object if the BulkStockQuotesRequest is nil or if an error occurs during the request execution.

func (*BulkStockQuotesRequest) Snapshot added in v1.0.0

Snapshot sets the snapshot parameter for the BulkStockQuotesRequest. This method is used to enable or disable the snapshot feature in the request and will result in all available tickers being returned in the response.

Parameters

  • bool: A boolean value representing whether to enable or disable the snapshot feature.

Returns

  • *BulkStockQuotesRequest: This method returns a pointer to the *BulkStockQuotesRequest instance it was called on. This allows for method chaining.

func (*BulkStockQuotesRequest) Symbols added in v1.0.0

Symbols sets the symbols parameter for the BulkStockQuotesRequest. This method is used to specify multiple stock symbols for which candle data is requested.

Parameters

  • []string: A slice of []string representing the stock symbols to be set.

Returns

  • *BulkStockQuotesRequest: This method returns a pointer to the BulkStockQuotesRequest instance it was called on. This allows for method chaining.

type Environment added in v1.1.0

type Environment string

Environment represents the type for different environments in which the MarketDataClient can operate. Customers do not need to set the environment. The MarketDataClient will automatically be initialized with a Production environment if no environment is set.

Market Data's Go Client supports three environments:

  1. Production
  2. Test
  3. Development.

It is used to configure the client to point to the appropriate base URL depending on the environment. This is used for development or testing by Market Data employees.

const (
	// Production specifies the production environment. It is used when the client is interacting with the live Market Data API.
	Production Environment = "prod"

	// Test specifies the testing environment. It is used for testing purposes, allowing interaction with a sandbox version of the Market Data API.
	Test Environment = "test"

	// Development specifies the development environment. It is typically used during the development phase, pointing to a local or staged version of the Market Data API.
	Development Environment = "dev"
)

type IndexQuoteRequest

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

IndexQuoteRequest represents a request to the /v1/indices/quotes/ endpoint. It encapsulates parameters for symbol and fifty-two-week data to be used in the request. This struct provides methods such as Symbol() and FiftyTwoWeek() to set these parameters respectively.

Generated By

  • IndexQuotes(): IndexQuotes creates a new *IndexQuoteRequest and returns a pointer to the request allowing for method chaining.

Setter Methods

These methods are used to set the parameters of the request. They allow for method chaining by returning a pointer to the *IndexQuoteRequest instance they modify.

  • Symbol(string) *IndexQuoteRequest: Sets the symbol parameter for the request.
  • FiftyTwoWeek(bool) *IndexQuoteRequest: Sets the fifty-two-week parameter for the request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get) ([]IndexQuote, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed) (*IndexQuotesResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw) (*resty.Response, error): Sends the request as is and returns the raw HTTP response.

func IndexQuotes

func IndexQuotes() *IndexQuoteRequest

IndexQuotes creates a new IndexQuoteRequest and associates it with the default client. This function initializes the request with default parameters for symbol and fifty-two-week data, and sets the request path based on the predefined endpoints for index quotes.

Returns

  • *IndexQuoteRequest: A pointer to the newly created IndexQuoteRequest with default parameters and associated with the default client.

func (*IndexQuoteRequest) FiftyTwoWeek

func (iqr *IndexQuoteRequest) FiftyTwoWeek(q bool) *IndexQuoteRequest

FiftyTwoWeek sets the FiftyTwoWeek parameter for the IndexQuoteRequest. This method is used to specify whether to include fifty-two-week high and low data in the quote. It modifies the fiftyTwoWeekParams field of the IndexQuoteRequest instance to store the boolean value.

Parameters

  • bool: A boolean indicating whether to include fifty-two-week data.

Returns

  • *IndexQuoteRequest: This method returns a pointer to the IndexQuoteRequest instance it was called on. This allows for method chaining. If the receiver (*IndexQuoteRequest) is nil, it returns nil to prevent a panic.

func (*IndexQuoteRequest) Get

func (iqr *IndexQuoteRequest) Get() ([]models.IndexQuote, error)

Get sends the IndexQuoteRequest, unpacks the IndexQuotesResponse, and returns a slice of IndexQuote. It returns an error if the request or unpacking fails. This method is crucial for obtaining the actual quote data from the index quote request. The method first checks if the IndexQuoteRequest receiver is nil, which would result in an error as the request cannot be sent. It then proceeds to send the request using the default client with the Packed method. Upon receiving the response, it unpacks the data into a slice of IndexQuote using the Unpack method from the response.

Returns

  • []models.IndexQuote: A slice of IndexQuote containing the unpacked quote data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*IndexQuoteRequest) Packed

Packed sends the IndexQuoteRequest and returns the IndexQuotesResponse. This method checks if the IndexQuoteRequest receiver is nil, returning an error if true. It proceeds to send the request using the default client and returns the IndexQuotesResponse along with any error encountered during the request.

Returns

  • *models.IndexQuotesResponse: A pointer to the IndexQuotesResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*IndexQuoteRequest) Raw

func (iqr *IndexQuoteRequest) Raw() (*resty.Response, error)

Raw executes the IndexQuoteRequest and returns the raw *resty.Response. The *resty.Response can be directly used to access the raw JSON or *http.Response for further processing.

Returns

  • *resty.Response: The raw HTTP response from the executed IndexQuoteRequest.
  • error: An error object if the IndexQuoteRequest is nil or if an error occurs during the request execution.

func (*IndexQuoteRequest) Symbol

func (iqr *IndexQuoteRequest) Symbol(q string) *IndexQuoteRequest

Symbol sets the symbol parameter for the IndexQuoteRequest. This method is used to specify the market symbol for which the quote data is requested. It modifies the symbolParams field of the IndexQuoteRequest instance to store the symbol value.

Parameters

  • string: A string representing the market symbol to be set.

Returns

  • *IndexQuoteRequest: This method returns a pointer to the IndexQuoteRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement. If the receiver (*IndexQuoteRequest) is nil, it returns nil to prevent a panic.

Note:

  • If an error occurs while setting the symbol (e.g., if the symbol value is not supported), the Error field of the IndexQuoteRequest is set with the encountered error, but the method still returns the IndexQuoteRequest instance to allow for further method calls or error handling by the caller.

type IndicesCandlesRequest

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

IndicesCandlesRequest represents a request to the /v1/indices/candles/ endpoint. It encapsulates parameters for resolution, symbol, and dates to be used in the request.

Generated By

  • IndexCandles() *IndicesCandlesRequest: IndexCandles creates a new *IndicesCandlesRequest and returns a pointer to the request allowing for method chaining.

Setter Methods

These methods are used to set the parameters of the request. They allow for method chaining by returning a pointer to the *IndicesCandlesRequest instance they modify.

  • Resolution(string) *IndicesCandlesRequest: Sets the resolution parameter for the request.
  • Symbol(string) *IndicesCandlesRequest: Sets the symbol parameter for the request.
  • Date(interface{}) *IndicesCandlesRequest: Sets the date parameter for the request.
  • From(interface{}) *IndicesCandlesRequest: Sets the 'from' date parameter for the request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get) ([]Candle, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed) (*IndicesCandlesResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw) (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
Example (Get)
vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2022-01-01").To("2022-01-05").Get()
if err != nil {
	println("Error retrieving VIX index candles:", err.Error())
	return
}

for _, candle := range vix {
	fmt.Println(candle)
}
Output:

Candle{Date: 2022-01-03, Open: 17.6, High: 18.54, Low: 16.56, Close: 16.6}
Candle{Date: 2022-01-04, Open: 16.57, High: 17.81, Low: 16.34, Close: 16.91}
Candle{Date: 2022-01-05, Open: 17.07, High: 20.17, Low: 16.58, Close: 19.73}
Example (Packed)
vix, err := IndexCandles().Symbol("VIX").Resolution("D").To("2022-01-05").Countback(3).Packed()
if err != nil {
	println("Error retrieving VIX index candles:", err.Error())
	return
}
fmt.Println(vix)
Output:

IndicesCandlesResponse{Time: [1641186000 1641272400 1641358800], Open: [17.6 16.57 17.07], High: [18.54 17.81 20.17], Low: [16.56 16.34 16.58], Close: [16.6 16.91 19.73]}
Example (Raw)
vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2022-01-01").To("2022-01-05").Raw()
if err != nil {
	println("Error retrieving VIX index candles:", err.Error())
	return
}
fmt.Println(vix)
Output:

{"s":"ok","t":[1641186000,1641272400,1641358800],"o":[17.6,16.57,17.07],"h":[18.54,17.81,20.17],"l":[16.56,16.34,16.58],"c":[16.6,16.91,19.73]}

func IndexCandles

func IndexCandles() *IndicesCandlesRequest

IndexCandles creates a new IndicesCandlesRequest and associates it with the default client. This function initializes the request with default parameters for date, resolution, and symbol, and sets the request path based on the predefined endpoints for indices candles.

Returns

  • *IndicesCandlesRequest: A pointer to the newly created *IndicesCandlesRequest with default parameters and associated client.

func (*IndicesCandlesRequest) Countback

func (icr *IndicesCandlesRequest) Countback(q int) *IndicesCandlesRequest

Countback sets the countback parameter for the IndicesCandlesRequest. It specifies the number of candles to return, counting backwards from the 'to' date.

Parameters

  • int: An int representing the number of candles to return.

Returns

  • *IndicesCandlesRequest: A pointer to the *IndicesCandlesRequest instance to allow for method chaining.

func (*IndicesCandlesRequest) Date

func (icr *IndicesCandlesRequest) Date(q interface{}) *IndicesCandlesRequest

Date sets the date parameter for the IndicesCandlesRequest. This method is used to specify the date for which the candle data is requested. It modifies the 'date' field of the IndicesCandlesRequest instance to store the date value.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix int, or any other type that the underlying dates package method can process.

Returns

  • *IndicesCandlesRequest: This method returns a pointer to the *IndicesCandlesRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement.

Notes

  • If an error occurs while setting the date (e.g., if the date value is not supported), the Error field of the request is set with the encountered error, but the method still returns the *IndicesCandlesRequest instance to allow for further method calls.

func (*IndicesCandlesRequest) From

func (icr *IndicesCandlesRequest) From(q interface{}) *IndicesCandlesRequest

From sets the 'from' date parameter for the IndicesCandlesRequest. It configures the starting point of the date range for which the candle data is requested.

Parameters

  • interface{}: An interface{} that represents the starting date. It can be a string, a time.Time object, a Unix timestamp or any other type that the underlying dates package can process.

Returns

  • *IndicesCandlesRequest: A pointer to the *IndicesCandlesRequest instance to allow for method chaining.

func (*IndicesCandlesRequest) Get

func (icr *IndicesCandlesRequest) Get() ([]models.Candle, error)

Get sends the IndicesCandlesRequest, unpacks the IndicesCandlesResponse, and returns a slice of IndexCandle. It returns an error if the request or unpacking fails. This method is crucial for obtaining the actual candle data from the indices candles request. The method first checks if the IndicesCandlesRequest receiver is nil, which would result in an error as the request cannot be sent. It then proceeds to send the request using the Packed method. Upon receiving the response, it unpacks the data into a slice of IndexCandle using the Unpack method from the response.

Returns

  • []models.Candle: A slice of []models.Candle containing the unpacked candle data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*IndicesCandlesRequest) Packed

Packed sends the IndicesCandlesRequest and returns the IndicesCandlesResponse. This method checks if the IndicesCandlesRequest receiver is nil, returning an error if true. It proceeds to send the request and returns the IndicesCandlesResponse along with any error encountered during the request.

Returns

  • *models.IndicesCandlesResponse: A pointer to the *IndicesCandlesResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*IndicesCandlesRequest) Raw

func (icr *IndicesCandlesRequest) Raw() (*resty.Response, error)

Raw executes the IndicesCandlesRequest and returns the raw *resty.Response. The *resty.Response can be directly used to access the raw JSON or *http.Response for further processing.

Returns

  • *resty.Response: The raw HTTP response from the executed IndicesCandlesRequest.
  • error: An error object if the IndicesCandlesRequest is nil or if an error occurs during the request execution.

func (*IndicesCandlesRequest) Resolution

Resolution sets the resolution parameter for the IndicesCandlesRequest. This method is used to specify the granularity of the candle data to be retrieved. It modifies the resolutionParams field of the IndicesCandlesRequest instance to store the resolution value.

Parameters

  • string: A string representing the resolution to be set. Valid resolutions may include values like "D", "5", "1h", etc. See the API's supported resolutions.

Returns

  • *IndicesCandlesRequest: This method returns a pointer to the *IndicesCandlesRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement. If the receiver (*IndicesCandlesRequest) is nil, it returns nil to prevent a panic.

Notes

  • If an error occurs while setting the resolution (e.g., if the resolution value is not supported), the Error field of the *IndicesCandlesRequest is set with the encountered error, but the method still returns the IndicesCandlesRequest instance to allow for further method calls by the caller.

func (*IndicesCandlesRequest) Symbol

Symbol sets the symbol parameter for the IndicesCandlesRequest. This method is used to specify the index symbol for which the candle data is requested.

Parameters

  • string: A string representing the index symbol to be set.

Returns

  • *IndicesCandlesRequest: This method returns a pointer to the *IndicesCandlesRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement. If the receiver (*IndicesCandlesRequest) is nil, it returns nil to prevent a panic.

Notes

  • If an error occurs while setting the symbol (e.g., if the symbol value is not supported), the Error field of the IndicesCandlesRequest is set with the encountered error, but the method still returns the IndicesCandlesRequest instance to allow for further method calls or error handling by the caller.

func (*IndicesCandlesRequest) To

func (icr *IndicesCandlesRequest) To(q interface{}) *IndicesCandlesRequest

To sets the 'to' date parameter for the IndicesCandlesRequest. It configures the ending point of the date range for which the candle data is requested.

Parameters

  • interface{}: An interface{} that represents the ending date. It can be a string, a time.Time object, or any other type that the underlying SetTo method can process.

Returns

  • *IndicesCandlesRequest: A pointer to the *IndicesCandlesRequest instance to allow for method chaining.

type LogEntry added in v1.1.0

type LogEntry struct {
	Timestamp         time.Time
	RequestHeaders    http.Header // The Request Headers
	ResponseHeaders   http.Header // The Response Headers
	RayID             string      // The Ray ID from the HTTP response
	Request           string      // The URL of the HTTP Request
	Status            int         // The status code of the response
	RateLimitConsumed int         // The number of requests consumed from the rate limit
	Delay             int64       // The time (in miliseconds) between the request and the server's response
	Response          string      // The server response
	// contains filtered or unexported fields
}

LogEntry represents a single HTTP request log entry. It includes detailed information about the request and response, such as headers, status code, and response body.

Methods

  • String() string: Returns a string representation of the HTTP request log entry.
  • PrettyPrint(): Prints a formatted representation of the HTTP request log entry.

func (LogEntry) PrettyPrint added in v1.1.0

func (l LogEntry) PrettyPrint()

PrettyPrint prints a formatted representation of the HTTP request log entry.

func (LogEntry) String added in v1.1.0

func (l LogEntry) String() string

String returns a string representation of the HTTP request log entry.

Returns

  • string: A string representing the log entry.

Example

LogEntry{Timestamp: 2024-02-19 14:53:34 -05:00, Status: 200, Request: https://api.marketdata.app/v1/stocks/candles/4H/AAPL/?from=2023-01-01&to=2023-01-04, RequestHeaders: map[Authorization:[Bearer **********************************************************L06F] User-Agent:[sdk-go/1.1.0]], RayID: 85810e82de8e7438-MIA, RateLimitConsumed: 0, Delay: 893ms, Response Headers: map[Allow:[GET, HEAD, OPTIONS] Alt-Svc:[h3=":443"; ma=86400] Cf-Cache-Status:[DYNAMIC] Cf-Ray:[85810e82de8e7438-MIA] Content-Type:[application/json] Cross-Origin-Opener-Policy:[same-origin] Date:[Mon, 19 Feb 2024 19:53:34 GMT] Nel:[{"success_fraction":0,"report_to":"cf-nel","max_age":604800}] Referrer-Policy:[same-origin] Report-To:[{"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=r18O66yjJ%2FxXqOnCb3a76wBgpZaCbhJcot%2Bfgl1oHna2LigHHAYRaXg8dNLiJYHes0ezAaIdXLhVNGQBo%2FBAte6%2ByNcaZku5cV19FPyiD2%2BKXJeEtnFN6pJUsUA77sxk%2FfWxOFU%3D"}],"group":"cf-nel","max_age":604800}] Server:[cloudflare] Vary:[Accept, Origin] X-Api-Ratelimit-Consumed:[0] X-Api-Ratelimit-Limit:[100000] X-Api-Ratelimit-Remaining:[99973] X-Api-Ratelimit-Reset:[1708439400] X-Api-Response-Log-Id:[88061028] X-Content-Type-Options:[nosniff] X-Frame-Options:[DENY]], Response: {"s":"ok","t":[1672756200,1672770600,1672842600,1672857000],"o":[130.28,124.6699,126.89,127.265],"h":[130.9,125.42,128.6557,127.87],"l":[124.19,124.17,125.08,125.28],"c":[124.6499,125.05,127.2601,126.38],"v":[64411753,30727802,49976607,28870878]}}

type MarketDataClient

type MarketDataClient struct {
	*resty.Client                // Embedding resty.Client to utilize its HTTP client functionalities.
	RateLimitLimit     int       // RateLimitLimit represents the maximum number of requests that can be made in a rate limit window.
	RateLimitRemaining int       // RateLimitRemaining tracks the number of requests that can still be made before hitting the rate limit.
	RateLimitReset     time.Time // RateLimitReset indicates the time when the rate limit will be reset.
	// contains filtered or unexported fields
}

MarketDataClient struct defines the structure for the MarketData client instance. It embeds the resty.Client to inherit the HTTP client functionalities. Additionally, it includes fields for managing rate limits and synchronization, as well as an error field for capturing any errors that occur during API calls. The debug field is used to control logging verbosity.

Setter Methods

  • Debug(bool): Enables or disables debug mode for logging detailed request and response information.
  • Environment(Environment): Sets the environment for the MarketDataClient.
  • Timeout(int): Sets the request timeout for the MarketDataClient.
  • Token(string) error: Sets the authentication token for the MarketDataClient.

Methods

  • RateLimitExceeded() bool: Checks if the rate limit for API requests has been exceeded.
  • String() string: Generates a formatted string that represents the MarketDataClient instance.

func GetClient

func GetClient() (*MarketDataClient, error)

GetClient checks for an existing instance of MarketDataClient and returns it. It is the starting point to interact with MarketDataClient when using environment variables. GetClient is only needed if you need to change some parameter of the client, like the timeout or you wish to access the Rate Limit information. If you just want to make requests, you can use the request initialization functions directly.

Returns

  • *MarketDataClient: A pointer to the existing or newly initialized MarketDataClient instance.
  • error: An error object if the client cannot be initialized.

func NewClient

func NewClient(token string) (*MarketDataClient, error)

NewClient creates and configures a new MarketDataClient instance with default settings. This method is primarily used to initialize a client when you are not using environment variables to store your token. NewClient sets the token and initializes the client with predefined configurations such as the default rate limit reset time, and common HTTP headers and hooks. It's the starting point for interacting with MarketDataClient when you do not use environment variables.

Returns

  • *MarketDataClient: A pointer to the MarketDataClient instance.
  • error: An error if the token failed to authorize with the Market Data API or nil if authorization was successful.

func (*MarketDataClient) Debug

func (c *MarketDataClient) Debug(enable bool)

Debug enables or disables debug mode for the MarketDataClient. When debug mode is enabled, the client logs detailed request and response information, which can be useful for development and troubleshooting.

Parameters

  • bool: A boolean value indicating whether to enable or disable debug mode.

func (*MarketDataClient) Environment

func (c *MarketDataClient) Environment(env Environment) error

Environment configures the base URL of the MarketDataClient based on the provided environment string. This method allows the client to switch between different environments such as production, testing, and development.

Parameters

  • string: A string representing the environment to configure. Accepted values are "prod", "test", and "dev".

Returns

  • *MarketDataClient: A pointer to the *MarketDataClient instance with the configured environment. This allows for method chaining.

If an invalid environment is provided, the client's Error field is set, and the same instance is returned.

func (*MarketDataClient) RateLimitExceeded

func (c *MarketDataClient) RateLimitExceeded() bool

RateLimitExceeded checks if the rate limit for API requests has been exceeded. It returns true if the number of remaining requests is less than or equal to zero and the current time is before the rate limit reset time, indicating that the client must wait before making further requests. Otherwise, it returns false, indicating that the client can continue making requests.

Returns

  • bool: A boolean value indicating whether the rate limit has been exceeded.

func (*MarketDataClient) String

func (c *MarketDataClient) String() string

String generates a formatted string that represents the MarketDataClient instance, including its environment, rate limit information, and the rate limit reset time. This method is useful for quickly obtaining a textual summary of the client's current state, particularly for logging or debugging purposes.

Returns

  • string: A formatted string containing the client's environment, rate limit information, and rate limit reset time.

func (*MarketDataClient) Timeout added in v1.1.0

func (c *MarketDataClient) Timeout(seconds int)

Timeout sets the request timeout for the MarketDataClient.

This method allows users to specify a custom timeout duration for all HTTP requests made by the client. The timeout duration is specified in seconds. Setting a timeout helps in preventing indefinitely hanging requests in case of network issues or slow server responses.

By default the client has a timeout of 95 seconds. The timeout may be lowered, but it cannot be increased. Valid timeouts are between 1 and 95 seconds. Setting the timeout to any invalid integer will cause the client to use the default timeout of 95 seconds.

Parameters

  • int: The timeout duration in seconds. A duration of 0 means no timeout.

func (*MarketDataClient) Token

func (c *MarketDataClient) Token(bearerToken string) error

Token configures the authentication token for the MarketDataClient. This method sets the authentication scheme to "Bearer" and assigns the provided bearerToken for subsequent requests. It also makes an initial request to the MarketData API to authorize the token and fetch rate limit information.

Parameters

  • string: A string representing the bearer token to be used for API requests.

Returns

  • error: An error if the authorization was not successful or nil if it was.

Notes

If an error occurs during the initial authorization request or if the response indicates a failure, the client remains unmodified. The token will only be set if authorization is successful.

type MarketDataLogs added in v1.1.0

type MarketDataLogs struct {
	// MaxLogEntries defines the maximum number of log entries that will be stored in memory.
	// Beyond this limit, older entries may be evicted or ignored.
	MaxEntries int

	// MemoryLimit specifies the maximum amount of memory (in bytes) that can be used for
	// storing log entries.  This helps in preventing excessive memory usage by in-memory
	// log storage.
	MemoryLimit int64

	// SuccessLogger is a zap logger used for logging successful operations.
	SuccessLogger *zap.Logger

	// ClientErrorLogger is a zap logger used for logging client-side errors.
	ClientErrorLogger *zap.Logger

	// ServerErrorLogger is a zap logger used for logging server-side errors.
	ServerErrorLogger *zap.Logger

	// Logs is the slice of LogEntry that contain all the request logs.
	Logs []LogEntry
}

MarketDataLogs represents a collection of HTTP request logs. It provides methods to manipulate and retrieve log entries.

Methods

  • String() string: Returns a string representation of all HTTP request logs.
  • PrintLatest(): Prints the latest HTTP request log entry.
  • LatestString() string : Gets the HTTP body response of the last log entry in string format.

func GetLogs

func GetLogs() *MarketDataLogs

GetLogs retrieves a pointer to the MarketDataLogs instance, allowing access to the logs collected during HTTP requests. This method is primarily used for debugging and monitoring purposes, providing insights into the HTTP request lifecycle and any issues that may have occurred.

Returns

  • *MarketDataLogs: A pointer to the MarketDataLogs instance containing logs of HTTP requests.

func (*MarketDataLogs) LatestString added in v1.1.0

func (l *MarketDataLogs) LatestString() string

LatestString returns the response of the last log entry in the MarketDataLogs.

This method checks if there are any logs present. If there are no logs, it returns a message indicating that no logs are available. If logs are present, it calculates the index of the last log entry, accesses it, and returns its response.

Returns

  • string: A string representing the response of the last log entry. If no logs are available, returns "No logs available".

func (*MarketDataLogs) PrintLatest added in v1.1.0

func (l *MarketDataLogs) PrintLatest()

PrintLatest prints the latest HTTP request log entry.

func (*MarketDataLogs) String added in v1.1.0

func (l *MarketDataLogs) String() string

String returns a string representation of all HTTP request logs.

Returns

  • string: A string representing all log entries, with log entry numbers starting at 0.

Example

MarketDataLogs{
  LogEntry[0]: {Timestamp: 2024-02-19 15:16:30 -05:00, Status: 200, Request: https://api.marketdata.app/v1/stocks/candles/4H/AAPL/?from=2023-01-01&to=2023-01-04, RequestHeaders: map[Authorization:[Bearer **********************************************************8IH6] User-Agent:[sdk-go/1.1.0]], RayID: 8581301bc9e974ca-MIA, RateLimitConsumed: 0, Delay: 1002ms, Response Headers: map[Allow:[GET, HEAD, OPTIONS] Alt-Svc:[h3=":443"; ma=86400] Cf-Cache-Status:[DYNAMIC] Cf-Ray:[8581301bc9e974ca-MIA] Content-Type:[application/json] Cross-Origin-Opener-Policy:[same-origin] Date:[Mon, 19 Feb 2024 20:16:30 GMT] Nel:[{"success_fraction":0,"report_to":"cf-nel","max_age":604800}] Referrer-Policy:[same-origin] Report-To:[{"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=ar7qRMEAxiHJcyRqlRlZvfzqv80inCp91LwdsxTfo51%2FSmdqz6NoadysPyFlMZKtDMG1IsDllX0GXXPjNsvjg4gQBr%2FLJ8G5Ad1z5lDXfhqrSee7umXzVf7dYmAFwq4x4sPMANE%3D"}],"group":"cf-nel","max_age":604800}] Server:[cloudflare] Vary:[Accept, Origin] X-Api-Ratelimit-Consumed:[0] X-Api-Ratelimit-Limit:[100000] X-Api-Ratelimit-Remaining:[99973] X-Api-Ratelimit-Reset:[1708439400] X-Api-Response-Log-Id:[88078705] X-Content-Type-Options:[nosniff] X-Frame-Options:[DENY]], Response: {"s":"ok","t":[1672756200,1672770600,1672842600,1672857000],"o":[130.28,124.6699,126.89,127.265],"h":[130.9,125.42,128.6557,127.87],"l":[124.19,124.17,125.08,125.28],"c":[124.6499,125.05,127.2601,126.38],"v":[64411753,30727802,49976607,28870878]}}
}

type MarketDataPacked

type MarketDataPacked interface {
	IsValid() bool
	Unpack() any
}

type MarketStatusRequest

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

MarketStatusRequest represents a request to the /v1/markets/status/ endpoint for market status information. It encapsulates parameters for country, and date to be used in the request. This struct provides methods such as Country(), Date(), From(), To(), and Countback() to set these parameters respectively.

Generated By

  • MarketStatus() *MarketStatusRequest: MarketStatus creates a new *MarketStatusRequest and returns a pointer to the request allowing for method chaining.

Setter Methods

  • Country(string) *MarketStatusRequest: Sets the country parameter for the request.
  • Date(interface{}) *MarketStatusRequest: Sets the date parameter for the request.
  • From(interface{}) *MarketStatusRequest: Sets the 'from' date parameter for the request.
  • To(interface{}) *MarketStatusRequest: Sets the 'to' date parameter for the request.
  • Countback(int) *MarketStatusRequest: Sets the countback parameter for the request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() ([]MarketStatusReport, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed() (*MarketStatusResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.

func MarketStatus

func MarketStatus() *MarketStatusRequest

MarketStatus creates a new MarketStatusRequest. This function initializes the request with default parameters for country, universal, and date, and sets the request path based on the predefined endpoints for market status.

Returns

  • *MarketStatusRequest: A pointer to the newly created *MarketStatusRequest with default parameters.
Example (Get)
msr, err := MarketStatus().From("2022-01-01").To("2022-01-10").Get()
if err != nil {
	fmt.Print(err)
	return
}

for _, report := range msr {
	fmt.Println(report)
}
Output:

MarketStatusReport{Date: 2022-01-01, Open: false, Closed: true}
MarketStatusReport{Date: 2022-01-02, Open: false, Closed: true}
MarketStatusReport{Date: 2022-01-03, Open: true, Closed: false}
MarketStatusReport{Date: 2022-01-04, Open: true, Closed: false}
MarketStatusReport{Date: 2022-01-05, Open: true, Closed: false}
MarketStatusReport{Date: 2022-01-06, Open: true, Closed: false}
MarketStatusReport{Date: 2022-01-07, Open: true, Closed: false}
MarketStatusReport{Date: 2022-01-08, Open: false, Closed: true}
MarketStatusReport{Date: 2022-01-09, Open: false, Closed: true}
MarketStatusReport{Date: 2022-01-10, Open: true, Closed: false}
Example (Packed)
msr, err := MarketStatus().From("2022-01-01").To("2022-01-10").Packed()
if err != nil {
	fmt.Print(err)
	return
}

fmt.Println(msr)
Output:

MarketStatusResponse{Date: [1641013200, 1641099600, 1641186000, 1641272400, 1641358800, 1641445200, 1641531600, 1641618000, 1641704400, 1641790800], Status: ["closed", "closed", "open", "open", "open", "open", "open", "closed", "closed", "open"]}

func (*MarketStatusRequest) Countback

func (msr *MarketStatusRequest) Countback(q int) *MarketStatusRequest

Countback sets the countback parameter for the MarketStatusRequest. It specifies the number of days to return, counting backwards from the 'to' date.

Parameters

  • int: The number of days to return before `to`.

Returns

  • *MarketStatusRequest: A pointer to the MarketStatusRequest instance to allow for method chaining.

func (*MarketStatusRequest) Country

Country sets the country parameter of the MarketStatusRequest. This method is used to specify the country for which the market status is requested. It modifies the countryParams field of the MarketStatusRequest instance to store the country value.

Parameters

  • q: A string representing the country to be set.

Returns

  • *MarketStatusRequest: This method returns a pointer to the MarketStatusRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement. If the receiver (*MarketStatusRequest) is nil, it returns nil to prevent a panic.

func (*MarketStatusRequest) Date

func (msr *MarketStatusRequest) Date(q interface{}) *MarketStatusRequest

Date sets the date parameter of the MarketStatusRequest. This method is used to specify the date for which the market status is requested. It modifies the dateParams field of the MarketStatusRequest instance to store the date value.

Parameters

  • interface{}: An interface{} that represents the starting date. It can be a string, a time.Time object, a Unix timestamp or any other type that the underlying dates package can process.

Returns

  • *MarketStatusRequest: This method returns a pointer to the MarketStatusRequest instance it was called on. This allows for method chaining. If the receiver (*MarketStatusRequest) is nil, it returns nil to prevent a panic.

func (*MarketStatusRequest) From

func (msr *MarketStatusRequest) From(q interface{}) *MarketStatusRequest

From sets the 'from' date parameter of the MarketStatusRequest. This method is used to specify the starting date of the period for which the market status is requested. It modifies the dateParams field of the MarketStatusRequest instance to store the 'from' date value.

Parameters

  • interface{}: The 'from' date to be set.

Returns

  • *MarketStatusRequest: This method returns a pointer to the MarketStatusRequest instance it was called on. This allows for method chaining. If the receiver (*MarketStatusRequest) is nil, it returns nil to prevent a panic.

func (*MarketStatusRequest) Get

Get sends the MarketStatusRequest, unpacks the MarketStatusResponse, and returns a slice of MarketStatusReport. It returns an error if the request or unpacking fails. This method is crucial for obtaining the actual market status data from the market status request. The method first checks if the MarketStatusRequest receiver is nil, which would result in an error as the request cannot be sent. It then proceeds to send the request using the Packed method. Upon receiving the response, it unpacks the data into a slice of MarketStatusReport using the Unpack method from the response.

Returns

  • []models.MarketStatusReport: A slice of MarketStatusReport containing the unpacked market status data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*MarketStatusRequest) Packed

Packed sends the MarketStatusRequest and returns the MarketStatusResponse. This method checks if the MarketStatusRequest receiver is nil, returning an error if true. It proceeds to send the request and returns the MarketStatusResponse along with any error encountered during the request.

Returns

  • *models.MarketStatusResponse: A pointer to the *MarketStatusResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*MarketStatusRequest) Raw

func (msr *MarketStatusRequest) Raw() (*resty.Response, error)

Raw executes the MarketStatusRequest and returns the raw *resty.Response. The *resty.Response can be directly used to access the raw JSON or *http.Response for further processing.

Returns

  • *resty.Response: The raw HTTP response from the executed MarketStatusRequest.
  • error: An error object if the MarketStatusRequest is nil or if an error occurs during the request execution.

func (*MarketStatusRequest) To

func (msr *MarketStatusRequest) To(q interface{}) *MarketStatusRequest

To sets the 'to' date parameter of the MarketStatusRequest. This method is used to specify the ending date of the period for which the market status is requested. It modifies the dateParams field of the MarketStatusRequest instance to store the 'to' date value.

Parameters

  • interface{}: The 'to' date to be set.

Returns

  • *MarketStatusRequest: This method returns a pointer to the MarketStatusRequest instance it was called on. This allows for method chaining. If the receiver (*MarketStatusRequest) is nil, it returns nil to prevent a panic.

type OptionChainRequest

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

OptionChainRequest represents a request to the /v1/options/chain/ endpoint. It encapsulates parameters for symbol, date, and various option-specific parameters to be used in the request. This struct provides methods to set these parameters, such as UnderlyingSymbol(), Date(), Expiration(), and Strike(), among others.

Generated By

  • OptionChain() *OptionChainRequest: OptionChain creates a new *OptionChainRequest and returns a pointer to the request allowing for method chaining.

Setter Methods

These methods are used to set the parameters of the request. They allow for method chaining by returning a pointer to the *OptionChainRequest instance they modify.

  • UnderlyingSymbol(string) *OptionChainRequest: Sets the underlying symbol parameter for the request.
  • Date(interface{}) *OptionChainRequest: Sets the date parameter for the request.
  • Expiration(interface{}) *OptionChainRequest: Sets the expiration parameter for the request.
  • Strike(float64) *OptionChainRequest: Sets the strike price parameter for the request.
  • Monthly(bool) *OptionChainRequest: Inclues or excludes monthly option expirations from the result.
  • Weekly(bool) *OptionChainRequest: Inclues or excludes weekly option expirations from the result.
  • Quarterly(bool) *OptionChainRequest: Inclues or excludes quarterly option expirations from the result.
  • Nonstandard(bool) *OptionChainRequest: Inclues or excludes non-standard option expirations from the result.
  • Month(int) *OptionChainRequest: Requests results from the specific specific month.
  • Year(int) *OptionChainRequest: Sets the year parameter for the request.
  • DTE(int) *OptionChainRequest: Sets the Days to Expiration parameter for the request.
  • Delta(float64) *OptionChainRequest: Sets the Delta parameter for the request.
  • Side(string) *OptionChainRequest: Sets the side of the market (call or put) for the request.
  • Range(string) *OptionChainRequest: Sets the range parameter for the request.
  • StrikeLimit(int) *OptionChainRequest: Sets the maximum number of strike prices to be included in the option chain.
  • MinOpenInterest(int) *OptionChainRequest: Sets the minimum open interest for options to be included in the option chain.
  • MinVolume(int) *OptionChainRequest: Sets the minimum volume for options to be included in the option chain.
  • MaxBidAskSpread(float64) *OptionChainRequest: Sets the maximum bid-ask spread for options to be included in the option chain.
  • MaxBidAskSpreadPct(float64) *OptionChainRequest: Sets the maximum bid-ask spread percentage for options to be included in the option chain.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() ([]OptionQuote, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed() (*OptionQuotesResponse, error): Packs the request parameters and sends the request, returning a *OptionQuotesResponse response.
  • Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
Example (Get)
resp, err := OptionChain().UnderlyingSymbol("AAPL").Side("call").Date("2022-01-03").DTE(60).StrikeLimit(2).Range("itm").Get()
if err != nil {
	fmt.Println("Error fetching option chain:", err)
	return
}
for _, contract := range resp {
	fmt.Println(contract)
}
Output:

OptionQuote{OptionSymbol: "AAPL220318C00175000", Underlying: "AAPL", Expiration: 2022-03-18 16:00:00 -04:00, Side: "call", Strike: 175, FirstTraded: 2021-07-13 09:30:00 -04:00, DTE: 73, Ask: 13.1, AskSize: 2, Bid: 12.95, BidSize: 3, Mid: 13.02, Last: 12.9, Volume: 1295, OpenInterest: 15232, UnderlyingPrice: 182.01, InTheMoney: true, Updated: "2022-01-03 16:00:00 -05:00", IV: nil, Delta: nil, Gamma: nil, Theta: nil, Vega: nil, Rho: nil, IntrinsicValue: 7.01, ExtrinsicValue: 6.02}
OptionQuote{OptionSymbol: "AAPL220318C00180000", Underlying: "AAPL", Expiration: 2022-03-18 16:00:00 -04:00, Side: "call", Strike: 180, FirstTraded: 2021-07-13 09:30:00 -04:00, DTE: 73, Ask: 10.2, AskSize: 12, Bid: 10, BidSize: 38, Mid: 10.1, Last: 10.1, Volume: 4609, OpenInterest: 18299, UnderlyingPrice: 182.01, InTheMoney: true, Updated: "2022-01-03 16:00:00 -05:00", IV: nil, Delta: nil, Gamma: nil, Theta: nil, Vega: nil, Rho: nil, IntrinsicValue: 2.01, ExtrinsicValue: 8.09}
Example (Packed)
resp, err := OptionChain().UnderlyingSymbol("AAPL").Side("call").Date("2022-01-03").
	Month(2).Year(2022).Range("itm").Strike(150).Weekly(false).Monthly(true).Quarterly(false).Nonstandard(false).Packed()
if err != nil {
	fmt.Println("Error fetching packed option chain:", err)
	return
}
fmt.Println(resp)
Output:

OptionQuotesResponse{OptionSymbol: ["AAPL220121C00150000"], Underlying: ["AAPL"], Expiration: [1642798800], Side: ["call"], Strike: [150], FirstTraded: [1568640600], DTE: [18], Ask: [32.15], AskSize: [2], Bid: [31.8], BidSize: [359], Mid: [31.98], Last: [32], Volume: [3763], OpenInterest: [98804], UnderlyingPrice: [182.01], InTheMoney: [true], Updated: [1641243600], IV: [nil], Delta: [nil], Gamma: [], Theta: [nil], Vega: [nil], Rho: [nil], IntrinsicValue: [32.01], ExtrinsicValue: [0.03]}

func OptionChain

func OptionChain() *OptionChainRequest

OptionChain creates a new OptionChainRequest and associates it with the default client. This function initializes the request with default parameters for symbol, date, and option-specific parameters, and sets the request path based on the predefined endpoints for option chains.

Returns

  • *OptionChainRequest: A pointer to the newly created OptionChainRequest with default parameters and associated client.

func (*OptionChainRequest) DTE

func (ocr *OptionChainRequest) DTE(dte int) *OptionChainRequest

DTE (Days to Expiration) sets the DTE parameter for the OptionChainRequest. This method specifies the number of days to expiration for the options in the option chain.

Parameters

  • int: Requests an expiration date from the option chain based on the number of days from the present date.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Date

func (ocr *OptionChainRequest) Date(q interface{}) *OptionChainRequest

Date sets the date parameter for the OptionChainRequest. This method is used to specify the date for which the option chain is requested. It modifies the dateParams field of the OptionChainRequest instance to store the date value.

Parameters

  • interface{}: An interface{} that represents the starting date. It can be a string, a time.Time object, a Unix timestamp or any other type that the underlying dates package can process.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Delta

func (ocr *OptionChainRequest) Delta(delta float64) *OptionChainRequest

Delta sets the Delta parameter for the OptionChainRequest. This method is used to specify a particular Delta value for the options in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the Delta value.

Parameters

  • float64: The Delta value to be set.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Expiration

func (ocr *OptionChainRequest) Expiration(q interface{}) *OptionChainRequest

Expiration sets the expiration parameter for the OptionChainRequest. This method is used to specify the expiration date for the options in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the expiration value.

Parameters

  • interface{}: An interface{} representing the expiration date to be set.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Get

func (ocr *OptionChainRequest) Get() ([]models.OptionQuote, error)

Get sends the OptionChainRequest, unpacks the OptionChainResponse, and returns a slice of OptionQuote. It returns an error if the request or unpacking fails. This method is crucial for obtaining the actual option chain data from the option chain request. The method first checks if the OptionChainRequest receiver is nil, which would result in an error as the request cannot be sent. It then proceeds to send the request using the default client. Upon receiving the response, it unpacks the data into a slice of OptionQuote using the Unpack method from the response.

Returns

  • []models.OptionQuote: A slice of OptionQuote containing the unpacked option chain data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*OptionChainRequest) MaxBidAskSpread

func (ocr *OptionChainRequest) MaxBidAskSpread(maxBidAskSpread float64) *OptionChainRequest

MaxBidAskSpread sets the MaxBidAskSpread parameter for the OptionChainRequest. This method is used to specify the maximum bid-ask spread for options to be included in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the maximum bid-ask spread value.

Parameters

  • float64: A float64 representing the maximum bid-ask spread neeeded to be included in the result.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) MaxBidAskSpreadPct

func (ocr *OptionChainRequest) MaxBidAskSpreadPct(maxBidAskSpreadPct float64) *OptionChainRequest

MaxBidAskSpreadPct sets the MaxBidAskSpreadPct parameter for the OptionChainRequest. This method is used to specify the maximum bid-ask spread percentage for options to be included in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the maximum bid-ask spread percentage value.

Parameters

  • float64: A float64 representing the maximum bid-ask spread percentage to be included in the result.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) MinOpenInterest

func (ocr *OptionChainRequest) MinOpenInterest(minOpenInterest int) *OptionChainRequest

MinOpenInterest sets the MinOpenInterest parameter for the OptionChainRequest. This method is used to specify the minimum open interest for options to be included in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the minimum open interest value.

Parameters

  • int: An int representing the minimum open interest required to be included in the result.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) MinVolume

func (ocr *OptionChainRequest) MinVolume(minVolume int) *OptionChainRequest

MinVolume sets the MinVolume parameter for the OptionChainRequest. This method is used to specify the minimum volume for options to be included in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the minimum volume value.

Parameters

  • int: An int representing the minimum volume needed to be included in the result.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Month

func (ocr *OptionChainRequest) Month(month int) *OptionChainRequest

Month sets the month parameter for the OptionChainRequest. This method is used to specify the month for which the option chain is requested. It modifies the optionParams field of the OptionChainRequest instance to store the month value.

Parameters

  • int: The month to be set.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Monthly

func (ocr *OptionChainRequest) Monthly(monthly bool) *OptionChainRequest

Monthly sets the monthly parameter for the OptionChainRequest. This method is used to specify whether to include monthly options in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the monthly value.

Parameters

  • bool: Whether to include monthly options.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Nonstandard

func (ocr *OptionChainRequest) Nonstandard(nonstandard bool) *OptionChainRequest

Nonstandard sets the nonstandard parameter for the OptionChainRequest. This method is used to specify whether to include nonstandard options in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the nonstandard value.

Parameters

  • bool: Whether to include nonstandard options.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Packed

Packed sends the OptionChainRequest and returns the OptionChainResponse. This method checks if the OptionChainRequest receiver is nil, returning an error if true. It proceeds to send the request using the default client and returns the OptionChainResponse along with any error encountered during the request.

Returns

  • *models.OptionQuotesResponse: A pointer to the OptionQuotesResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*OptionChainRequest) Quarterly

func (ocr *OptionChainRequest) Quarterly(quarterly bool) *OptionChainRequest

Quarterly sets the quarterly parameter for the OptionChainRequest. This method is used to specify whether to include quarterly options in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the quarterly value.

Parameters

  • bool: Whether to include quarterly options.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Range

func (ocr *OptionChainRequest) Range(rangeParam string) *OptionChainRequest

Range sets the Range parameter for the OptionChainRequest. This method is used to specify the range of options to be included in the option chain based on their strike price. It modifies the optionParams field of the OptionChainRequest instance to store the range value.

Parameters

  • string: A string representing the range of options to be included. The expected values can vary, such as "ITM" (In The Money), "OTM" (Out of The Money), "ATM" (At The Money), etc.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Raw

func (ocr *OptionChainRequest) Raw() (*resty.Response, error)

Raw executes the OptionChainRequest and returns the raw *resty.Response. This method uses the default client for this request. The *resty.Response can be directly used to access the raw JSON or *http.Response.

Returns

  • *resty.Response: The raw HTTP response from the executed OptionChainRequest.
  • error: An error object if the OptionChainRequest is nil or if an error occurs during the request execution.

func (*OptionChainRequest) Side

func (ocr *OptionChainRequest) Side(side string) *OptionChainRequest

Side sets the Side parameter for the OptionChainRequest. This method is used to specify the side of the market for the options in the option chain (e.g., call or put). It modifies the optionParams field of the OptionChainRequest instance to store the side value.

Parameters

  • string: A string representing the side of the market chain to be set. Expected value is "call" or "put".

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Strike

func (ocr *OptionChainRequest) Strike(strike float64) *OptionChainRequest

Strike sets the strike price parameter for the OptionChainRequest. This method is used to specify a particular strike price for the options in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the strike price value.

Parameters

  • float64: The strike price to be set.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) StrikeLimit

func (ocr *OptionChainRequest) StrikeLimit(strikeLimit int) *OptionChainRequest

StrikeLimit sets the StrikeLimit parameter for the OptionChainRequest. This method is used to specify the maximum number of strike prices to be included in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the strike limit value.

Parameters

  • int: The maximum number of strikes to be included.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) UnderlyingSymbol

func (ocr *OptionChainRequest) UnderlyingSymbol(q string) *OptionChainRequest

UnderlyingSymbol sets the underlyingSymbol parameter for the OptionChainRequest. This method is used to specify the symbol of the underlying asset for which the option chain is requested. It modifies the symbolParams field of the OptionChainRequest instance to store the symbol value.

Parameters

  • string: The underlying symbol to be set.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Weekly

func (ocr *OptionChainRequest) Weekly(weekly bool) *OptionChainRequest

Weekly sets the weekly parameter for the OptionChainRequest. This method is used to specify whether to include weekly options in the option chain. It modifies the optionParams field of the OptionChainRequest instance to store the weekly value.

Parameters

  • bool: Whether to include weekly options.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

func (*OptionChainRequest) Year

func (ocr *OptionChainRequest) Year(year int) *OptionChainRequest

Year sets the year parameter for the OptionChainRequest. This method is used to specify the year for which the option chain is requested. It modifies the optionParams field of the OptionChainRequest instance to store the year value.

Parameters

  • int: The year to be set.

Returns

  • *OptionChainRequest: This method returns a pointer to the OptionChainRequest instance it was called on. This allows for method chaining. If the receiver (*OptionChainRequest) is nil, it returns nil to prevent a panic.

type OptionLookupRequest

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

OptionsLookupRequest represents a request to the /v1/options/lookup/ endpoint for retrieving an OCC-formatted option symbol based on user input. It encapsulates parameters for user input to be used in the request.

Generated By

  • OptionsLookup() *OptionsLookupRequest: OptionsLookup creates a new *OptionsLookupRequest and returns a pointer to the request allowing for method chaining.

Setter Methods

  • UserInput(string) *OptionLookupRequest: Sets the user input parameter for the request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() (string, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed() (*OptionLookupResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
Example (Get)
resp, err := OptionLookup().UserInput("AAPL 7/28/2023 200 Call").Get()
if err != nil {
	fmt.Print(err)
	return
}

fmt.Println(resp)
Output:

AAPL230728C00200000
Example (Packed)
resp, err := OptionLookup().UserInput("AAPL 7/28/2023 200 Call").Packed()
if err != nil {
	fmt.Print(err)
	return
}

fmt.Println(resp)
Output:

OptionLookupResponse{OptionSymbol: "AAPL230728C00200000"}

func OptionLookup

func OptionLookup() *OptionLookupRequest

OptionLookup creates a new OptionsLookupRequest and uses the default client.

Returns

  • *OptionsLookupRequest: A pointer to the newly created OptionsLookupRequest with default parameters and associated client.

func (*OptionLookupRequest) Get

func (o *OptionLookupRequest) Get() (string, error)

Get sends the OptionLookupRequest, unpacks the OptionsLookupResponse, and returns the unpacked data as a string. It returns an error if the request or unpacking fails.

Returns

  • string: A string containing the unpacked options data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*OptionLookupRequest) Packed

Packed sends the OptionLookupRequest and returns the OptionsLookupResponse.

Returns

  • *models.OptionsLookupResponse: A pointer to the OptionsLookupResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*OptionLookupRequest) Raw

func (olr *OptionLookupRequest) Raw() (*resty.Response, error)

Raw executes the OptionLookupRequest and returns the raw *resty.Response. The *resty.Response allows access to the raw JSON or *http.Response for further processing.

Returns

  • *resty.Response: The raw HTTP response from the executed OptionLookupRequest.
  • error: An error object if the request fails due to being nil, or other execution errors.

func (*OptionLookupRequest) UserInput

func (o *OptionLookupRequest) UserInput(userInput string) *OptionLookupRequest

UserInput sets the user input parameter for the OptionsLookupRequest. This method is used to specify the user input for which the options data is requested.

Parameters

  • string: A string representing the text to lookup with the OptionsLookupRequest endpoint.

Returns

  • *OptionsLookupRequest: This method returns a pointer to the OptionsLookupRequest instance it was called on, allowing for method chaining.

type OptionQuoteRequest

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

OptionQuotesRequest represents a request to the /v1/options/quotes/ endpoint for retrieving options quotes. It encapsulates parameters for symbol, expiration, and strike to be used in the request.

Generated By

  • OptionQuotes() *OptionQuoteRequest: OptionQuotes creates a new *OptionQuoteRequest and returns a pointer to the request allowing for method chaining.

Setter Methods

  • OptionSymbol(string) *OptionQuoteRequest: Sets the symbol parameter for the request.
  • Date(interface{}) *OptionQuoteRequest: Sets the date parameter for the request, accepting flexible date input.
  • From(interface{}) *OptionQuoteRequest: Sets the start date of a date range for the request, accepting flexible date input.
  • To(interface{}) *OptionQuoteRequest: Sets the end date of a date range for the request, accepting flexible date input.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() ([]OptionQuote, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed() (*OptionQuotesResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
Example (Get)
resp, err := OptionQuote().OptionSymbol("AAPL250117C00150000").Date("2024-02-05").Get()
if err != nil {
	fmt.Print(err)
	return
}

for _, quote := range resp {
	fmt.Println(quote)
}
Output:

OptionQuote{OptionSymbol: "AAPL250117C00150000", Underlying: "AAPL", Expiration: 2025-01-17 16:00:00 -05:00, Side: "call", Strike: 150, FirstTraded: 2022-09-10 09:30:00 -04:00, DTE: 347, Ask: 47.7, AskSize: 17, Bid: 47.2, BidSize: 36, Mid: 47.45, Last: 48.65, Volume: 202, OpenInterest: 10768, UnderlyingPrice: 187.68, InTheMoney: true, Updated: "2024-02-05 16:00:00 -05:00", IV: nil, Delta: nil, Gamma: nil, Theta: nil, Vega: nil, Rho: nil, IntrinsicValue: 37.68, ExtrinsicValue: 9.77}
Example (Packed)
resp, err := OptionQuote().OptionSymbol("AAPL250117P00150000").Date("2024-02-05").Packed()
if err != nil {
	fmt.Print(err)
	return
}

fmt.Println(resp)
Output:

OptionQuotesResponse{OptionSymbol: ["AAPL250117P00150000"], Underlying: ["AAPL"], Expiration: [1737147600], Side: ["put"], Strike: [150], FirstTraded: [1662816600], DTE: [347], Ask: [3.65], AskSize: [292], Bid: [3.5], BidSize: [634], Mid: [3.58], Last: [3.55], Volume: [44], OpenInterest: [18027], UnderlyingPrice: [187.68], InTheMoney: [false], Updated: [1707166800], IV: [], Delta: [], Gamma: [], Theta: [], Vega: [], Rho: [], IntrinsicValue: [0], ExtrinsicValue: [3.58]}

func OptionQuote

func OptionQuote() *OptionQuoteRequest

OptionQuotes creates a new OptionQuotesRequest and uses the default client.

Returns

  • *OptionQuotesRequest: A pointer to the newly created OptionQuotesRequest with default parameters.

func (*OptionQuoteRequest) Date

func (oqr *OptionQuoteRequest) Date(q interface{}) *OptionQuoteRequest

Date sets the date parameter for the OptionQuotesRequest. This method is used to specify the date for which the option quote is requested. It allows for flexibility in the type of date input (e.g., string, time.Time) through the use of an interface{} parameter.

Parameters

  • interface{}: The date to be set. The actual type accepted can vary (e.g., string, time.Time, int for Unix timestamp).

Returns

  • *OptionQuotesRequest: This method returns a pointer to the OptionQuotesRequest instance it was called on, allowing for method chaining. If the receiver (*OptionQuotesRequest) is nil, it returns nil to prevent a panic.

func (*OptionQuoteRequest) From

func (oqr *OptionQuoteRequest) From(q interface{}) *OptionQuoteRequest

From sets the from parameter for the OptionQuotesRequest. This method is used to specify the start date of a date range for which the option quote is requested. Similar to the Date method, it accepts a flexible date input through an interface{} parameter.

Parameters

  • interface{}: The start date of the range to be set. The actual type accepted can vary.

Returns

  • *OptionQuotesRequest: This method returns a pointer to the OptionQuotesRequest instance it was called on, allowing for method chaining. If the receiver (*OptionQuotesRequest) is nil, it returns nil to prevent a panic.

func (*OptionQuoteRequest) Get

func (oqr *OptionQuoteRequest) Get() ([]models.OptionQuote, error)

Get sends the OptionQuoteRequest, unpacks the OptionQuotesResponse, and returns a slice of OptionQuote. It returns an error if the request or unpacking fails. This method uses the default client for the request.

Returns

  • []models.OptionQuote: A slice of OptionQuote containing the unpacked options quotes data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*OptionQuoteRequest) OptionSymbol

func (oqr *OptionQuoteRequest) OptionSymbol(q string) *OptionQuoteRequest

OptionSymbol sets the symbol parameter for the OptionQuotesRequest. This method is used to specify the symbol of the option for which the quote is requested.

Parameters

  • string: A string representing the option symbol to be set.

Returns

  • *OptionQuotesRequest: This method returns a pointer to the OptionQuotesRequest instance it was called on, allowing for method chaining.

func (*OptionQuoteRequest) Packed

Packed sends the OptionQuoteRequest and returns the OptionQuotesResponse. This method uses the default client for the request.

Returns

  • *models.OptionQuotesResponse: A pointer to the OptionQuotesResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*OptionQuoteRequest) Raw

func (oqr *OptionQuoteRequest) Raw() (*resty.Response, error)

Raw executes the OptionQuoteRequest and returns the raw *resty.Response. This method uses the default client for the request. The *resty.Response can be used to access the raw JSON or *http.Response directly.

Returns

  • *resty.Response: The raw HTTP response from the executed request.
  • error: An error object if the OptionQuoteRequest is nil or if an error occurs during the request execution.

func (*OptionQuoteRequest) To

func (oqr *OptionQuoteRequest) To(q interface{}) *OptionQuoteRequest

To sets the to parameter for the OptionQuotesRequest. This method is used to specify the end date of a date range for which the option quote is requested. It accepts a flexible date input through an interface{} parameter, similar to the From method.

Parameters

  • interface{}: The end date of the range to be set. The actual type accepted can vary, depending on implementation.

Returns

  • *OptionQuotesRequest: This method returns a pointer to the OptionQuotesRequest instance it was called on, allowing for method chaining. If the receiver (*OptionQuotesRequest) is nil, it returns nil to prevent a panic.

type OptionStrikesRequest added in v1.1.0

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

OptionStrikesRequest represents a request to the /v1/options/strikes/ endpoint. It encapsulates parameters for underlying symbol, expiration, and date to be used in the request. This struct provides methods such as UnderlyingSymbol(), Expiration(), and Date() to set these parameters respectively.

Setter Methods

  • UnderlyingSymbol(string) *OptionStrikesRequest: Sets the underlying symbol parameter for the request.
  • Expiration(string) *OptionStrikesRequest: Sets the expiration parameter for the request.
  • Date(interface{}) *OptionStrikesRequest: Sets the date parameter for the request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() ([]OptionStrikes, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed() (*OptionStrikesResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
Example (Get)
resp, err := OptionStrikes().UnderlyingSymbol("AAPL").Date("2009-02-09").Get()
if err != nil {
	fmt.Print(err)
	return
}

for _, expiration := range resp {
	fmt.Println(expiration)
}
Output:

OptionStrikes{Expiration: 2009-02-21, Strikes: [40.00 45.00 50.00 55.00 60.00 65.00 70.00 75.00 80.00 85.00 90.00 95.00 100.00 105.00 110.00 115.00 120.00 125.00 130.00 135.00 140.00]}
OptionStrikes{Expiration: 2009-03-21, Strikes: [35.00 40.00 45.00 50.00 55.00 60.00 65.00 70.00 75.00 80.00 85.00 90.00 95.00 100.00 105.00 110.00 115.00 120.00 125.00 130.00 135.00]}
OptionStrikes{Expiration: 2009-04-18, Strikes: [15.00 17.50 20.00 22.50 25.00 30.00 35.00 40.00 45.00 50.00 55.00 60.00 65.00 70.00 75.00 80.00 85.00 90.00 95.00 100.00 105.00 110.00 115.00 120.00 125.00 130.00 135.00 140.00 145.00 150.00 155.00 160.00 165.00 170.00 175.00 180.00 185.00 190.00 195.00 200.00 210.00 220.00 230.00 240.00 250.00 260.00 270.00 280.00 290.00 300.00]}
OptionStrikes{Expiration: 2009-07-18, Strikes: [12.50 15.00 17.50 20.00 22.50 25.00 30.00 35.00 40.00 45.00 50.00 55.00 60.00 65.00 70.00 75.00 80.00 85.00 90.00 95.00 100.00 105.00 110.00 115.00 120.00 125.00 130.00 135.00 140.00 145.00 150.00 155.00 160.00 165.00 170.00 175.00 180.00 185.00 190.00]}
OptionStrikes{Expiration: 2010-01-16, Strikes: [22.50 25.00 30.00 35.00 40.00 45.00 50.00 55.00 60.00 65.00 70.00 75.00 80.00 85.00 90.00 95.00 100.00 105.00 110.00 120.00 125.00 130.00 135.00 140.00 145.00 150.00 155.00 160.00 170.00 180.00 190.00 200.00 210.00 220.00 230.00 240.00 250.00 260.00 270.00 280.00 290.00 300.00 310.00 320.00 330.00 340.00 350.00 360.00 370.00 380.00 390.00 400.00]}
OptionStrikes{Expiration: 2011-01-22, Strikes: [20.00 30.00 40.00 50.00 60.00 70.00 80.00 85.00 90.00 95.00 100.00 110.00 120.00 125.00 130.00 140.00 150.00 160.00 170.00 180.00 190.00 200.00 210.00 220.00 230.00 240.00]}
Example (Packed)
resp, err := OptionStrikes().UnderlyingSymbol("AAPL").Date("2009-02-09").Packed()
if err != nil {
	fmt.Print(err)
	return
}

fmt.Println(resp)
Output:

OptionStrikesResponse{Strikes: [2009-02-21:[40.00 45.00 50.00 55.00 60.00 65.00 70.00 75.00 80.00 85.00 90.00 95.00 100.00 105.00 110.00 115.00 120.00 125.00 130.00 135.00 140.00], 2009-03-21:[35.00 40.00 45.00 50.00 55.00 60.00 65.00 70.00 75.00 80.00 85.00 90.00 95.00 100.00 105.00 110.00 115.00 120.00 125.00 130.00 135.00], 2009-04-18:[15.00 17.50 20.00 22.50 25.00 30.00 35.00 40.00 45.00 50.00 55.00 60.00 65.00 70.00 75.00 80.00 85.00 90.00 95.00 100.00 105.00 110.00 115.00 120.00 125.00 130.00 135.00 140.00 145.00 150.00 155.00 160.00 165.00 170.00 175.00 180.00 185.00 190.00 195.00 200.00 210.00 220.00 230.00 240.00 250.00 260.00 270.00 280.00 290.00 300.00], 2009-07-18:[12.50 15.00 17.50 20.00 22.50 25.00 30.00 35.00 40.00 45.00 50.00 55.00 60.00 65.00 70.00 75.00 80.00 85.00 90.00 95.00 100.00 105.00 110.00 115.00 120.00 125.00 130.00 135.00 140.00 145.00 150.00 155.00 160.00 165.00 170.00 175.00 180.00 185.00 190.00], 2010-01-16:[22.50 25.00 30.00 35.00 40.00 45.00 50.00 55.00 60.00 65.00 70.00 75.00 80.00 85.00 90.00 95.00 100.00 105.00 110.00 120.00 125.00 130.00 135.00 140.00 145.00 150.00 155.00 160.00 170.00 180.00 190.00 200.00 210.00 220.00 230.00 240.00 250.00 260.00 270.00 280.00 290.00 300.00 310.00 320.00 330.00 340.00 350.00 360.00 370.00 380.00 390.00 400.00], 2011-01-22:[20.00 30.00 40.00 50.00 60.00 70.00 80.00 85.00 90.00 95.00 100.00 110.00 120.00 125.00 130.00 140.00 150.00 160.00 170.00 180.00 190.00 200.00 210.00 220.00 230.00 240.00]], Updated: 1234155600}

func OptionStrikes added in v1.1.0

func OptionStrikes() *OptionStrikesRequest

OptionStrikes creates a new OptionStrikesRequest and uses the default client. This function initializes the request with default parameters for underlying symbol, expiration, and date, and sets the request path based on the predefined endpoints for options strikes.

Returns

  • *OptionStrikesRequest: A pointer to the newly created OptionStrikesRequest with default parameters.

func (*OptionStrikesRequest) Date added in v1.1.0

func (o *OptionStrikesRequest) Date(date interface{}) *OptionStrikesRequest

Date sets the date parameter for the OptionStrikesRequest. This is used to make a historical request. This method is used to specify the date for which the options strikes data is requested.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix int, or any other type that the underlying dates package method can process.

Returns

  • *OptionStrikesRequest: This method returns a pointer to the OptionStrikesRequest instance it was called on. This allows for method chaining.

func (*OptionStrikesRequest) Expiration added in v1.1.0

func (o *OptionStrikesRequest) Expiration(expiration string) *OptionStrikesRequest

Expiration sets the expiration parameter for the OptionStrikesRequest. This method is used to specify the expiration date of the options for which strikes data is requested.

Parameters

  • expiration: A string representing the expiration date to be set.

Returns

  • *OptionStrikesRequest: This method returns a pointer to the OptionStrikesRequest instance it was called on. This allows for method chaining.

func (*OptionStrikesRequest) Get added in v1.1.0

Get sends the OptionStrikesRequest, unpacks the OptionStrikesResponse, and returns a slice of OptionStrikes. It returns an error if the request or unpacking fails.

Returns

  • []models.OptionStrikes: A slice of OptionStrikes containing the unpacked options strikes data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*OptionStrikesRequest) Packed added in v1.1.0

Packed sends the OptionStrikesRequest and returns the OptionStrikesResponse.

Returns

  • *models.OptionStrikesResponse: A pointer to the OptionStrikesResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*OptionStrikesRequest) Raw added in v1.1.0

func (osr *OptionStrikesRequest) Raw() (*resty.Response, error)

Raw executes the OptionStrikesRequest and returns the raw *resty.Response. This method returns the *resty.Response which can be used to directly access the raw JSON or *http.Response.

Returns

  • *resty.Response: The raw HTTP response from the executed OptionStrikesRequest.
  • error: An error object if the OptionStrikesRequest is nil or if an error occurs during the request execution.

func (*OptionStrikesRequest) UnderlyingSymbol added in v1.1.0

func (o *OptionStrikesRequest) UnderlyingSymbol(underlyingSymbol string) *OptionStrikesRequest

UnderlyingSymbol sets the underlying symbol parameter for the OptionStrikesRequest. This method is used to specify the symbol of the underlying asset for which options strikes data is requested.

Parameters

  • underlyingSymbol: A string representing the symbol to be set.

Returns

  • *OptionStrikesRequest: This method returns a pointer to the OptionStrikesRequest instance it was called on. This allows for method chaining.

type OptionsExpirationsRequest

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

OptionsExpirationsRequest represents a request for retrieving options expirations data from the /v1/options/expirations/ endpoint. It encapsulates parameters for the underlying symbol and strike price to be used in the request. This struct provides methods such as UnderlyingSymbol() and Strike() to set these parameters respectively.

Generated By

  • OptionsExpirations() *OptionsExpirationsRequest: OptionsExpirations creates a new *OptionsExpirationsRequest and returns a pointer to the request allowing for method chaining.

Setter Methods

  • Strike(float64) *OptionsExpirationsRequest: Sets the strike price parameter for the options expirations request.
  • UnderlyingSymbol(string) *OptionsExpirationsRequest: Sets the underlying symbol parameter for the options expirations request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() ([]time.Time, error): Sends the request, unpacks the response, and returns []time.Time allowing direct-access to the data.
  • Packed() (*OptionsExpirationsResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.

func OptionsExpirations

func OptionsExpirations() *OptionsExpirationsRequest

OptionsExpirations creates a new OptionsExpirationsRequest with the default client.

Returns

  • *OptionsExpirationsRequest: A pointer to the newly created OptionsExpirationsRequest with default parameters.

func (*OptionsExpirationsRequest) Date

func (oer *OptionsExpirationsRequest) Date(q interface{}) *OptionsExpirationsRequest

Date sets the date parameter for the OptionsExpirationsRequest. This method is used to specify the date for which the options expirations are requested. It modifies the dateParams field of the OptionsExpirationsRequest instance to store the date value.

Parameters

  • interface{}: An interface{} that represents the starting date. It can be a string, a time.Time object, a Unix timestamp or any other type that the underlying dates package can process.

Returns

  • *OptionsExpirationsRequest: This method returns a pointer to the OptionsExpirationsRequest instance it was called on. This allows for method chaining. If the receiver (*OptionsExpirationsRequest) is nil, it returns nil to prevent a panic.

func (*OptionsExpirationsRequest) Get

func (o *OptionsExpirationsRequest) Get() ([]time.Time, error)

Get sends the OptionsExpirationsRequest, unpacks the OptionsExpirationsResponse, and returns a slice of time.Time. It returns an error if the request or unpacking fails. This method uses the default client for the request.

Returns

  • []time.Time: A slice of time.Time containing the unpacked options expirations data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*OptionsExpirationsRequest) Packed

Packed sends the OptionsExpirationsRequest and returns the OptionsExpirationsResponse. This method uses the default client for the request.

Returns

  • *models.OptionsExpirationsResponse: A pointer to the OptionsExpirationsResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*OptionsExpirationsRequest) Raw

func (oer *OptionsExpirationsRequest) Raw() (*resty.Response, error)

Raw executes the OptionsExpirationsRequest and returns the raw *resty.Response. This method uses the default client for the request. The *resty.Response can be used to directly access the raw JSON or *http.Response.

Returns

  • *resty.Response: The raw HTTP response from the executed OptionsExpirationsRequest.
  • error: An error object if the OptionsExpirationsRequest is nil or if an error occurs during the request execution.

func (*OptionsExpirationsRequest) Strike

Strike sets the strike price parameter for the OptionsExpirationsRequest. This method is used to specify a particular strike price for filtering the options expirations.

Parameters

  • float64: A float64 representing the strike price to be set.

Returns

  • *OptionsExpirationsRequest: This method returns a pointer to the OptionsExpirationsRequest instance it was called on, allowing for method chaining.

func (*OptionsExpirationsRequest) UnderlyingSymbol

func (o *OptionsExpirationsRequest) UnderlyingSymbol(symbol string) *OptionsExpirationsRequest

UnderlyingSymbol sets the underlying symbol parameter for the OptionsExpirationsRequest. This method is used to specify the symbol of the underlying asset for which the options expirations are requested.

Parameters

  • string: A string representing the underlying symbol to be set.

Returns

  • *OptionsExpirationsRequest: This method returns a pointer to the OptionsExpirationsRequest instance it was called on, allowing for method chaining.

type StockCandlesRequest

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

StockCandlesRequest represents a request to the /v1/stocks/candles/ endpoint. It encapsulates parameters for resolution, symbol, date, and additional stock-specific parameters to be used in the request. This struct provides methods such as Resolution(), Symbol(), Date(), From(), To(), Countback(), AdjustSplits(), AdjustDividends(), Extended(), and Exchange() to set these parameters respectively.

Generated By

  • StockCandles() *StockCandlesRequest: StockCandles creates a new *StockCandlesRequest and returns a pointer to the request allowing for method chaining.

Setter Methods

  • Resolution(string) *StockCandlesRequest: Sets the resolution parameter for the request.
  • Symbol(string) *StockCandlesRequest: Sets the symbol parameter for the request.
  • Date(interface{}) *StockCandlesRequest: Sets the date parameter for the request.
  • From(interface{}) *StockCandlesRequest: Sets the 'from' date parameter for the request.
  • To(interface{}) *StockCandlesRequest: Sets the 'to' date parameter for the request.
  • Countback(int) *StockCandlesRequest: Sets the countback parameter for the request.
  • AdjustSplits(bool) *StockCandlesRequest: Sets the adjust splits parameter for the request.
  • AdjustDividends(bool) *StockCandlesRequest: Sets the adjust dividends parameter for the request.
  • Extended(bool) *StockCandlesRequest: Sets the extended hours data parameter for the request.
  • Exchange(string) *StockCandlesRequest: Sets the exchange parameter for the request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() ([]Candle, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed() (*StockCandlesResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
Example (Get)
scr, err := StockCandles().Resolution("4H").Symbol("AAPL").From("2023-01-01").To("2023-01-04").Get()
if err != nil {
	fmt.Print(err)
	return
}

for _, candle := range scr {
	fmt.Println(candle)
}
Output:

Candle{Time: 2023-01-03 09:30:00 -05:00, Open: 130.28, High: 130.9, Low: 124.19, Close: 124.6499, Volume: 64411753}
Candle{Time: 2023-01-03 13:30:00 -05:00, Open: 124.6699, High: 125.42, Low: 124.17, Close: 125.05, Volume: 30727802}
Candle{Time: 2023-01-04 09:30:00 -05:00, Open: 126.89, High: 128.6557, Low: 125.08, Close: 127.2601, Volume: 49976607}
Candle{Time: 2023-01-04 13:30:00 -05:00, Open: 127.265, High: 127.87, Low: 125.28, Close: 126.38, Volume: 28870878}
Example (Packed)
scr, err := StockCandles().Resolution("4H").Symbol("AAPL").From("2023-01-01").To("2023-01-04").Packed()
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println(scr)
Output:

StockCandlesResponse{Date: [1672756200 1672770600 1672842600 1672857000], Open: [130.28 124.6699 126.89 127.265], High: [130.9 125.42 128.6557 127.87], Low: [124.19 124.17 125.08 125.28], Close: [124.6499 125.05 127.2601 126.38], Volume: [64411753 30727802 49976607 28870878]}
Example (Raw)
scr, err := StockCandles().Resolution("4H").Symbol("AAPL").From("2023-01-01").To("2023-01-04").Raw()
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println(scr)
Output:

{"s":"ok","t":[1672756200,1672770600,1672842600,1672857000],"o":[130.28,124.6699,126.89,127.265],"h":[130.9,125.42,128.6557,127.87],"l":[124.19,124.17,125.08,125.28],"c":[124.6499,125.05,127.2601,126.38],"v":[64411753,30727802,49976607,28870878]}

func StockCandles

func StockCandles() *StockCandlesRequest

StockCandles initializes a new StockCandlesRequest with default parameters. This function prepares a request to fetch stock candle data. It sets up all necessary parameters and configurations to make the request ready to be sent.

Returns

  • *StockCandlesRequest: A pointer to the newly created StockCandlesRequest instance. This instance contains all the necessary parameters set to their default values and is ready to have additional parameters set or to be sent.

func (*StockCandlesRequest) AdjustDividends

func (scr *StockCandlesRequest) AdjustDividends(q bool) *StockCandlesRequest

AdjustDividends sets the adjust dividends parameter for the StockCandlesRequest. This method indicates whether the returned data should be adjusted for dividends.

Parameters

  • bool: Whether to adjust for dividends.

Returns

  • *StockCandlesRequest: This method returns a pointer to the *StockCandlesRequest instance it was called on. This allows for method chaining.

func (*StockCandlesRequest) AdjustSplits

func (scr *StockCandlesRequest) AdjustSplits(q bool) *StockCandlesRequest

AdjustSplits sets the adjust splits parameter for the StockCandlesRequest. This method indicates whether the returned data should be adjusted for stock splits.

Parameters

  • bool: Whether to adjust for splits.

Returns

  • *StockCandlesRequest: This method returns a pointer to the *StockCandlesRequest instance it was called on. This allows for method chaining.

func (*StockCandlesRequest) Countback

func (scr *StockCandlesRequest) Countback(q int) *StockCandlesRequest

Countback sets the countback parameter for the StockCandlesRequest. This method specifies the number of candles to return, counting backwards from the 'to' date.

Parameters

  • int: The number of candles to return.

Returns

  • *StockCandlesRequest: This method returns a pointer to the *StockCandlesRequest instance it was called on. This allows for method chaining.

func (*StockCandlesRequest) Date

func (scr *StockCandlesRequest) Date(q interface{}) *StockCandlesRequest

Date sets the date parameter for the StockCandlesRequest. This method is used to specify the date for which the stock candle data is requested.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix timestamp as an int, or any other type that the underlying dates package method can process.

Returns

  • *StockCandlesRequest: This method returns a pointer to the *StockCandlesRequest instance it was called on. This allows for method chaining.

func (*StockCandlesRequest) Exchange

Exchange sets the exchange parameter for the StockCandlesRequest. This method is used to specify the exchange from which the stock candle data is requested.

Parameters

  • string: The exchange to be set.

Returns

  • *StockCandlesRequest: This method returns a pointer to the *StockCandlesRequest instance it was called on. This allows for method chaining.

func (*StockCandlesRequest) Extended

func (scr *StockCandlesRequest) Extended(q bool) *StockCandlesRequest

Extended sets the extended hours data parameter for the StockCandlesRequest. This method indicates whether the returned data should include extended hours trading data.

Parameters

  • bool: Whether to include extended hours data.

Returns

  • *StockCandlesRequest: This method returns a pointer to the *StockCandlesRequest instance it was called on. This allows for method chaining.

func (*StockCandlesRequest) From

func (scr *StockCandlesRequest) From(q interface{}) *StockCandlesRequest

From sets the 'from' date parameter for the StockCandlesRequest. This method is used to specify the starting point of the date range for which the stock candle data is requested.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix timestamp as an int, or any other type that the underlying dates package method can process.

Returns

  • *StockCandlesRequest: This method returns a pointer to the *StockCandlesRequest instance it was called on. This allows for method chaining.

func (*StockCandlesRequest) Get

func (scr *StockCandlesRequest) Get() ([]models.Candle, error)

Get sends the StockCandlesRequest, unpacks the StockCandlesResponse, and returns a slice of StockCandle. It returns an error if the request or unpacking fails.

Returns

  • []Candle: A slice of []Candle containing the unpacked candle data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*StockCandlesRequest) Packed

Packed sends the StockCandlesRequest and returns the StockCandlesResponse. // # Returns

  • *StockCandlesResponse: A pointer to the StockCandlesResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*StockCandlesRequest) Raw

func (scr *StockCandlesRequest) Raw() (*resty.Response, error)

Raw executes the StockCandlesRequest and returns the raw *resty.Response. This method returns the raw JSON or *http.Response for further processing without accepting an alternative MarketDataClient.

Returns

  • *resty.Response: The raw HTTP response from the executed request.
  • error: An error object if the request fails due to execution errors.

func (*StockCandlesRequest) Resolution

func (cr *StockCandlesRequest) Resolution(q string) *StockCandlesRequest

Resolution sets the resolution parameter for the StockCandlesRequest. This method is used to specify the granularity of the candle data to be retrieved.

Parameters

  • string: A string representing the resolution to be set.

Returns

  • *StockCandlesRequest: This method returns a pointer to the *StockCandlesRequest instance it was called on. This allows for method chaining.

func (*StockCandlesRequest) Symbol

Symbol sets the symbol parameter for the StockCandlesRequest. This method is used to specify the stock symbol for which candle data is requested.

Parameters

  • string: A string representing the stock symbol to be set.

Returns

  • *StockCandlesRequest: This method returns a pointer to the *StockCandlesRequest instance it was called on. This allows for method chaining.

func (*StockCandlesRequest) To

func (scr *StockCandlesRequest) To(q interface{}) *StockCandlesRequest

To sets the 'to' date parameter for the StockCandlesRequest. This method is used to specify the ending point of the date range for which the stock candle data is requested.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix timestamp as an int, or any other type that the underlying dates package method can process.

Returns

  • *StockCandlesRequest: This method returns a pointer to the *StockCandlesRequest instance it was called on

type StockCandlesRequestV2

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

StockCandlesRequestV2 represents a request to the /v2/stocks/candles endpoint.

Example (Get)
scr2, err := StockCandlesV2().Resolution("D").Symbol("AAPL").DateKey("2023-01").Get()
if err != nil {
	fmt.Print(err)
	return
}

for _, candle := range scr2 {
	fmt.Println(candle)
}
Output:

Candle{Date: 2023-01-03, Open: 130.28, High: 130.9, Low: 124.17, Close: 125.07, Volume: 112117471, VWAP: 125.725, N: 1021065}
Candle{Date: 2023-01-04, Open: 126.89, High: 128.6557, Low: 125.08, Close: 126.36, Volume: 89100633, VWAP: 126.6464, N: 770042}
Candle{Date: 2023-01-05, Open: 127.13, High: 127.77, Low: 124.76, Close: 125.02, Volume: 80716808, VWAP: 126.0883, N: 665458}
Candle{Date: 2023-01-06, Open: 126.01, High: 130.29, Low: 124.89, Close: 129.62, Volume: 87754715, VWAP: 128.1982, N: 711520}
Candle{Date: 2023-01-09, Open: 130.465, High: 133.41, Low: 129.89, Close: 130.15, Volume: 70790813, VWAP: 131.6292, N: 645365}
Candle{Date: 2023-01-10, Open: 130.26, High: 131.2636, Low: 128.12, Close: 130.73, Volume: 63896155, VWAP: 129.822, N: 554940}
Candle{Date: 2023-01-11, Open: 131.25, High: 133.51, Low: 130.46, Close: 133.49, Volume: 69458949, VWAP: 132.3081, N: 561278}
Candle{Date: 2023-01-12, Open: 133.88, High: 134.26, Low: 131.44, Close: 133.41, Volume: 71379648, VWAP: 133.171, N: 635331}
Candle{Date: 2023-01-13, Open: 132.03, High: 134.92, Low: 131.66, Close: 134.76, Volume: 57809719, VWAP: 133.6773, N: 537385}
Candle{Date: 2023-01-17, Open: 134.83, High: 137.29, Low: 134.13, Close: 135.94, Volume: 63612627, VWAP: 135.7587, N: 595831}
Candle{Date: 2023-01-18, Open: 136.815, High: 138.61, Low: 135.03, Close: 135.21, Volume: 69672800, VWAP: 136.3316, N: 578304}
Candle{Date: 2023-01-19, Open: 134.08, High: 136.25, Low: 133.77, Close: 135.27, Volume: 58280413, VWAP: 134.9653, N: 491674}
Candle{Date: 2023-01-20, Open: 135.28, High: 138.02, Low: 134.22, Close: 137.87, Volume: 80200655, VWAP: 136.3762, N: 552230}
Candle{Date: 2023-01-23, Open: 138.12, High: 143.315, Low: 137.9, Close: 141.11, Volume: 81760313, VWAP: 141.2116, N: 719288}
Candle{Date: 2023-01-24, Open: 140.305, High: 143.16, Low: 140.3, Close: 142.53, Volume: 66435142, VWAP: 142.0507, N: 498679}
Candle{Date: 2023-01-25, Open: 140.89, High: 142.43, Low: 138.81, Close: 141.86, Volume: 65799349, VWAP: 140.7526, N: 536505}
Candle{Date: 2023-01-26, Open: 143.17, High: 144.25, Low: 141.9, Close: 143.96, Volume: 54105068, VWAP: 143.3429, N: 472135}
Candle{Date: 2023-01-27, Open: 143.155, High: 147.23, Low: 143.08, Close: 145.93, Volume: 70547743, VWAP: 145.8365, N: 560022}
Candle{Date: 2023-01-30, Open: 144.955, High: 145.55, Low: 142.85, Close: 143, Volume: 64015274, VWAP: 143.6524, N: 551111}
Candle{Date: 2023-01-31, Open: 142.7, High: 144.34, Low: 142.28, Close: 144.29, Volume: 65874459, VWAP: 143.6473, N: 468170}
Example (Packed)
scr2, err := StockCandlesV2().Resolution("D").Symbol("AAPL").DateKey("2023-01").Packed()
if err != nil {
	fmt.Print(err)
	return
}

fmt.Println(scr2)
Output:

StockCandlesResponse{Date: [1672722000 1672808400 1672894800 1672981200 1673240400 1673326800 1673413200 1673499600 1673586000 1673931600 1674018000 1674104400 1674190800 1674450000 1674536400 1674622800 1674709200 1674795600 1675054800 1675141200], Open: [130.28 126.89 127.13 126.01 130.465 130.26 131.25 133.88 132.03 134.83 136.815 134.08 135.28 138.12 140.305 140.89 143.17 143.155 144.955 142.7], High: [130.9 128.6557 127.77 130.29 133.41 131.2636 133.51 134.26 134.92 137.29 138.61 136.25 138.02 143.315 143.16 142.43 144.25 147.23 145.55 144.34], Low: [124.17 125.08 124.76 124.89 129.89 128.12 130.46 131.44 131.66 134.13 135.03 133.77 134.22 137.9 140.3 138.81 141.9 143.08 142.85 142.28], Close: [125.07 126.36 125.02 129.62 130.15 130.73 133.49 133.41 134.76 135.94 135.21 135.27 137.87 141.11 142.53 141.86 143.96 145.93 143 144.29], Volume: [112117471 89100633 80716808 87754715 70790813 63896155 69458949 71379648 57809719 63612627 69672800 58280413 80200655 81760313 66435142 65799349 54105068 70547743 64015274 65874459], VWAP: [125.725 126.6464 126.0883 128.1982 131.6292 129.822 132.3081 133.171 133.6773 135.7587 136.3316 134.9653 136.3762 141.2116 142.0507 140.7526 143.3429 145.8365 143.6524 143.6473], N: [1021065 770042 665458 711520 645365 554940 561278 635331 537385 595831 578304 491674 552230 719288 498679 536505 472135 560022 551111 468170]}

func StockCandlesV2

func StockCandlesV2() *StockCandlesRequestV2

StockCandles creates a new CandlesRequest and associates it with the provided client. If no client is provided, it uses the default client.

func (*StockCandlesRequestV2) DateKey

Date sets the date parameter for the CandlesRequest.

func (*StockCandlesRequestV2) Get

func (scrV2 *StockCandlesRequestV2) Get() ([]models.Candle, error)

Get sends the StockCandlesRequestV2, unpacks the StockCandlesResponse, and returns a slice of StockCandle. It returns an error if the request or unpacking fails.

Returns

  • []models.StockCandle: A slice of []Candle containing the unpacked candle data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*StockCandlesRequestV2) Packed

Packed sends the StockCandlesRequestV2 and returns the StockCandlesResponse.

Returns

  • *models.StockCandlesResponse: A pointer to the StockCandlesResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (StockCandlesRequestV2) Raw

func (request StockCandlesRequestV2) Raw() (*resty.Response, error)

Raw executes the request and returns the raw resty.Response.

Returns

  • *resty.Response: The raw response from the executed request.
  • error: An error object if the baseRequest is nil, or if an error occurs during the request execution.

func (*StockCandlesRequestV2) Resolution

Resolution sets the resolution parameter for the CandlesRequest.

func (*StockCandlesRequestV2) Symbol

Symbol sets the symbol parameter for the CandlesRequest.

type StockEarningsRequest

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

StockEarningsRequest represents a request to the /v1/stocks/earnings/ endpoint. It encapsulates parameters for symbol, report type, and date to be used in the request. This struct provides methods such as Report(), Symbol(), Date(), From(), To(), and Countback() to set these parameters respectively.

Generated By

  • StockEarnings() *StockEarningsRequest: StockEarnings creates a new *StockEarningsRequest and returns a pointer to the request allowing for method chaining.

Setter Methods

  • Report(q string) *StockEarningsRequest: Sets the report type parameter for the request.
  • Symbol(q string) *StockEarningsRequest: Sets the symbol parameter for the request.
  • Date(q interface{}) *StockEarningsRequest: Sets the date parameter for the request.
  • From(q interface{}) *StockEarningsRequest: Sets the 'from' date parameter for the request.
  • To(q interface{}) *StockEarningsRequest: Sets the 'to' date parameter for the request.
  • Countback(q int) *StockEarningsRequest: Sets the countback parameter for the request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() ([]StockEarningsReport, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed() (*StockEarningsResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
Example (Get)
ser, err := StockEarnings().Symbol("AAPL").From("2022-01-01").To("2022-01-31").Get()
if err != nil {
	fmt.Print(err)
	return
}

for _, report := range ser {
	report.Updated = time.Time{}
	fmt.Println(report)
}
Output:

StockEarningsReport{Symbol: "AAPL", FiscalYear: 2022, FiscalQuarter: 1, Date: "2021-12-31", ReportDate: "2022-01-27", ReportTime: "after close", Currency: "USD", ReportedEPS: 2.100000, EstimatedEPS: 1.890000, SurpriseEPS: 0.210000, SurpriseEPSPct: 0.111100, Updated: "nil"}
Example (Packed)
ser, err := StockEarnings().Symbol("AAPL").From("2022-01-01").To("2022-01-31").Packed()
if err != nil {
	fmt.Print(err)
	return
}

ser.Updated = []int64{} // Delete the updated field so the string output does not change between runs.

fmt.Println(ser)
Output:

StockEarningsResponse{Symbol: [AAPL], FiscalYear: 2022, FiscalQuarter: 1, Date: [1640926800], ReportDate: [1643259600], ReportTime: [after close], Currency: [USD], ReportedEPS: [2.100000 ], EstimatedEPS: [1.890000 ], SurpriseEPS: [0.210000 ], SurpriseEPSpct: [0.111100 ], Updated: []}
Example (Raw)
ser, err := StockEarnings().Symbol("AAPL").From("2022-01-01").To("2022-01-31").Raw()
if err != nil {
	fmt.Print(err)
	return
}

// Convert the response to a string if it's not already
serString := ser.String()

// Use regex to remove the "updated" key and its value so that the output is consistent between runs.
re := regexp.MustCompile(`,"updated":\[\d+\]`)
cleanedSerString := re.ReplaceAllString(serString, "")

fmt.Println(cleanedSerString)
Output:

{"s":"ok","symbol":["AAPL"],"fiscalYear":[2022],"fiscalQuarter":[1],"date":[1640926800],"reportDate":[1643259600],"reportTime":["after close"],"currency":["USD"],"reportedEPS":[2.1],"estimatedEPS":[1.89],"surpriseEPS":[0.21],"surpriseEPSpct":[0.1111]}

func StockEarnings

func StockEarnings() *StockEarningsRequest

StockEarnings creates a new StockEarningsRequest with default parameters and associates it with the default client. This function initializes the request with default parameters for symbol, report type, and date, and sets the request path based on the predefined endpoints for stock earnings.

Returns

  • *StockEarningsRequest: A pointer to the newly created StockEarningsRequest with default parameters and associated client.

func (*StockEarningsRequest) Countback

func (ser *StockEarningsRequest) Countback(q int) *StockEarningsRequest

Countback sets the countback parameter for the StockEarningsRequest. This method specifies the number of periods to return, counting backwards from the 'to' date.

Parameters

  • int: The number of periods to return.

Returns

  • *StockEarningsRequest: This method returns a pointer to the *StockEarningsRequest instance it was called on. This allows for method chaining.

func (*StockEarningsRequest) Date

func (ser *StockEarningsRequest) Date(q interface{}) *StockEarningsRequest

Date sets the date parameter for the StockEarningsRequest. This method is used to specify the date for which the stock earnings data is requested.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix int, or any other type that the underlying dates package method can process.

Returns

  • *StockEarningsRequest: This method returns a pointer to the *StockEarningsRequest instance it was called on. This allows for method chaining.

func (*StockEarningsRequest) From

func (ser *StockEarningsRequest) From(q interface{}) *StockEarningsRequest

From sets the 'from' date parameter for the StockEarningsRequest. This method is used to specify the starting point of the date range for which the stock earnings data is requested.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix int, or any other type that the underlying dates package method can process.

Returns

  • *StockEarningsRequest: This method returns a pointer to the *StockEarningsRequest instance it was called on. This allows for method chaining.

func (*StockEarningsRequest) Get

Get sends the StockEarningsRequest, unpacks the StockEarningsResponse, and returns a slice of StockEarningsReport. It returns an error if the request or unpacking fails.

Returns

  • []models.StockEarningsReport: A slice of StockEarningsReport containing the unpacked earnings data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*StockEarningsRequest) Packed

Packed sends the StockEarningsRequest and returns the StockEarningsResponse.

Returns

  • *models.StockEarningsResponse: A pointer to the StockEarningsResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*StockEarningsRequest) Raw

func (ser *StockEarningsRequest) Raw() (*resty.Response, error)

Raw executes the StockEarningsRequest and returns the raw *resty.Response. The *resty.Response can be used to access the raw JSON or *http.Response directly.

Returns

  • *resty.Response: The raw response from the executed StockEarningsRequest.
  • error: An error object if the StockEarningsRequest is nil, the MarketDataClient is nil, or if an error occurs during the request execution.

func (*StockEarningsRequest) Report

Report sets the report type parameter for the StockEarningsRequest. This method is used to specify which earnings report to be retrieved.

Parameters

  • string: A string representing which report to be returned.

Returns

  • *StockEarningsRequest: This method returns a pointer to the *StockEarningsRequest instance it was called on. This allows for method chaining.

func (*StockEarningsRequest) Symbol

Symbol sets the symbol parameter for the StockEarningsRequest. This method is used to specify the stock symbol for which earnings data is requested.

Parameters

  • string: A string representing the stock symbol to be set.

Returns

  • *StockEarningsRequest: This method returns a pointer to the *StockEarningsRequest instance it was called on. This allows for method chaining.

func (*StockEarningsRequest) To

func (ser *StockEarningsRequest) To(q interface{}) *StockEarningsRequest

To sets the 'to' date parameter for the StockEarningsRequest. This method is used to specify the ending point of the date range for which the stock earnings data is requested.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix int, or any other type that the underlying dates package method can process.

Returns

  • *StockEarningsRequest: This method returns a pointer to the *StockEarningsRequest instance it was called on. This allows for method chaining.

type StockNewsRequest

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

StockNewsRequest represents a request to the /v1/stocks/news/ endpoint. It encapsulates parameters for symbol, date, and additional news-specific parameters to be used in the request. This struct provides methods such as Symbol(), Date(), From(), To(), and Countback() to set these parameters respectively.

Setter Methods

  • Symbol(string) *StockNewsRequest: Sets the symbol parameter for the request.
  • Date(interface{}) *StockNewsRequest: Sets the date parameter for the request.
  • From(interface{}) *StockNewsRequest: Sets the 'from' date parameter for the request.
  • To(interface{}) *StockNewsRequest: Sets the 'to' date parameter for the request.
  • Countback(int) *StockNewsRequest: Sets the countback parameter for the request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() ([]StockNews, error): Initiates the request, processes the response, and provides an slice of `StockNews` objects for straightforward access to news articles.
  • Packed() (*StockNewsResponse, error): Delivers a packed `StockNewsResponse` object containing slices of data that directly correspond to the JSON structure returned by the Market Data API.
  • Raw() (*resty.Response, error): Executes the request in its raw form and retrieves the raw HTTP response for maximum flexibility.
Example (Get)
resp, err := StockNews().Symbol("AAPL").Date("2023-01-01").Get()
if err != nil {
	fmt.Print(err)
	return
}

for _, news := range resp {
	fmt.Println(news)
}
Output:

StockNews{Symbol: "AAPL", Headline: "Lessons Learned From Visa and Mastercard in a Year of Crypto News", Content: "How Visa and Mastercard fared in a year dominated by crypto news. Why fortress-like balance sheets will be an even bigger asset in the new year. To catch full episodes of all The Motley Fool's free podcasts, check out our podcast center.<br /><br />Continue reading", Source: "https://finance.yahoo.com/m/4b9f894a-9854-3caf-8775-c7e9f9d4ce90/lessons-learned-from-visa-and.html", PublicationDate: "2023-01-01"}
StockNews{Symbol: "AAPL", Headline: "Down 28% in 2022, Is Apple Stock a Buy for 2023?", Content: "Apple (NASDAQ: AAPL) has benefited from robust consumer demand and hopes that easing supply chain constraints will boost the tech giant's prospects. *Stock prices used were the afternoon prices of Dec.<br /><br />Continue reading", Source: "https://finance.yahoo.com/m/457b8480-3b01-3a94-9273-54aaf80906a8/down-28%25-in-2022%2C-is-apple.html", PublicationDate: "2023-01-01"}
StockNews{Symbol: "AAPL", Headline: "80% of Warren Buffett's Portfolio Is Invested in These 7 Stocks as 2023 Begins", Content: "Two of these stocks were especially big winners for Buffett in 2022.", Source: "https://www.fool.com/investing/2023/01/01/80-of-warren-buffetts-portfolio-is-invested-in-the/", PublicationDate: "2023-01-01"}
StockNews{Symbol: "AAPL", Headline: "2 Beaten-Down Warren Buffett Stocks to Buy in 2023", Content: "These are high-conviction stocks for the Oracle of Omaha but they're trading at knocked-down prices.<br /><br />Continue reading", Source: "https://finance.yahoo.com/m/cc37d40a-9068-3de1-9dd3-a6a71da3aa75/2-beaten-down-warren-buffett.html", PublicationDate: "2023-01-01"}
StockNews{Symbol: "AAPL", Headline: "2023 Dividend Growth Portfolio Review And Look Ahead", Content: "I review my current holdings and sectors in the portfolio and how it has changed over the years. See my income projections for 2023 and potential pitfalls.", Source: "https://seekingalpha.com/article/4567219-2023-dividend-growth-portfolio-review-and-look-ahead", PublicationDate: "2023-01-01"}
StockNews{Symbol: "AAPL", Headline: "The Fall Of Tesla And The Rise of Exxon Amid The Energy Crisis", Content: "Growth stocks have been thoroughly hammered this year, with high inflation and rising interest rates pinching growth equities of all stripes. But few stocks exemplify the dramatic shake-up at the top, like leading EV maker Tesla Inc. (NASDAQ: TSLA). TSLA stock has tanked 69.5% in the year-to-date, wiping off a staggering $877 billion from its market cap. In comparison, the S&P 500 has declined a more modest 19.7% over the timeframe. Tesla has gone from being the fifth most valuable public company and now ranks just thirteenth with a market cap of $385 billion.<br /><br />Tesla’s woes are well documented, including Musk's Twitter takeover and related distractions; worries that high inflation and rising interest rates will dampen consumers' enthusiasm for EVs, as well as investor jitters about growth assets. TSLA shareholders are furious at CEO Elon Musk, The Wall Street Journal reports, for his Twitter antics and tomfoolery, which has led to several downgrades for the stock. Meanwhile, hordes of customers are canceling their Tesla orders, \"His personality is absolutely tanking the Tesla brand. I'm looking forward to having an Elon-free existence,’’ a biotech exec with a Model S lease has told CNET. \"There is no Tesla CEO today,\" tweeted Gary Black, a hedge fund manager with ~$50 million worth of TSLA stock told Futurism.<br /><br />Related: U.S. Oil, Gas Rigs Up 193 This Year<br /><br />But Tesla is hardly alone here: most EV stocks have had a year to forget with rising costs, supply chain issues, increasing competition, and the threat of a potential recession causing many to sell off heavily.<br /><br />Surprisingly, some Wall Street pundits have not given up on TSLA stock and are urging investors to use the selloff as a buying opportunity. To wit, Citi has tapped TSLA as a bullish contrarian stock for 2023, while Baird analyst Ben Kallo still sees Tesla as a “Best Idea” stock in 2023. Meanwhile, Morgan Stanley says Tesla could extend its lead over its EV rivals in the coming year, and has cited “valuation, cash flow, innovation and cost leadership” as key reasons to maintain a Buy-equivalent rating. Meanwhile, famed contrarian investor Cathie Wood, known for betting big on former growth stocks as they fall, recently loaded up on more than 25K shares of the EV giant.<br /><br />Story continues<br /><br />In sharp contrast, things could not have gone differently for Tesla’s biggest fossil fuel rival, Exxon Mobil Corp. (NYSE: XOM). Exxon Mobil has enjoyed the biggest rise in the S&P 500 this year, with the energy giant jumping almost like technology stocks did in the tech boom thanks to high oil and gas prices triggered by the energy crisis. XOM shares have soared 72% this year, adding $190 billion to the company’s market value. Exxon’s increase in market value surpasses any company in the S&P 500, making Exxon Mobil the eighth most valuable stock in the S&P 500. That’s a remarkable jump considering that it only ranked 27th most valuable in the S&P 500 a year ago. Exxon was the most valuable S&P 500 company in 2011 until Apple Inc. (NASDAQ: AAPL) surpassed it in 2012.<br /><br />Whereas Citi has picked XOM as one of its bearish contrarian stocks for 2023, the stock is viewed favorably by most Wall Street analysts, as evidenced by its $118.89 average price target, good for a 10% upside. The energy sector in general is expected to outperform the market again in 2023, and XOM should be just fine, considering it’s still cheap with a PE (Fwd) of 7.9. Back in October, Exxon raised its quarterly dividend by $0.03 per share to $0.91 per share marking the company's 40th straight year of increasing its dividend, keeping it in the elite group of Dividend Aristocrats. XOM shares now yield 3.3%.<br /><br />The outlook for the energy sector remains bright. According to a recent Moody's research report, industry earnings will stabilize overall in 2023, though they will come in slightly below levels reached by recent peaks.<br /><br />The analysts note that commodity prices have declined from very high levels earlier in 2022, but have predicted that prices are likely to remain cyclically strong through 2023. This, combined with modest growth in volumes, will support strong cash flow generation for oil and gas producers. Moody’s estimates that the U.S. energy sector’s EBITDA for 2022 will clock in at $623B but fall slightly to $585B in 2023.<br /><br />The analysts say that low capex, rising uncertainty about the expansion of future supplies, and high geopolitical risk premium will, however, continue to support cyclically high oil prices. Meanwhile, strong export demand for U.S. LNG will continue supporting high natural gas prices.<br /><br />The combined dividend and buyback yield for the energy sector is now approaching 8%, which is high by historical standards. Similarly elevated levels occurred in 2020 and 2009, which preceded periods of strength. In comparison, the combined dividend and buyback yield for the S&P 500 is closer to five percent, which makes for one of the largest gaps in favor of the energy sector on record.<br /><br />In other words, there simply aren’t better places for people investing in the U.S. stock market to park their money if they are looking for serious earnings growth.<br /><br />By Alex Kimani for Oilprice.com<br /><br />More Top Reads from Oilprice.com:<br /><br />A New Type Of Oil And Gas Funding Is Booming What is Crude Oil? A Detailed Explanation on this Essential Fossil Fuel Chevron Sending Tanker To Venezuela To Load Oil<br /><br />Read this article on OilPrice.com", Source: "https://finance.yahoo.com/news/fall-tesla-rise-exxon-amid-000000565.html", PublicationDate: "2023-01-01"}
Example (Packed)
resp, err := StockNews().Symbol("AAPL").Date("2023-01-01").Packed()
if err != nil {
	fmt.Print(err)
	return
}

fmt.Println(resp)
Output:

StockNewsResponse{Symbol: "AAPL", Headline: "Lessons Learned From Visa and Mastercard in a Year of Crypto News", Content: "How Visa and Mastercard fared in a year dominated by crypto news. Why fortress-like balance sheets will be an even bigger asset in the new year. To catch full episodes of all The Motley Fool's free podcasts, check out our podcast center.<br /><br />Continue reading", Source: "https://finance.yahoo.com/m/4b9f894a-9854-3caf-8775-c7e9f9d4ce90/lessons-learned-from-visa-and.html", PublicationDate: 1672549200; Symbol: "AAPL", Headline: "Down 28% in 2022, Is Apple Stock a Buy for 2023?", Content: "Apple (NASDAQ: AAPL) has benefited from robust consumer demand and hopes that easing supply chain constraints will boost the tech giant's prospects. *Stock prices used were the afternoon prices of Dec.<br /><br />Continue reading", Source: "https://finance.yahoo.com/m/457b8480-3b01-3a94-9273-54aaf80906a8/down-28%25-in-2022%2C-is-apple.html", PublicationDate: 1672549200; Symbol: "AAPL", Headline: "80% of Warren Buffett's Portfolio Is Invested in These 7 Stocks as 2023 Begins", Content: "Two of these stocks were especially big winners for Buffett in 2022.", Source: "https://www.fool.com/investing/2023/01/01/80-of-warren-buffetts-portfolio-is-invested-in-the/", PublicationDate: 1672549200; Symbol: "AAPL", Headline: "2 Beaten-Down Warren Buffett Stocks to Buy in 2023", Content: "These are high-conviction stocks for the Oracle of Omaha but they're trading at knocked-down prices.<br /><br />Continue reading", Source: "https://finance.yahoo.com/m/cc37d40a-9068-3de1-9dd3-a6a71da3aa75/2-beaten-down-warren-buffett.html", PublicationDate: 1672549200; Symbol: "AAPL", Headline: "2023 Dividend Growth Portfolio Review And Look Ahead", Content: "I review my current holdings and sectors in the portfolio and how it has changed over the years. See my income projections for 2023 and potential pitfalls.", Source: "https://seekingalpha.com/article/4567219-2023-dividend-growth-portfolio-review-and-look-ahead", PublicationDate: 1672549200; Symbol: "AAPL", Headline: "The Fall Of Tesla And The Rise of Exxon Amid The Energy Crisis", Content: "Growth stocks have been thoroughly hammered this year, with high inflation and rising interest rates pinching growth equities of all stripes. But few stocks exemplify the dramatic shake-up at the top, like leading EV maker Tesla Inc. (NASDAQ: TSLA). TSLA stock has tanked 69.5% in the year-to-date, wiping off a staggering $877 billion from its market cap. In comparison, the S&P 500 has declined a more modest 19.7% over the timeframe. Tesla has gone from being the fifth most valuable public company and now ranks just thirteenth with a market cap of $385 billion.<br /><br />Tesla’s woes are well documented, including Musk's Twitter takeover and related distractions; worries that high inflation and rising interest rates will dampen consumers' enthusiasm for EVs, as well as investor jitters about growth assets. TSLA shareholders are furious at CEO Elon Musk, The Wall Street Journal reports, for his Twitter antics and tomfoolery, which has led to several downgrades for the stock. Meanwhile, hordes of customers are canceling their Tesla orders, \"His personality is absolutely tanking the Tesla brand. I'm looking forward to having an Elon-free existence,’’ a biotech exec with a Model S lease has told CNET. \"There is no Tesla CEO today,\" tweeted Gary Black, a hedge fund manager with ~$50 million worth of TSLA stock told Futurism.<br /><br />Related: U.S. Oil, Gas Rigs Up 193 This Year<br /><br />But Tesla is hardly alone here: most EV stocks have had a year to forget with rising costs, supply chain issues, increasing competition, and the threat of a potential recession causing many to sell off heavily.<br /><br />Surprisingly, some Wall Street pundits have not given up on TSLA stock and are urging investors to use the selloff as a buying opportunity. To wit, Citi has tapped TSLA as a bullish contrarian stock for 2023, while Baird analyst Ben Kallo still sees Tesla as a “Best Idea” stock in 2023. Meanwhile, Morgan Stanley says Tesla could extend its lead over its EV rivals in the coming year, and has cited “valuation, cash flow, innovation and cost leadership” as key reasons to maintain a Buy-equivalent rating. Meanwhile, famed contrarian investor Cathie Wood, known for betting big on former growth stocks as they fall, recently loaded up on more than 25K shares of the EV giant.<br /><br />Story continues<br /><br />In sharp contrast, things could not have gone differently for Tesla’s biggest fossil fuel rival, Exxon Mobil Corp. (NYSE: XOM). Exxon Mobil has enjoyed the biggest rise in the S&P 500 this year, with the energy giant jumping almost like technology stocks did in the tech boom thanks to high oil and gas prices triggered by the energy crisis. XOM shares have soared 72% this year, adding $190 billion to the company’s market value. Exxon’s increase in market value surpasses any company in the S&P 500, making Exxon Mobil the eighth most valuable stock in the S&P 500. That’s a remarkable jump considering that it only ranked 27th most valuable in the S&P 500 a year ago. Exxon was the most valuable S&P 500 company in 2011 until Apple Inc. (NASDAQ: AAPL) surpassed it in 2012.<br /><br />Whereas Citi has picked XOM as one of its bearish contrarian stocks for 2023, the stock is viewed favorably by most Wall Street analysts, as evidenced by its $118.89 average price target, good for a 10% upside. The energy sector in general is expected to outperform the market again in 2023, and XOM should be just fine, considering it’s still cheap with a PE (Fwd) of 7.9. Back in October, Exxon raised its quarterly dividend by $0.03 per share to $0.91 per share marking the company's 40th straight year of increasing its dividend, keeping it in the elite group of Dividend Aristocrats. XOM shares now yield 3.3%.<br /><br />The outlook for the energy sector remains bright. According to a recent Moody's research report, industry earnings will stabilize overall in 2023, though they will come in slightly below levels reached by recent peaks.<br /><br />The analysts note that commodity prices have declined from very high levels earlier in 2022, but have predicted that prices are likely to remain cyclically strong through 2023. This, combined with modest growth in volumes, will support strong cash flow generation for oil and gas producers. Moody’s estimates that the U.S. energy sector’s EBITDA for 2022 will clock in at $623B but fall slightly to $585B in 2023.<br /><br />The analysts say that low capex, rising uncertainty about the expansion of future supplies, and high geopolitical risk premium will, however, continue to support cyclically high oil prices. Meanwhile, strong export demand for U.S. LNG will continue supporting high natural gas prices.<br /><br />The combined dividend and buyback yield for the energy sector is now approaching 8%, which is high by historical standards. Similarly elevated levels occurred in 2020 and 2009, which preceded periods of strength. In comparison, the combined dividend and buyback yield for the S&P 500 is closer to five percent, which makes for one of the largest gaps in favor of the energy sector on record.<br /><br />In other words, there simply aren’t better places for people investing in the U.S. stock market to park their money if they are looking for serious earnings growth.<br /><br />By Alex Kimani for Oilprice.com<br /><br />More Top Reads from Oilprice.com:<br /><br />A New Type Of Oil And Gas Funding Is Booming What is Crude Oil? A Detailed Explanation on this Essential Fossil Fuel Chevron Sending Tanker To Venezuela To Load Oil<br /><br />Read this article on OilPrice.com", Source: "https://finance.yahoo.com/news/fall-tesla-rise-exxon-amid-000000565.html", PublicationDate: 1672549200}
Example (Raw)
resp, err := StockNews().Symbol("AAPL").Date("2023-01-01").Raw()
if err != nil {
	fmt.Print(err)
	return
}

fmt.Println(resp)
Output:

{"s":"ok","symbol":["AAPL","AAPL","AAPL","AAPL","AAPL","AAPL"],"headline":["Lessons Learned From Visa and Mastercard in a Year of Crypto News","Down 28% in 2022, Is Apple Stock a Buy for 2023?","80% of Warren Buffett's Portfolio Is Invested in These 7 Stocks as 2023 Begins","2 Beaten-Down Warren Buffett Stocks to Buy in 2023","2023 Dividend Growth Portfolio Review And Look Ahead","The Fall Of Tesla And The Rise of Exxon Amid The Energy Crisis"],"content":["How Visa and Mastercard fared in a year dominated by crypto news. Why fortress-like balance sheets will be an even bigger asset in the new year. To catch full episodes of all The Motley Fool's free podcasts, check out our podcast center.<br /><br />Continue reading","Apple (NASDAQ: AAPL) has benefited from robust consumer demand and hopes that easing supply chain constraints will boost the tech giant's prospects. *Stock prices used were the afternoon prices of Dec.<br /><br />Continue reading","Two of these stocks were especially big winners for Buffett in 2022.","These are high-conviction stocks for the Oracle of Omaha but they're trading at knocked-down prices.<br /><br />Continue reading","I review my current holdings and sectors in the portfolio and how it has changed over the years. See my income projections for 2023 and potential pitfalls.","Growth stocks have been thoroughly hammered this year, with high inflation and rising interest rates pinching growth equities of all stripes. But few stocks exemplify the dramatic shake-up at the top, like leading EV maker Tesla Inc. (NASDAQ: TSLA). TSLA stock has tanked 69.5% in the year-to-date, wiping off a staggering $877 billion from its market cap. In comparison, the S&P 500 has declined a more modest 19.7% over the timeframe. Tesla has gone from being the fifth most valuable public company and now ranks just thirteenth with a market cap of $385 billion.<br /><br />Tesla’s woes are well documented, including Musk's Twitter takeover and related distractions; worries that high inflation and rising interest rates will dampen consumers' enthusiasm for EVs, as well as investor jitters about growth assets. TSLA shareholders are furious at CEO Elon Musk, The Wall Street Journal reports, for his Twitter antics and tomfoolery, which has led to several downgrades for the stock. Meanwhile, hordes of customers are canceling their Tesla orders, \"His personality is absolutely tanking the Tesla brand. I'm looking forward to having an Elon-free existence,’’ a biotech exec with a Model S lease has told CNET. \"There is no Tesla CEO today,\" tweeted Gary Black, a hedge fund manager with ~$50 million worth of TSLA stock told Futurism.<br /><br />Related: U.S. Oil, Gas Rigs Up 193 This Year<br /><br />But Tesla is hardly alone here: most EV stocks have had a year to forget with rising costs, supply chain issues, increasing competition, and the threat of a potential recession causing many to sell off heavily.<br /><br />Surprisingly, some Wall Street pundits have not given up on TSLA stock and are urging investors to use the selloff as a buying opportunity. To wit, Citi has tapped TSLA as a bullish contrarian stock for 2023, while Baird analyst Ben Kallo still sees Tesla as a “Best Idea” stock in 2023. Meanwhile, Morgan Stanley says Tesla could extend its lead over its EV rivals in the coming year, and has cited “valuation, cash flow, innovation and cost leadership” as key reasons to maintain a Buy-equivalent rating. Meanwhile, famed contrarian investor Cathie Wood, known for betting big on former growth stocks as they fall, recently loaded up on more than 25K shares of the EV giant.<br /><br />Story continues<br /><br />In sharp contrast, things could not have gone differently for Tesla’s biggest fossil fuel rival, Exxon Mobil Corp. (NYSE: XOM). Exxon Mobil has enjoyed the biggest rise in the S&P 500 this year, with the energy giant jumping almost like technology stocks did in the tech boom thanks to high oil and gas prices triggered by the energy crisis. XOM shares have soared 72% this year, adding $190 billion to the company’s market value. Exxon’s increase in market value surpasses any company in the S&P 500, making Exxon Mobil the eighth most valuable stock in the S&P 500. That’s a remarkable jump considering that it only ranked 27th most valuable in the S&P 500 a year ago. Exxon was the most valuable S&P 500 company in 2011 until Apple Inc. (NASDAQ: AAPL) surpassed it in 2012.<br /><br />Whereas Citi has picked XOM as one of its bearish contrarian stocks for 2023, the stock is viewed favorably by most Wall Street analysts, as evidenced by its $118.89 average price target, good for a 10% upside. The energy sector in general is expected to outperform the market again in 2023, and XOM should be just fine, considering it’s still cheap with a PE (Fwd) of 7.9. Back in October, Exxon raised its quarterly dividend by $0.03 per share to $0.91 per share marking the company's 40th straight year of increasing its dividend, keeping it in the elite group of Dividend Aristocrats. XOM shares now yield 3.3%.<br /><br />The outlook for the energy sector remains bright. According to a recent Moody's research report, industry earnings will stabilize overall in 2023, though they will come in slightly below levels reached by recent peaks.<br /><br />The analysts note that commodity prices have declined from very high levels earlier in 2022, but have predicted that prices are likely to remain cyclically strong through 2023. This, combined with modest growth in volumes, will support strong cash flow generation for oil and gas producers. Moody’s estimates that the U.S. energy sector’s EBITDA for 2022 will clock in at $623B but fall slightly to $585B in 2023.<br /><br />The analysts say that low capex, rising uncertainty about the expansion of future supplies, and high geopolitical risk premium will, however, continue to support cyclically high oil prices. Meanwhile, strong export demand for U.S. LNG will continue supporting high natural gas prices.<br /><br />The combined dividend and buyback yield for the energy sector is now approaching 8%, which is high by historical standards. Similarly elevated levels occurred in 2020 and 2009, which preceded periods of strength. In comparison, the combined dividend and buyback yield for the S&P 500 is closer to five percent, which makes for one of the largest gaps in favor of the energy sector on record.<br /><br />In other words, there simply aren’t better places for people investing in the U.S. stock market to park their money if they are looking for serious earnings growth.<br /><br />By Alex Kimani for Oilprice.com<br /><br />More Top Reads from Oilprice.com:<br /><br />A New Type Of Oil And Gas Funding Is Booming What is Crude Oil? A Detailed Explanation on this Essential Fossil Fuel Chevron Sending Tanker To Venezuela To Load Oil<br /><br />Read this article on OilPrice.com"],"source":["https://finance.yahoo.com/m/4b9f894a-9854-3caf-8775-c7e9f9d4ce90/lessons-learned-from-visa-and.html","https://finance.yahoo.com/m/457b8480-3b01-3a94-9273-54aaf80906a8/down-28%25-in-2022%2C-is-apple.html","https://www.fool.com/investing/2023/01/01/80-of-warren-buffetts-portfolio-is-invested-in-the/","https://finance.yahoo.com/m/cc37d40a-9068-3de1-9dd3-a6a71da3aa75/2-beaten-down-warren-buffett.html","https://seekingalpha.com/article/4567219-2023-dividend-growth-portfolio-review-and-look-ahead","https://finance.yahoo.com/news/fall-tesla-rise-exxon-amid-000000565.html"],"publicationDate":[1672549200,1672549200,1672549200,1672549200,1672549200,1672549200]}

func StockNews

func StockNews() *StockNewsRequest

StockNews creates a new StockNewsRequest and associates it with the default client. This function initializes the request with default parameters for symbol, date, and additional news-specific parameters, and sets the request path based on the predefined endpoints for stock news.

Returns

  • *StockNewsRequest: A pointer to the newly created *StockNewsRequest with default parameters and associated client.

func (*StockNewsRequest) Countback

func (snr *StockNewsRequest) Countback(q int) *StockNewsRequest

Countback sets the countback parameter for the StockNewsRequest. This method specifies the number of news items to return, counting backwards from the 'to' date.

Parameters

  • int: The number of news items to return.

Returns

  • *StockNewsRequest: This method returns a pointer to the *StockNewsRequest instance it was called on. This allows for method chaining.

func (*StockNewsRequest) Date

func (snr *StockNewsRequest) Date(q interface{}) *StockNewsRequest

Date sets the date parameter for the StockNewsRequest. This method is used to specify the date for which the stock news data is requested.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix int, or any other type that the underlying dates package method can process.

Returns

  • *StockNewsRequest: This method returns a pointer to the StockNewsRequest instance it was called on. This allows for method chaining.

func (*StockNewsRequest) From

func (snr *StockNewsRequest) From(q interface{}) *StockNewsRequest

From sets the 'from' date parameter for the StockNewsRequest. This method is used to specify the starting point of the date range for which the stock news data is requested.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix int, or any other type that the underlying dates package method can process.

Returns

  • *StockNewsRequest: This method returns a pointer to the StockNewsRequest instance it was called on. This allows for method chaining.

func (*StockNewsRequest) Get

func (snr *StockNewsRequest) Get() ([]models.StockNews, error)

Get sends the StockNewsRequest, unpacks the StockNewsResponse, and returns a slice of StockNews. It returns an error if the request or unpacking fails.

Returns

  • []models.StockNews: A slice of StockNews containing the unpacked news data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*StockNewsRequest) Packed

func (snr *StockNewsRequest) Packed() (*models.StockNewsResponse, error)

Packed sends the StockNewsRequest and returns the StockNewsResponse.

Returns

  • *models.StockNewsResponse: A pointer to the StockNewsResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*StockNewsRequest) Raw

func (snr *StockNewsRequest) Raw() (*resty.Response, error)

Raw executes the StockNewsRequest and returns the raw *resty.Response. This method retrieves the raw HTTP response for further processing.

Returns

  • *resty.Response: The raw HTTP response from the executed request.
  • error: An error object if the request fails due to being nil or other execution errors.

func (*StockNewsRequest) Symbol

func (snr *StockNewsRequest) Symbol(q string) *StockNewsRequest

Symbol sets the symbol parameter for the StockNewsRequest. This method is used to specify the stock symbol for which news data is requested.

Parameters

  • string: A string representing the stock symbol to be set.

Returns

  • *StockNewsRequest: This method returns a pointer to the StockNewsRequest instance it was called on. This allows for method chaining.

func (*StockNewsRequest) To

func (snr *StockNewsRequest) To(q interface{}) *StockNewsRequest

To sets the 'to' date parameter for the StockNewsRequest. This method is used to specify the ending point of the date range for which the stock news data is requested.

Parameters

  • interface{}: An interface{} representing the date to be set. It can be a string, a time.Time object, a Unix int, or any other type that the underlying dates package method can process.

Returns

  • *StockNewsRequest: This method returns a pointer to the StockNewsRequest instance it was called on. This allows for method chaining.

type StockQuoteRequest

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

StockQuoteRequest represents a request to the /v1/stocks/quotes/ endpoint. It encapsulates parameters for symbol and fifty-two-week data to be used in the request. This struct provides methods such as Symbol() and FiftyTwoWeek() to set these parameters respectively.

Setter Methods

  • Symbol(string) *StockQuoteRequest: Sets the symbol parameter for the request.
  • FiftyTwoWeek(bool) *StockQuoteRequest: Sets the fifty-two-week data parameter for the request.

Execution Methods

These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint.

  • Get() ([]Candle, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
  • Packed() (*IndicesCandlesResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response.
  • Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
Example (Get)
// This example demonstrates how to create a StockQuoteRequest, set its parameters,
// and perform an actual request to fetch stock quotes for the "AAPL" symbol.

// Initialize a new StockQuoteRequest and fetch a stock quote.
sqr, err := StockQuote().Symbol("AAPL").Get()
if err != nil {
	log.Fatalf("Failed to get stock quotes: %v", err)
}

// Check if the response contains the "AAPL" symbol.
for _, quote := range sqr {
	fmt.Printf("Symbol: %s\n", quote.Symbol)
}
Output:

Symbol: AAPL
Example (Packed)
// This example demonstrates how to create a StockQuoteRequest, set its parameters,
// and perform an actual request to fetch stock quotes for the "AAPL" symbol.

// Initialize a new StockQuoteRequest and fetch a stock quote.
sqr, err := StockQuote().Symbol("AAPL").Packed()
if err != nil {
	log.Fatalf("Failed to get stock quotes: %v", err)
}

// Iterate and print all the symbols in the slice.
for _, symbol := range sqr.Symbol {
	fmt.Printf("Symbol: %s\n", symbol)
}
Output:

Symbol: AAPL
Example (Raw)
// This example demonstrates how to create a StockQuoteRequest, set its parameters,
// and perform an actual request to fetch stock quotes for the "AAPL" symbol.
// The response is converted to a raw string and we print out the string at the end of the test.

// Initialize a new StockQuoteRequest and fetch a stock quote.
sqr, err := StockQuote().Symbol("AAPL").Raw()
if err != nil {
	log.Fatalf("Failed to get stock quotes: %v", err)
}

// Convert the response to a string.
sqrStr := sqr.String()

// Use regex to find the symbol in the response string.
re := regexp.MustCompile(`"symbol":\["(.*?)"\]`)
matches := re.FindStringSubmatch(sqrStr)

if len(matches) < 2 {
	log.Fatalf("Failed to extract symbol from response")
}

// Print the extracted symbol.
fmt.Printf("Symbol: %s\n", matches[1])
Output:

Symbol: AAPL

func StockQuote

func StockQuote() *StockQuoteRequest

StockQuote creates a new StockQuoteRequest and associates it with the default client. This function initializes the request with default parameters for symbol and fifty-two-week data, and sets the request path based on the predefined endpoints for stock quotes.

Returns

  • *StockQuoteRequest: A pointer to the newly created StockQuoteRequest with default parameters and associated client.

func (*StockQuoteRequest) FiftyTwoWeek

func (sqr *StockQuoteRequest) FiftyTwoWeek(q bool) *StockQuoteRequest

FiftyTwoWeek sets the fifty-two-week data parameter for the StockQuoteRequest. This method indicates whether to include fifty-two-week high and low data in the quote.

Parameters

  • bool: A bool indicating whether to include fifty-two-week data.

Returns

  • *StockQuoteRequest: This method returns a pointer to the *StockQuoteRequest instance it was called on. This allows for method chaining.

func (*StockQuoteRequest) Get

func (sqr *StockQuoteRequest) Get() ([]models.StockQuote, error)

Get sends the StockQuoteRequest, unpacks the StockQuotesResponse, and returns a slice of StockQuote. It returns an error if the request or unpacking fails.

Returns

  • []models.StockQuote: A slice of StockQuote containing the unpacked quote data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*StockQuoteRequest) Packed

Packed sends the StockQuoteRequest and returns the StockQuotesResponse.

Returns

  • *models.StockQuotesResponse: A pointer to the StockQuotesResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (*StockQuoteRequest) Raw

func (sqr *StockQuoteRequest) Raw() (*resty.Response, error)

Raw executes the StockQuoteRequest and returns the raw *resty.Response. This method returns the raw HTTP response from the executed request.

Returns

  • *resty.Response: The raw HTTP response from the executed request.
  • error: An error object if the request fails due to being nil, or other execution errors.

func (*StockQuoteRequest) Symbol

func (sqr *StockQuoteRequest) Symbol(q string) *StockQuoteRequest

Symbol sets the symbol parameter for the StockQuoteRequest. This method is used to specify the stock symbol for which quote data is requested.

Parameters

  • string: A string representing the stock symbol to be set.

Returns

  • *StockQuoteRequest: This method returns a pointer to the *StockQuoteRequest instance it was called on. This allows for method chaining.

type StockTickersRequestV2 added in v1.0.0

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

StockTickersRequestV2 represents a request to the /v2/stocks/tickers/ endpoint. It encapsulates the date parameter to be used in the request. This struct provides the method DateKey() to set this parameter.

Setter Methods

  • DateKey(q string) *StockTickersRequestV2: Sets the date parameter for the StockTickersRequestV2.
Example (Get)
tickers, err := StockTickers().DateKey("2023-01-05").Get()
if err != nil {
	fmt.Print(err)
	return
}
for _, ticker := range tickers {
	if ticker.Symbol == "AAPL" {
		fmt.Println(ticker)
		break
	}
}
Output:

Ticker{Symbol: AAPL, Name: Apple Inc., Type: CS, Currency: USD, Exchange: XNAS, FigiShares: BBG001S5N8V8, FigiComposite: BBG000B9XRY4, Cik: 0000320193, Updated: 2023-01-11 19:00:00 -05:00}

func StockTickers

func StockTickers() *StockTickersRequestV2

StockTickers creates a new StockTickersRequestV2 and associates it with the default client. This function initializes the request with the default date parameter and sets the request path based on the predefined endpoints for stock tickers.

Returns

  • *StockTickersRequestV2: A pointer to the newly created StockTickersRequestV2 with default parameters and associated client.

func (*StockTickersRequestV2) DateKey added in v1.0.0

DateKey sets the date parameter for the StockTickersRequestV2. This method is used to specify the date for which the stock tickers data is requested.

Parameters

  • string: A string representing the date to be set.

Returns

  • *StockTickersRequestV2: This method returns a pointer to the StockTickersRequestV2 instance it was called on. This allows for method chaining.

func (*StockTickersRequestV2) Get added in v1.0.0

func (str *StockTickersRequestV2) Get() ([]models.Ticker, error)

Get sends the StockTickersRequestV2, unpacks the TickersResponse, and returns a slice of Ticker. It returns an error if the request or unpacking fails. This method is crucial for obtaining the actual stock tickers data from the stock tickers request. The method first checks if the StockTickersRequestV2 receiver is nil, which would result in an error as the request cannot be sent. It then proceeds to send the request using the Packed method. Upon receiving the response, it unpacks the data into a slice of Ticker using the Unpack method from the response.

Returns

  • []models.Ticker: A slice of Ticker containing the unpacked tickers data from the response.
  • error: An error object that indicates a failure in sending the request or unpacking the response.

func (*StockTickersRequestV2) Packed added in v1.0.0

Packed sends the StockTickersRequestV2 and returns the TickersResponse. This method checks if the StockTickersRequestV2 receiver is nil, returning an error if true. Otherwise, it proceeds to send the request and returns the TickersResponse along with any error encountered during the request.

Returns

  • *models.TickersResponse: A pointer to the TickersResponse obtained from the request.
  • error: An error object that indicates a failure in sending the request.

func (StockTickersRequestV2) Raw added in v1.0.0

func (request StockTickersRequestV2) Raw() (*resty.Response, error)

Raw executes the request and returns the raw resty.Response.

Returns

  • *resty.Response: The raw response from the executed request.
  • error: An error object if the baseRequest is nil, or if an error occurs during the request execution.

Directories

Path Synopsis
helpers
dates
Package dates provides utilities for parsing, formatting, and manipulating dates and times.
Package dates provides utilities for parsing, formatting, and manipulating dates and times.
parameters
Package parameters defines structures and functions for handling request parameters across various API endpoints.
Package parameters defines structures and functions for handling request parameters across various API endpoints.
types
Package types provides utility functions for checking the type and value of variables.
Package types provides utility functions for checking the type and value of variables.
Package models defines the data structures used to represent the responses from the Market Data API.
Package models defines the data structures used to represent the responses from the Market Data API.

Jump to

Keyboard shortcuts

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