with dynamic attributes based on the summary content, and remove the trailing ."""
+ detail_pattern = re.compile(
+ r'(.*?) \((.*?)\)
\n',
+ re.DOTALL
+ )
+ return re.sub(detail_pattern, r'\n', content)
+
+def read_file_content(file_path):
+ """Read and return the content of the file."""
+ try:
+ with open(file_path, 'r') as file:
+ return file.read()
+ except FileNotFoundError:
+ print(f"Error: The file {file_path} was not found.")
+ return None
+
+def write_file_content(file_path, content):
+ """Write the given content to the file."""
+ with open(file_path, 'w') as file:
+ file.write(content)
+
+def remove_pattern(content, patterns):
+ """Remove all occurrences of the patterns from the content."""
+ for pattern in patterns:
+ pattern_str = r'\n?'.join([re.escape(part) for part in pattern])
+ pattern_re = re.compile(pattern_str, re.DOTALL)
+ content = re.sub(pattern_re, '', content, 1)
+ return content
+
+def replace_content(content, replacements):
+ """Replace occurrences based on a dictionary of find-and-replace pairs."""
+ for find, replace in replacements.items():
+ content = content.replace(find, replace)
+ return content
+
+def process_file(file_path, patterns, replacements):
+ """Process the file to remove specified patterns, replace specified strings, and convert to , including removing the trailing ."""
+ content = read_file_content(file_path)
+ if content is not None:
+ if patterns:
+ content = remove_pattern(content, patterns)
+ if replacements:
+ content = replace_content(content, replacements)
+ content = convert_details_to_tabitem(content) # Convert to and remove trailing
+ content = add_tabs_tags(content) # Add and tags
+ content = remove_output_blocks(content) # Remove output blocks
+ content = process_header_blocks(content) # Process header blocks
+ content = remove_index_block(content) # Remove index block
+ content = correct_escaping_in_links(content) # Correct escaping in links
+
+ write_file_content(file_path, content)
+ print(f"File {file_path} has been processed.")
+
+def combine_files_into_mdx(file_paths, output_mdx_path):
+ """Combine the content of multiple files into a single .mdx file."""
+ combined_content = ""
+ for file_path in file_paths:
+ with open(file_path, 'r') as file:
+ combined_content += file.read() + "\n\n" # Add some space between files
+ with open(output_mdx_path, 'w') as output_file:
+ output_file.write(combined_content)
+ print(f"Combined MDX file created at {output_mdx_path}")
+
+if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ print("Usage: ./process_markdown.py [ ...]")
+ sys.exit(1)
+
+ patterns = [
+ ['', '```go', 'import "."', '```', ''],
+ ['# client'],
+ ['# models'],
+ ['Generated by [gomarkdoc]()'],
+ ['']
+ ]
+ replacements = {
+ 'eoij4tlifi3': '',
+ '
\n ': '
' # Generate closing MDX tabs
+ }
+ for file_path in sys.argv[1:]:
+ process_file(file_path, patterns, replacements)
+ # Combine all processed files into a single .mdx file
+ output_mdx_path = "combined_output.mdx" # Specify your output .mdx file path here
+ process_file_paths = sys.argv[1:] # Assuming these are the paths of processed files
+ combine_files_into_mdx(process_file_paths, output_mdx_path)
diff --git a/client.go b/client.go
index 02850c6..83b640e 100644
--- a/client.go
+++ b/client.go
@@ -33,10 +33,6 @@
// 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.
-//
-// Environment:
-// The SDK can be configured to work with different environments (production, test, development)
-// by setting the appropriate host URL. The default environment is production.
package client
import (
diff --git a/helpers/dates/timeStrings.go b/helpers/dates/timeStrings.go
new file mode 100644
index 0000000..0785e60
--- /dev/null
+++ b/helpers/dates/timeStrings.go
@@ -0,0 +1,52 @@
+package dates
+
+import "time"
+
+// PreferredTimezone represents the preferred timezone for time display.
+var PreferredTimeStringTimezone = "America/New_York"
+
+// timeStringTimezone is the variable that stores the PreferredTimezone as a *time.Location.
+var timeStringTimezone *time.Location
+
+// TimeFormat specifies the format for displaying full datetime information.
+var TimeStringTimeFormat = "2006-01-02 15:04:05 Z07:00"
+
+// DateFormat specifies the format for displaying date-only information.
+var TimeStringDateFormat = "2006-01-02"
+
+func init() {
+ // Initialize defaultTimezone to UTC as a fallback
+ timeStringTimezone = time.UTC
+
+ // Attempt to load the preferred timezone
+ if loc, err := time.LoadLocation(PreferredTimeStringTimezone); err == nil {
+ timeStringTimezone = loc // Use preferred timezone if available
+ }
+}
+
+// TimeString converts a time.Time object to a string representation using a predefined timezone and format.
+// This method is primarily used in for string methods that need a standardized string representation of time.Time,
+// such as for logging, displaying to users, or when performing date-time comparisons in a specific timezone.
+//
+// # Parameters
+//
+// - time.Time: The time object to be formatted.
+//
+// # Returns
+//
+// - string: The formatted time as a string in the predefined timezone and format. Returns 'nil' if the time object is a zero value.
+//
+// # Notes
+//
+// - This method utilizes the global PreferredTimezone variable, which can be set to the preferred timezone or falls back to UTC if the preferred timezone is not set.
+func TimeString(t time.Time) string {
+ if t.IsZero() {
+ return "nil"
+ }
+ tInLoc := t.In(timeStringTimezone)
+ // Use IsStartOfDay from helpers/dates to check if the time is at the start of the day
+ if IsStartOfDay(tInLoc, timeStringTimezone) {
+ return tInLoc.Format(TimeStringDateFormat)
+ }
+ return tInLoc.Format(TimeStringTimeFormat)
+}
diff --git a/indices_candles.go b/indices_candles.go
index 63dc215..b5f60a1 100644
--- a/indices_candles.go
+++ b/indices_candles.go
@@ -7,15 +7,33 @@ import (
"github.com/MarketDataApp/sdk-go/models"
)
-// IndicesCandlesRequest represents a request to the /v1/indices/candles endpoint.
-// It encapsulates parameters for resolution, symbol, and date to be used in the request.
-// This struct provides methods such as Resolution(), Symbol(), Date(), and From() to set these parameters respectively.
+// IndicesCandlesRequest represents a request to the [/v1/indices/candles/{resolution}/{symbol}/] endpoint.
+// It encapsulates parameters for resolution, symbol, and dates to be used in the request.
+//
+// # Generated By
+//
+// - IndexCandles(client ...*MarketDataClient) *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.
//
-// # Public Methods:
// - Resolution(q string) *IndicesCandlesRequest: Sets the resolution parameter for the request.
// - Symbol(q string) *IndicesCandlesRequest: Sets the symbol parameter for the request.
// - Date(q interface{}) *IndicesCandlesRequest: Sets the date parameter for the request.
// - From(q 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.
+//
+// - Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
+// - Packed() (*IndicesCandlesResponse, error): Packs the request parameters and sends the request, returning a structured response.
+// - Get() ([]Candle, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
+//
+// [/v1/indices/candles/{resolution}/{symbol}/]: https://www.marketdata.app/docs/api/indices/candles
type IndicesCandlesRequest struct {
*baseRequest
resolutionParams *parameters.ResolutionParams // Holds the resolution parameter of the request.
@@ -27,14 +45,17 @@ type IndicesCandlesRequest struct {
// 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:
-// - q: A string representing the resolution to be set. Valid resolutions may include values like "1min", "5min", "1h", etc., depending on the API's supported resolutions.
+// # 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
//
-// 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.
+// - *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.
//
-// Note:
-// - 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 or error handling by the caller.
+// # 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 (icr *IndicesCandlesRequest) Resolution(q string) *IndicesCandlesRequest {
if icr == nil {
return nil
@@ -47,16 +68,18 @@ func (icr *IndicesCandlesRequest) Resolution(q string) *IndicesCandlesRequest {
}
// Symbol sets the symbol parameter for the IndicesCandlesRequest.
-// This method is used to specify the market symbol for which the candle data is requested.
-// It modifies the symbolParams field of the IndicesCandlesRequest instance to store the symbol value.
+// 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
//
-// Parameters:
-// - q: A string representing the market symbol to be set.
+// - *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.
//
-// 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
//
-// Note:
// - 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 (icr *IndicesCandlesRequest) Symbol(q string) *IndicesCandlesRequest {
if icr == nil {
@@ -71,16 +94,19 @@ func (icr *IndicesCandlesRequest) Symbol(q string) *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 dateParams field of the IndicesCandlesRequest instance to store the date value.
+// 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
//
-// Parameters:
-// - q: An interface{} representing the date to be set. It can be a string, a time.Time object, or any other type that the underlying SetDate method can process.
+// - *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.
//
-// 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
//
-// Note:
-// - If an error occurs while setting the date (e.g., if the date value is not supported), the Error field of the baseRequest 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.
+// - 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 (icr *IndicesCandlesRequest) Date(q interface{}) *IndicesCandlesRequest {
err := icr.dateParams.SetDate(q)
if err != nil {
@@ -90,11 +116,14 @@ func (icr *IndicesCandlesRequest) Date(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:
-// - q: An interface{} that represents the starting date. It can be a string, a time.Time object, or any other type that the underlying SetFrom method can process.
//
-// Returns:
-// - *IndicesCandlesRequest: A pointer to the IndicesCandlesRequest instance to allow for method chaining.
+// # Parameters
+//
+// - interface{}: An interface{} that represents the starting date. It can be a string, a time.Time object, or any other type that the underlying SetFrom method can process.
+//
+// # Returns
+//
+// - *IndicesCandlesRequest: A pointer to the *IndicesCandlesRequest instance to allow for method chaining.
func (icr *IndicesCandlesRequest) From(q interface{}) *IndicesCandlesRequest {
err := icr.dateParams.SetFrom(q)
if err != nil {
@@ -104,11 +133,14 @@ func (icr *IndicesCandlesRequest) From(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:
-// - q: 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.
+// # 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.
func (icr *IndicesCandlesRequest) To(q interface{}) *IndicesCandlesRequest {
err := icr.dateParams.SetTo(q)
if err != nil {
@@ -118,11 +150,14 @@ func (icr *IndicesCandlesRequest) To(q interface{}) *IndicesCandlesRequest {
}
// Countback sets the countback parameter for the IndicesCandlesRequest. It specifies the number of candles to return, counting backwards from the 'to' date.
-// Parameters:
-// - q: An int representing the number of candles to return.
//
-// Returns:
-// - *IndicesCandlesRequest: A pointer to the IndicesCandlesRequest instance to allow for method chaining.
+// # 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 (icr *IndicesCandlesRequest) Countback(q int) *IndicesCandlesRequest {
err := icr.dateParams.SetCountback(q)
if err != nil {
@@ -135,10 +170,8 @@ func (icr *IndicesCandlesRequest) Countback(q int) *IndicesCandlesRequest {
// This method is used to gather all the parameters set in the IndicesCandlesRequest into a single slice
// for easier manipulation and usage in subsequent requests.
//
-// Parameters:
-// - None
+// # Returns
//
-// Returns:
// - []parameters.MarketDataParam: A slice containing all the parameters set in the IndicesCandlesRequest.
// - error: An error object indicating failure to pack the parameters, nil if successful.
func (icr *IndicesCandlesRequest) getParams() ([]parameters.MarketDataParam, error) {
@@ -154,12 +187,14 @@ func (icr *IndicesCandlesRequest) getParams() ([]parameters.MarketDataParam, err
// An optional MarketDataClient can be passed to replace the client used in the request.
// Otherwise, it proceeds to send the request and returns the IndicesCandlesResponse along with any error encountered during the request.
//
-// Parameters:
-// - optionalClients: A variadic parameter that can accept zero or one MarketDataClient pointer. If a client is provided,
+// # Parameters
+//
+// - ...*MarketDataClient: A variadic parameter that can accept zero or one *MarketDataClient pointer. If a client is provided,
// it replaces the current client for this request.
//
-// Returns:
-// - *models.IndicesCandlesResponse: A pointer to the IndicesCandlesResponse obtained from 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 (icr *IndicesCandlesRequest) Packed(optionalClients ...*MarketDataClient) (*models.IndicesCandlesResponse, error) {
if icr == nil {
@@ -187,11 +222,13 @@ func (icr *IndicesCandlesRequest) Packed(optionalClients ...*MarketDataClient) (
// Upon receiving the response, it unpacks the data into a slice of IndexCandle using the Unpack method from the response.
// An optional MarketDataClient can be passed to replace the client used in the request.
//
-// Parameters:
-// - optionalClients: A variadic parameter that can accept zero or one MarketDataClient pointer. If a client is provided,
+// # Parameters
+//
+// - ...*MarketDataClient: A variadic parameter that can accept zero or one *MarketDataClient pointer. If a client is provided,
// it replaces the current client for this request.
//
-// Returns:
+// # Returns
+//
// - []models.IndexCandle: A slice of IndexCandle 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 (icr *IndicesCandlesRequest) Get(optionalClients ...*MarketDataClient) ([]models.Candle, error) {
@@ -219,12 +256,14 @@ func (icr *IndicesCandlesRequest) Get(optionalClients ...*MarketDataClient) ([]m
// with default parameters for date, resolution, and symbol, and sets the request path based on
// the predefined endpoints for indices candles.
//
-// Parameters:
-// - client: A variadic parameter that can accept zero or one MarketDataClient pointer. If no client is provided,
+// # Parameters
+//
+// - ...*MarketDataClient: A variadic parameter that can accept zero or one *MarketDataClient pointer. If no client is provided,
// the default client is used.
//
-// Returns:
-// - *IndicesCandlesRequest: A pointer to the newly created IndicesCandlesRequest with default parameters and associated client.
+// # Returns
+//
+// - *IndicesCandlesRequest: A pointer to the newly created *IndicesCandlesRequest with default parameters and associated client.
func IndexCandles(client ...*MarketDataClient) *IndicesCandlesRequest {
baseReq := newBaseRequest(client...)
baseReq.path = endpoints[1]["indices"]["candles"]
diff --git a/indices_quotes.go b/indices_quotes.go
index 0a470cb..a09c9f0 100644
--- a/indices_quotes.go
+++ b/indices_quotes.go
@@ -7,13 +7,32 @@ import (
"github.com/MarketDataApp/sdk-go/models"
)
-// IndexQuoteRequest represents a request to the /indices/quote endpoint.
+// 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.
//
-// Public Methods:
-// - Symbol(q string) *IndexQuoteRequest: Sets the symbol parameter for the request.
-// - FiftyTwoWeek(q bool) *IndexQuoteRequest: Sets the fifty-two-week parameter for the request.
+// # Generated By
+//
+// - IndexQuotes(client ...*MarketDataClient): 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.
+//
+// - Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response.
+// - Packed() (*IndexQuotesResponse, error): Packs the request parameters and sends the request, returning a structured response.
+// - Get() ([]IndexQuote, error): Sends the request, unpacks the response, and returns the data in a user-friendly format.
+//
+// [/v1/indices/quotes/]: https://www.marketdata.app/docs/api/indices/quotes
type IndexQuoteRequest struct {
*baseRequest
symbolParams *parameters.SymbolParams
@@ -24,13 +43,16 @@ type IndexQuoteRequest struct {
// 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:
-// - q: A string representing the market symbol to be set.
+// # Parameters
+//
+// - string: A string representing the market symbol to be set.
+//
+// # Returns
//
-// 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:
+// # 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.
func (iqr *IndexQuoteRequest) Symbol(q string) *IndexQuoteRequest {
if iqr == nil {
@@ -47,10 +69,12 @@ func (iqr *IndexQuoteRequest) Symbol(q string) *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:
-// - q: A boolean indicating whether to include fifty-two-week data.
+// # Parameters
+//
+// - bool: A boolean indicating whether to include fifty-two-week data.
+//
+// # Returns
//
-// 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 (iqr *IndexQuoteRequest) FiftyTwoWeek(q bool) *IndexQuoteRequest {
if iqr == nil {
@@ -64,7 +88,8 @@ func (iqr *IndexQuoteRequest) FiftyTwoWeek(q bool) *IndexQuoteRequest {
// This method is used to gather all the parameters set in the IndexQuoteRequest into a single slice
// for easier manipulation and usage in subsequent requests.
//
-// Returns:
+// # Returns
+//
// - []parameters.MarketDataParam: A slice containing all the parameters set in the IndexQuoteRequest.
// - error: An error object indicating failure to pack the parameters, nil if successful.
func (iqr *IndexQuoteRequest) getParams() ([]parameters.MarketDataParam, error) {
@@ -79,11 +104,14 @@ func (iqr *IndexQuoteRequest) getParams() ([]parameters.MarketDataParam, error)
// This method checks if the IndexQuoteRequest receiver is nil, returning an error if true.
// An optional MarketDataClient can be passed to replace the client used in the request.
// Otherwise, it proceeds to send the request and returns the IndexQuotesResponse along with any error encountered during the request.
-// Parameters:
-// - optionalClients: A variadic parameter that can accept zero or one MarketDataClient pointer. If a client is provided,
+//
+// # Parameters
+//
+// - ...*MarketDataClient: A variadic parameter that can accept zero or one *MarketDataClient pointer. If a client is provided,
// it replaces the current client for this request.
//
-// Returns:
+// # 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 (iqr *IndexQuoteRequest) Packed(optionalClients ...*MarketDataClient) (*models.IndexQuotesResponse, error) {
@@ -111,11 +139,14 @@ func (iqr *IndexQuoteRequest) Packed(optionalClients ...*MarketDataClient) (*mod
// 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 IndexQuote using the Unpack method from the response.
// An optional MarketDataClient can be passed to replace the client used in the request.
-// Parameters:
-// - optionalClients: A variadic parameter that can accept zero or one MarketDataClient pointer. If a client is provided,
+//
+// # Parameters
+//
+// - ...*MarketDataClient: A variadic parameter that can accept zero or one MarketDataClient pointer. If a client is provided,
// it replaces the current client for this request.
//
-// Returns:
+// # 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 (iqr *IndexQuoteRequest) Get(optionalClients ...*MarketDataClient) ([]models.IndexQuote, error) {
@@ -142,11 +173,13 @@ func (iqr *IndexQuoteRequest) Get(optionalClients ...*MarketDataClient) ([]model
// If no client is provided, it uses 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.
-// Parameters:
-// - client: A variadic parameter that can accept zero or one MarketDataClient pointer. If no client is provided,
-// the default client is used.
//
-// Returns:
+// # Parameters
+//
+// - ...*MarketDataClient: A variadic parameter that can accept zero or one MarketDataClient pointer. If no client is provided, the default client is used.
+//
+// # Returns
+//
// - *IndexQuoteRequest: A pointer to the newly created IndexQuoteRequest with default parameters and associated client.
func IndexQuotes(client ...*MarketDataClient) *IndexQuoteRequest {
baseReq := newBaseRequest(client...)
diff --git a/models/candle.go b/models/candle.go
index 01bc6d7..7c031f1 100644
--- a/models/candle.go
+++ b/models/candle.go
@@ -9,8 +9,27 @@ import (
"github.com/MarketDataApp/sdk-go/helpers/dates"
)
-// Candle represents a single candle in a stock candlestick chart.
-// It includes the time, open, high, low, close prices, volume, and optionally symbol, VWAP and number of trades.
+// Candle represents a single candle in a stock candlestick chart, encapsulating the time, open, high, low, close prices,
+// volume, and optionally the symbol, VWAP, and number of trades.
+//
+// # Generated By
+//
+// - StockCandlesResponse.Unpack(): Generates Candle instances from a StockCandlesResponse.
+// - BulkStockCandlesResponse.Unpack(): Generates Candle instances from a BulkStockStockCandlesResponse.
+// - IndicesCandlesResponse.Unpack(): Generates Candle instances from a IndicesCandlesResponse.
+//
+// # Methods
+//
+// - String() string: Provides a string representation of the Candle.
+// - Equals(other Candle) bool: Checks if two Candle instances are equal.
+// - MarshalJSON() ([]byte, error): Customizes the JSON output of Candle.
+// - UnmarshalJSON(data []byte) error: Customizes the JSON input processing of Candle.
+//
+// # Notes
+//
+// - The VWAP, N fields are optional and will only be present in v2 Stock Candles.
+// - The Volume field is optional and will not be present in Index Candles.
+// - The Symbol field is optional and only be present in candles that were generated using the bulkcandles endpoint.
type Candle struct {
Symbol string `json:"symbol,omitempty"` // The symbol of the candle.
Date time.Time `json:"t"` // Date represents the date and time of the candle.
@@ -23,10 +42,16 @@ type Candle struct {
N int64 `json:"n,omitempty"` // N is the number of trades that occurred, optional.
}
-// String returns a string representation of a Candle.
+// String provides a textual representation of the Candle instance. This method is primarily used for logging or debugging purposes, where a developer needs a quick and easy way to view the contents of a Candle instance in a human-readable format.
+//
+// # Returns
//
-// Returns:
-// - A string representation of the Candle.
+// - string: A string that represents the Candle instance, including its symbol, date/time, open, high, low, close prices, volume, VWAP, and number of trades, if available.
+//
+// # Notes
+//
+// - The output format is designed to be easily readable, with each field labeled and separated by commas.
+// - Fields that are not applicable or not set (e.g., VWAP, N, Volume for Index Candles) are omitted from the output.
func (c Candle) String() string {
loc, _ := time.LoadLocation("America/New_York")
var parts []string
@@ -57,6 +82,22 @@ func (c Candle) String() string {
return "Candle{" + strings.Join(parts, ", ") + "}"
}
+// Equals compares the current Candle instance with another Candle instance to determine if they represent the same candle data.
+// This method is useful for validating if two Candle instances have identical properties, including symbol, date/time, open,
+// high, low, close prices, volume, VWAP, and number of trades. It's primarily used in scenarios where candle data integrity
+// needs to be verified or when deduplicating candle data.
+//
+// # Parameters
+//
+// - Candle: The other Candle instance to compare against the current instance.
+//
+// # Returns
+//
+// - bool: Indicates whether the two Candle instances are identical. True if all properties match, false otherwise.
+//
+// # Notes
+//
+// - This method performs a deep equality check on all Candle properties, including date/time which is compared using the Equal method from the time package to account for potential timezone differences.
func (c Candle) Equals(other Candle) bool {
return c.Symbol == other.Symbol &&
c.Date.Equal(other.Date) &&
@@ -69,7 +110,16 @@ func (c Candle) Equals(other Candle) bool {
c.N == other.N
}
-// MarshalJSON customizes the JSON output of Candle.
+// MarshalJSON customizes the JSON output of the Candle struct, primarily used for converting the Candle data into a JSON format that includes the Date as a Unix timestamp instead of the standard time.Time format. This method is particularly useful when the Candle data needs to be serialized into JSON for storage or transmission over networks where a compact and universally understood date format is preferred.
+//
+// # Returns
+//
+// - []byte: The JSON-encoded representation of the Candle.
+// - error: An error if the JSON marshaling fails.
+//
+// # Notes
+//
+// - The Date field of the Candle is converted to a Unix timestamp to facilitate easier handling of date and time in JSON.
func (c Candle) MarshalJSON() ([]byte, error) {
// Define a struct that matches Candle but with Date as an integer (Unix timestamp).
type Alias Candle
@@ -83,6 +133,20 @@ func (c Candle) MarshalJSON() ([]byte, error) {
}
// UnmarshalJSON customizes the JSON input processing of Candle.
+//
+// UnmarshalJSON customizes the JSON input processing for the Candle struct, allowing for the Date field to be correctly interpreted from a Unix timestamp (integer) back into a Go time.Time object. This method is essential for deserializing Candle data received in JSON format, where date and time are represented as Unix timestamps, ensuring the Candle struct accurately reflects the original data.
+//
+// # Parameters
+//
+// - data []byte: The JSON-encoded data that is to be unmarshaled into the Candle struct.
+//
+// # Returns
+//
+// - error: An error if the JSON unmarshaling fails, nil otherwise.
+//
+// # Notes
+//
+// - The Date field in the JSON is expected to be a Unix timestamp (integer). This method converts it back to a time.Time object, ensuring the Candle struct's Date field is correctly populated.
func (c *Candle) UnmarshalJSON(data []byte) error {
// Define a struct that matches Candle but with Date as an integer (Unix timestamp).
type Alias Candle
@@ -163,6 +227,11 @@ func (a BySymbol) Len() int { return len(a) }
func (a BySymbol) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a BySymbol) Less(i, j int) bool { return a[i].Symbol < a[j].Symbol }
+// Clones the current Candle instance, creating a new instance with the same values. This method is useful when you need a copy of a Candle instance without modifying the original instance.
+//
+// # Returns
+//
+// - Candle: A new Candle instance with the same values as the current instance.
func (c Candle) Clone() Candle {
return Candle{
Symbol: c.Symbol,
@@ -177,40 +246,49 @@ func (c Candle) Clone() Candle {
}
}
-// IsBefore checks if the current Candle instance occurred before the specified Candle.
+// IsBefore determines whether the current Candle instance occurred before another specified Candle instance.
+// This method is primarily used for comparing the dates of two Candle instances to establish their chronological order,
+// which can be useful in time series analysis or when organizing historical financial data.
+//
+// # Parameters
+//
+// - other Candle: The Candle instance to compare with the current Candle instance.
+//
+// # Returns
//
-// Parameters:
-// - other: A Candle instance to compare with the current Candle instance.
+// - bool: Returns true if the date of the current Candle instance is before the date of the 'other' Candle instance; otherwise, returns false.
//
-// Returns:
-// - bool: Returns true if the current Candle's date is before the 'other' Candle's date; otherwise, false.
+// # Notes
+//
+// - This method only compares the dates of the Candle instances, ignoring other fields such as Open, Close, High, Low, etc.
func (c Candle) IsBefore(other Candle) bool {
return c.Date.Before(other.Date)
}
-// IsAfter checks if the current Candle instance occurred after the specified Candle.
+// IsAfter determines if the current Candle instance occurred after another specified Candle instance. This method is useful
+// for chronological comparisons between two Candle instances, particularly in time series analysis or when organizing historical
+// financial data in ascending order.
+//
+// # Parameters
//
-// Parameters:
-// - other: A Candle instance to compare with the current Candle instance.
+// - other Candle: The Candle instance to compare with the current Candle instance.
//
-// Returns:
-// - bool: Returns true if the current Candle's date is after the 'other' Candle's date; otherwise, false.
+// # Returns
+//
+// - bool: Indicates whether the current Candle's date is after the 'other' Candle's date. Returns true if it is; otherwise, false.
func (c Candle) IsAfter(other Candle) bool {
return c.Date.After(other.Date)
}
-// IsValid checks the validity of the Candle based on its financial data.
+// IsValid evaluates the financial data of a Candle to determine its validity. This method is essential for ensuring that
+// the Candle's data adheres to basic financial integrity rules, making it a critical step before performing further
+// analysis or operations with Candle data. A Candle is deemed valid if its high, open, and close prices are logically
+// consistent with each other and its volume is non-negative.
+//
+// # Returns
//
-// A Candle is considered valid if:
-// - The high price is greater than or equal to the low price.
-// - The open price is greater than or equal to the low price.
-// - The close price is greater than or equal to the low price.
-// - The high price is greater than or equal to the open price.
-// - The high price is greater than or equal to the close price.
-// - The volume is non-negative.
+// - bool: Indicates whether the Candle is valid based on its financial data. Returns true if all validity criteria are met; otherwise, false.
//
-// Returns:
-// - bool: Returns true if the Candle meets all the validity criteria; otherwise, false.
func (c Candle) IsValid() bool {
return c.High >= c.Low && c.Open >= c.Low && c.Close >= c.Low && c.High >= c.Open && c.High >= c.Close && c.Volume >= 0
}
diff --git a/models/indices_candles.go b/models/indices_candles.go
index afa85d2..11d7d1e 100644
--- a/models/indices_candles.go
+++ b/models/indices_candles.go
@@ -10,18 +10,34 @@ import (
// IndicesCandlesResponse represents the response structure for indices candles data.
// It includes slices for time, open, high, low, and close values of the indices.
+//
+// # Generated By
+//
+// - IndexCandlesRequest.Packed(): This method sends the IndicesCandlesRequest to the Market Data API and returns the IndicesCandlesResponse. It handles the actual communication with the [/v1/indices/candles/] endpoint, sending the request, and returns a packed response that strictly conforms to the Market Data JSON response without unpacking the result into individual candle structs.
+//
+// # Methods
+//
+// - String(): Provides a formatted string representation of the IndicesCandlesResponse instance. This method is primarily used for logging or debugging purposes, allowing the user to easily view the contents of an IndicesCandlesResponse object in a human-readable format. It concatenates the time, open, high, low, and close values of the indices into a single string.
+// - Unpack() ([]Candle, error): Unpacks the IndicesCandlesResponse into a slice of Candle structs, checking for errors in data consistency.
+// - MarshalJSON(): Marshals the IndicesCandlesResponse into a JSON object with ordered keys.
+// - UnmarshalJSON(data []byte): Custom unmarshals a JSON object into the IndicesCandlesResponse, including validation.
+// - Validate(): Runs checks for time in ascending order, equal slice lengths, and no empty slices.
+// - IsValid(): Checks if the IndicesCandlesResponse passes all validation checks and returns a boolean.
type IndicesCandlesResponse struct {
- Date []int64 `json:"t" human:"Date"`
- Open []float64 `json:"o" human:"Open"`
- High []float64 `json:"h" human:"High"`
- Low []float64 `json:"l" human:"Low"`
- Close []float64 `json:"c" human:"Close"`
+ Date []int64 `json:"t"` // Date holds the Unix timestamps for each candle, representing the time at which each candle was opened.
+ Open []float64 `json:"o"` // Open contains the opening prices for each candle in the response.
+ High []float64 `json:"h"` // High includes the highest prices reached during the time period each candle represents.
+ Low []float64 `json:"l"` // Low encompasses the lowest prices during the candle's time period.
+ Close []float64 `json:"c"` // Close contains the closing prices for each candle, marking the final price at the end of each candle's time period.
}
-
-// String returns a string representation of the IndicesCandlesResponse.
+// String provides a formatted string representation of the IndicesCandlesResponse instance.
+// This method is primarily used for logging or debugging purposes, allowing the user to easily
+// view the contents of an IndicesCandlesResponse object in a human-readable format. It concatenates
+// the time, open, high, low, and close values of the indices into a single string.
//
-// Returns:
-// - A formatted string containing the time, open, high, low, and close values.
+// # Returns
+//
+// - string: A formatted string containing the time, open, high, low, and close values of the indices.
func (icr *IndicesCandlesResponse) String() string {
return fmt.Sprintf("IndicesCandlesResponse{Time: %v, Open: %v, High: %v, Low: %v, Close: %v}",
icr.Date, icr.Open, icr.High, icr.Low, icr.Close)
@@ -104,14 +120,14 @@ func (icr *IndicesCandlesResponse) Unpack() ([]Candle, error) {
return indexCandles, nil
}
-// MarshalJSON is a method on the IndicesCandlesResponse struct.
-// It marshals the struct into a JSON object.
-// The JSON object is an ordered map with keys "s", "t", "o", "h", "l", and "c".
-// The "s" key is always set to "ok".
-// The "t", "o", "h", "l", and "c" keys correspond to the Time, Open, High, Low, and Close slices in the struct.
+// MarshalJSON marshals the IndicesCandlesResponse struct into a JSON object, ensuring the keys are ordered as specified.
+// This method is particularly useful when a consistent JSON structure with ordered keys is required for external interfaces or storage.
+// The "s" key is set to "ok" to indicate successful marshaling, followed by the indices data keys "t", "o", "h", "l", and "c".
//
-// Returns:
-// - A byte slice of the JSON object, error if marshaling fails.
+// # Returns
+//
+// - []byte: A byte slice representing the marshaled JSON object. The keys within the JSON object are ordered as "s", "t", "o", "h", "l", and "c".
+// - error: An error object if marshaling fails, otherwise nil.
func (icr *IndicesCandlesResponse) MarshalJSON() ([]byte, error) {
// Create a new ordered map
o := orderedmap.New()
@@ -130,13 +146,15 @@ func (icr *IndicesCandlesResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(o)
}
-// UnmarshalJSON custom unmarshals a JSON object into the IndicesCandlesResponse.
+// UnmarshalJSON custom unmarshals a JSON object into the IndicesCandlesResponse, incorporating validation to ensure the data integrity of the unmarshaled object. This method is essential for converting JSON data into a structured IndicesCandlesResponse object while ensuring that the data adheres to expected formats and constraints.
//
-// Parameters:
-// - data: A byte slice of the JSON object to be unmarshaled.
+// # Parameters
//
-// Returns:
-// - An error if unmarshaling or validation fails.
+// - []byte: A byte slice of the JSON object to be unmarshaled.
+//
+// # Returns
+//
+// - error: An error if unmarshaling or validation fails, otherwise nil.
func (icr *IndicesCandlesResponse) UnmarshalJSON(data []byte) error {
// Define a secondary type to prevent infinite recursion
type Alias IndicesCandlesResponse
@@ -162,10 +180,11 @@ func (icr *IndicesCandlesResponse) UnmarshalJSON(data []byte) error {
return nil
}
-// Validate runs multiple checks on the IndicesCandlesResponse: time in ascending order, equal slice lengths, and no empty slices.
+// Validate performs multiple checks on the IndicesCandlesResponse to ensure data integrity. This method is crucial for verifying that the response data is consistent and reliable, specifically checking for time sequence, equal length of data slices, and the presence of data in each slice. It's used to preemptively catch and handle data-related errors before they can affect downstream processes.
//
-// Returns:
-// - An error if any of the checks fail, nil otherwise.
+// # Returns
+//
+// - error: An error if any validation check fails, otherwise nil. This allows for easy identification of data integrity issues.
func (icr *IndicesCandlesResponse) Validate() error {
// Create a channel to handle errors
errChan := make(chan error, 3)
@@ -186,13 +205,17 @@ func (icr *IndicesCandlesResponse) Validate() error {
return nil
}
-// IsValid checks if the IndicesCandlesResponse passes all validation checks.
-//
-// Returns:
-// - A boolean indicating if the response is valid.
+// IsValid determines the validity of the IndicesCandlesResponse based on various validation checks.
+// This method is primarily used to quickly assess if the response data adheres to expected formats and constraints,
+// making it a crucial step before further processing of the response data.
+
+// # Returns
+//
+// - bool: Indicates whether the IndicesCandlesResponse is valid.
func (icr *IndicesCandlesResponse) IsValid() bool {
if err := icr.Validate(); err != nil {
return false
}
return true
}
+
diff --git a/models/indices_quotes.go b/models/indices_quotes.go
index 7454a95..26071af 100644
--- a/models/indices_quotes.go
+++ b/models/indices_quotes.go
@@ -4,11 +4,25 @@ import (
"fmt"
"strings"
"time"
+
+ "github.com/MarketDataApp/sdk-go/helpers/dates"
)
-// IndexQuotesResponse represents the response structure for index quotes.
-// It includes slices for symbols, last prices, changes, percentage changes,
-// 52-week highs, 52-week lows, and update timestamps.
+// IndexQuotesResponse encapsulates the data for index quotes, including symbols, last prices, price changes, percentage changes, 52-week highs and lows, and update timestamps.
+//
+// # Generated By
+//
+// - IndexQuoteRequest.Packed(): Fetches index quotes and returns them in an IndexQuotesResponse struct.
+//
+// # Methods
+//
+// - Unpack() ([]IndexQuote, error): Transforms the IndexQuotesResponse into a slice of IndexQuote for individual processing.
+// - String() string: Provides a string representation of the IndexQuotesResponse for logging or debugging.
+//
+// # Notes
+//
+// - The Change and ChangePct fields are pointers to accommodate nil values, indicating that the change information is not applicable or unavailable.
+// - The High52 and Low52 fields are pointers to slices, allowing for the entire field to be nil if 52-week high/low data is not applicable or unavailable.
type IndexQuotesResponse struct {
Symbol []string `json:"symbol"` // Symbols are the stock symbols or tickers.
Last []float64 `json:"last"` // Last contains the last traded prices.
@@ -19,9 +33,20 @@ type IndexQuotesResponse struct {
Updated []int64 `json:"updated"` // Updated contains timestamps of the last updates.
}
-// IndexQuote represents a single quote for an index.
-// It includes the symbol, last price, change, percentage change,
-// 52-week high, 52-week low, volume, and update timestamp.
+// IndexQuote represents a single quote for an index, encapsulating details such as the symbol, last traded price, price changes, 52-week high and low prices, volume, and the timestamp of the last update.
+//
+// # Generated By
+//
+// - Unpack(): Generates IndexQuote instances from an IndexQuotesResponse.
+//
+// # Methods
+//
+// - String() string: Provides a string representation of the IndexQuote.
+//
+// # Notes
+//
+// - The Change and ChangePct fields are pointers to accommodate nil values, indicating that the change information is not applicable or unavailable.
+// - The High52 and Low52 fields are also pointers, allowing these fields to be nil if 52-week high/low data is not applicable or unavailable.
type IndexQuote struct {
Symbol string // Symbol is the stock symbol or ticker.
Last float64 // Last is the last traded price.
@@ -33,10 +58,13 @@ type IndexQuote struct {
Updated time.Time // Updated is the timestamp of the last update.
}
-// String returns a string representation of the IndexQuote.
+// String generates a string representation of the IndexQuote for easy human-readable display. It is useful for logging,
+// debugging, or displaying the IndexQuote details, including symbol, last traded price, volume, update timestamp,
+// and optionally, 52-week highs, lows, and price changes if available.
//
-// Returns:
-// - A string that represents the IndexQuote.
+// # Returns
+//
+// - string: A formatted string encapsulating the IndexQuote details. It includes the symbol, last price, volume, update timestamp, and, if not nil, 52-week highs, lows, change, and percentage change.
func (iq IndexQuote) String() string {
high52 := "nil"
if iq.High52 != nil {
@@ -55,14 +83,17 @@ func (iq IndexQuote) String() string {
changePct = fmt.Sprintf("%v", *iq.ChangePct)
}
return fmt.Sprintf("IndexQuote{Symbol: %q, Last: %v, Volume: %v, Updated: %q, High52: %s, Low52: %s, Change: %s, ChangePct: %s}",
- iq.Symbol, iq.Last, iq.Volume, formatTime(iq.Updated), high52, low52, change, changePct)
+ iq.Symbol, iq.Last, iq.Volume, dates.TimeString(iq.Updated), high52, low52, change, changePct)
}
-// Unpack transforms the IndexQuotesResponse into a slice of IndexQuote.
+// Unpack transforms the IndexQuotesResponse into a slice of IndexQuote. This method is primarily used
+// for converting a bulk response of index quotes into individual index quote objects, making them easier to work with
+// in a program. It is useful when you need to process or display index quotes individually after fetching them in bulk.
+//
+// # Returns
//
-// Returns:
-// - A slice of IndexQuote derived from the IndexQuotesResponse.
-// - An error if any issues occur during the unpacking process.
+// - []IndexQuote: A slice of IndexQuote derived from the IndexQuotesResponse, allowing for individual access and manipulation of index quotes.
+// - error: An error if any issues occur during the unpacking process, enabling error handling in the calling function.
func (iqr *IndexQuotesResponse) Unpack() ([]IndexQuote, error) {
var indexQuotes []IndexQuote
for i := range iqr.Symbol {
@@ -90,10 +121,14 @@ func (iqr *IndexQuotesResponse) Unpack() ([]IndexQuote, error) {
return indexQuotes, nil
}
-// String returns a string representation of the IndexQuotesResponse.
+// String provides a formatted string representation of the IndexQuotesResponse instance. This method is primarily used for
+// logging or debugging purposes, allowing the user to easily view the contents of an IndexQuotesResponse object in a
+// human-readable format. It concatenates various fields of the IndexQuotesResponse into a single string, making it
+// easier to understand the response at a glance.
+//
+// # Returns
//
-// Returns:
-// - A string that represents the IndexQuotesResponse.
+// - string: A formatted string containing the contents of the IndexQuotesResponse.
func (iqr *IndexQuotesResponse) String() string {
var result strings.Builder
@@ -117,13 +152,15 @@ func (iqr *IndexQuotesResponse) String() string {
return result.String()
}
-// joinFloat64Slice joins a slice of float64 into a single string.
-//
-// Parameters:
-// - slice: The slice of float64 to be joined.
-//
-// Returns:
-// - A string representation of the joined slice.
+// joinFloat64Slice converts a slice of float64 values into a single, comma-separated string.
+// This method is primarily used for creating a human-readable string representation of numerical data,
+// which can be useful for logging, debugging, or displaying data to end-users.
+
+// # Parameters
+// - []float64 slice: The slice of float64 values to be joined.
+
+// # Returns
+// - string: A comma-separated string representation of the input slice.
func joinFloat64Slice(slice []float64) string {
strs := make([]string, len(slice))
for i, v := range slice {
@@ -134,10 +171,12 @@ func joinFloat64Slice(slice []float64) string {
// joinFloat64PointerSlice joins a slice of *float64 into a single string, handling nil pointers gracefully.
//
-// Parameters:
+// # Parameters:
+//
// - slice: The slice of *float64 to be joined.
//
-// Returns:
+// # Returns:
+//
// - A string representation of the joined slice, with "nil" for nil pointers.
func joinFloat64PointerSlice(slice []*float64) string {
strs := make([]string, len(slice))
@@ -153,10 +192,12 @@ func joinFloat64PointerSlice(slice []*float64) string {
// joinInt64Slice joins a slice of int64 into a single string.
//
-// Parameters:
+// # Parameters:
+//
// - slice: The slice of int64 to be joined.
//
-// Returns:
+// # Returns:
+//
// - A string representation of the joined slice.
func joinInt64Slice(slice []int64) string {
strs := make([]string, len(slice))
diff --git a/models/market_status_test.go b/models/market_status_test.go
index 3ce3101..cd105a6 100644
--- a/models/market_status_test.go
+++ b/models/market_status_test.go
@@ -9,7 +9,7 @@ func TestGetOpenDates(t *testing.T) {
// Create a mock MarketStatusResponse
msr := &MarketStatusResponse{
Date: []int64{time.Now().Unix(), time.Now().AddDate(0, 0, -1).Unix()},
- Status: &[]string{"open", "closed"},
+ Status: []string{"open", "closed"},
}
openDates, err := msr.GetOpenDates()
@@ -30,7 +30,7 @@ func TestGetClosedDates(t *testing.T) {
// Create a mock MarketStatusResponse
msr := &MarketStatusResponse{
Date: []int64{time.Now().Unix(), time.Now().AddDate(0, 0, -1).Unix()},
- Status: &[]string{"open", "closed"},
+ Status: []string{"open", "closed"},
}
closedDates, err := msr.GetClosedDates()
diff --git a/models/markets_status.go b/models/markets_status.go
index 67146f5..4fab2ed 100644
--- a/models/markets_status.go
+++ b/models/markets_status.go
@@ -8,62 +8,76 @@ import (
"github.com/MarketDataApp/sdk-go/helpers/dates"
)
-// MarketStatusResponse holds the response data for a market status request.
-// It includes a slice of dates and an optional slice of corresponding market statuses.
+// MarketStatusResponse encapsulates the response data for market status queries, including dates and optionally, the
+// corresponding market statuses.
+//
+// # Generated By
+//
+// - MarketStatusRequest.Get(): Generates a MarketStatusResponse containing market status information for requested dates.
+//
+// # Methods
+//
+// - String(): Returns a string representation of the MarketStatusResponse.
type MarketStatusResponse struct {
- Date []int64 `json:"date"` // Date contains UNIX timestamps for each market status entry.
- Status *[]string `json:"status,omitempty"` // Status is a pointer to a slice of market status strings, which can be omitted if empty.
+ Date []int64 `json:"date"` // Date contains UNIX timestamps for each market status entry.
+ Status []string `json:"status"` // Status is a pointer to a slice of market status strings, which can be omitted if empty.
}
-// IsValid checks if the MarketStatusResponse contains at least one date.
+// IsValid determines whether the MarketStatusResponse instance has at least one date entry.
+// This method is primarily used to verify that the response is not empty, indicating that there is market status data available for processing.
//
-// Returns:
-// - bool: True if there is at least one date, false otherwise.
+// # Returns
+//
+// - bool: Indicates whether there is at least one date entry in the MarketStatusResponse. True if at least one date is present, false otherwise.
func (msr *MarketStatusResponse) IsValid() bool {
return len(msr.Date) > 0
}
-// String returns a string representation of the MarketStatusResponse, including dates and their corresponding statuses.
+// String provides a formatted string representation of the MarketStatusResponse instance. This method is primarily used for logging
+// or debugging purposes, allowing the user to easily view the contents of a MarketStatusResponse object in a human-readable format.
+// It concatenates the dates and their corresponding statuses into a single string.
//
-// Returns:
-// - string: A string representation of the MarketStatusResponse.
+// # Returns
+//
+// - string: A formatted string containing the dates and their corresponding statuses.
func (msr *MarketStatusResponse) String() string {
- dateParts := make([]string, len(msr.Date))
- for i, date := range msr.Date {
- dateParts[i] = fmt.Sprintf("%v", date)
- }
- statusParts := "nil"
- if msr.Status != nil {
- statusSlice := make([]string, len(*msr.Status))
- for i, status := range *msr.Status {
- statusSlice[i] = fmt.Sprintf("%q", status)
- }
- statusParts = "[" + strings.Join(statusSlice, ", ") + "]"
- }
- return fmt.Sprintf("MarketStatusResponse{Date: [%s], Status: %s}", strings.Join(dateParts, ", "), statusParts)
+ dateParts := make([]string, len(msr.Date))
+ for i, date := range msr.Date {
+ dateParts[i] = fmt.Sprintf("%v", date)
+ }
+ statusParts := "nil"
+ if len(msr.Status) > 0 {
+ statusSlice := make([]string, len(msr.Status))
+ for i, status := range msr.Status {
+ statusSlice[i] = fmt.Sprintf("%q", status)
+ }
+ statusParts = "[" + strings.Join(statusSlice, ", ") + "]"
+ }
+ return fmt.Sprintf("MarketStatusResponse{Date: [%s], Status: %s}", strings.Join(dateParts, ", "), statusParts)
}
-// String returns a string representation of the MarketStatusReport.
+// Unpack transforms the MarketStatusResponse into a slice of MarketStatusReport, facilitating the analysis or processing
+// of market status data in a structured format. This method is particularly useful when there's a need to iterate over
+// market statuses, perform conditional checks, or when preparing the data for display. It ensures that each market status
+// entry is paired with its corresponding date, converting UNIX timestamps to time.Time objects and mapping status strings
+// to boolean open/closed indicators.
//
-// Returns:
-// - string: A string representation of the MarketStatusReport.
-func (ms MarketStatusReport) String() string {
- return fmt.Sprintf("MarketStatusReport{Date: %v, Open: %v, Closed: %v}", formatTime(ms.Date), ms.Open, ms.Closed)
-}
-
-// Unpack unpacks the MarketStatusResponse into a slice of MarketStatusReport.
+// # Returns
//
-// Returns:
-// - []MarketStatusReport: A slice of MarketStatusReport derived from the MarketStatusResponse.
-// - error: An error if the date and status slices are not of the same length or any other issue occurs.
+// - []MarketStatusReport: A slice of MarketStatusReport, each representing a market status entry with its date and open/closed status.
+// - error: An error indicating issues with data consistency, such as mismatched slice lengths, or any other processing error.
+//
+// # Notes
+//
+// - The method assumes that the lengths of the Date and Status slices in the MarketStatusResponse are equal. An error is returned if this is not the case.
func (msr *MarketStatusResponse) Unpack() ([]MarketStatusReport, error) {
- if msr.Status == nil || len(msr.Date) != len(*msr.Status) {
+ if len(msr.Date) != len(msr.Status) {
return nil, fmt.Errorf("date and status slices are not of the same length")
}
var marketStatuses []MarketStatusReport
for i, date := range msr.Date {
- status := strings.ToLower((*msr.Status)[i])
+ status := strings.ToLower(msr.Status[i])
marketStatus := MarketStatusReport{
Date: time.Unix(date, 0),
Open: status == "open",
@@ -75,11 +89,16 @@ func (msr *MarketStatusResponse) Unpack() ([]MarketStatusReport, error) {
return marketStatuses, nil
}
-// GetOpenDates returns a slice of dates when the market was open.
+// GetOpenDates identifies and returns all dates when the market was reported as open. This method is particularly useful for analyzing market activity over a period, allowing users to focus on days when trading was possible.
+
+// # Returns
//
-// Returns:
-// - []time.Time: A slice of time.Time representing the dates when the market was open.
-// - error: An error if there's an issue unpacking the MarketStatusResponse.
+// - []time.Time: A slice of time.Time objects, each representing a date when the market was open.
+// - error: An error object indicating issues encountered while unpacking the MarketStatusResponse.
+//
+// # Notes
+//
+// - This method relies on the Unpack function to interpret the MarketStatusResponse. Any errors in unpacking will be propagated.
func (msr *MarketStatusResponse) GetOpenDates() ([]time.Time, error) {
marketStatuses, err := msr.Unpack()
if err != nil {
@@ -96,11 +115,16 @@ func (msr *MarketStatusResponse) GetOpenDates() ([]time.Time, error) {
return openDates, nil
}
-// GetClosedDates returns a slice of dates when the market was closed.
+// GetClosedDates identifies and returns all dates when the market was reported as closed. This method is useful for analyzing market activity over a period, allowing users to focus on days when trading was not possible.
//
-// Returns:
-// - []time.Time: A slice of time.Time representing the dates when the market was closed.
-// - error: An error if there's an issue unpacking the MarketStatusResponse.
+// # Returns
+//
+// - []time.Time: A slice of time.Time objects, each representing a date when the market was closed.
+// - error: An error object indicating issues encountered while unpacking the MarketStatusResponse.
+//
+// # Notes
+//
+// - This method relies on the Unpack function to interpret the MarketStatusResponse. Any errors in unpacking will be propagated.
func (msr *MarketStatusResponse) GetClosedDates() ([]time.Time, error) {
marketStatuses, err := msr.Unpack()
if err != nil {
@@ -117,11 +141,19 @@ func (msr *MarketStatusResponse) GetClosedDates() ([]time.Time, error) {
return closedDates, nil
}
-// GetDateRange returns the date range of the MarketStatusResponse.
+// GetDateRange calculates and returns the date range covered by the MarketStatusResponse. This method is primarily used
+// when a user needs to determine the span of dates over which market status data is available, allowing for analysis
+// of market trends within a specific timeframe.
//
-// Returns:
-// - *dates.DateRange: A pointer to a DateRange object representing the earliest and latest dates in the MarketStatusResponse.
-// - error: An error if there's an issue finding the earliest or latest date.
+// # Returns
+//
+// - *dates.DateRange: A pointer to a DateRange object encapsulating the earliest and latest dates found in the MarketStatusResponse.
+// - error: An error object if there's an issue identifying the earliest or latest date within the MarketStatusResponse.
+//
+// # Notes
+//
+// - This method relies on the dates.Earliest and dates.Latest functions to compute the date range. Any errors encountered
+// by these functions will be returned to the caller.
func (msr *MarketStatusResponse) GetDateRange() (*dates.DateRange, error) {
// Use the Earliest and Latest functions to find the earliest and latest dates
earliest, err := dates.Earliest(msr.Date)
@@ -143,9 +175,30 @@ func (msr *MarketStatusResponse) GetDateRange() (*dates.DateRange, error) {
return dr, nil
}
-// MarketStatusReport represents the status of a market.
+// MarketStatusReport encapsulates the operational status of a market on a specific date.
+//
+// # Generated By
+//
+// - MarketStatusResponse.Unpack(): Generates a slice of []MarketStatusReport instances from a MarketStatusResponse.
+//
+// # Methods
+//
+// - String() string: Provides a string representation of the MarketStatusReport.
+//
+// # Notes
+//
+// - This struct is used to convey whether a market is open or closed on a particular date.
+// - The 'Open' and 'Closed' fields are mutually exclusive.
type MarketStatusReport struct {
Date time.Time `json:"date"`
Open bool `json:"open"`
Closed bool `json:"closed"`
}
+
+// String returns a string representation of the MarketStatusReport.
+//
+// Returns:
+// - string: A string representation of the MarketStatusReport.
+func (ms MarketStatusReport) String() string {
+ return fmt.Sprintf("MarketStatusReport{Date: %v, Open: %v, Closed: %v}", dates.TimeString(ms.Date), ms.Open, ms.Closed)
+}
diff --git a/models/models.go b/models/models.go
index 52e8d8a..43c6cc8 100644
--- a/models/models.go
+++ b/models/models.go
@@ -4,50 +4,3 @@
// way to interact with market data. The package also includes methods for unpacking these responses
// into more usable Go data types, such as converting timestamps to time.Time objects.
package models
-
-import (
- "time"
-
- "github.com/MarketDataApp/sdk-go/helpers/dates"
-)
-
-// PreferredTimezone represents the preferred timezone for time display.
-var PreferredTimezone = "America/New_York"
-
-// defaultTimezone is a fallback timezone used when the preferred timezone is not available.
-var defaultTimezone *time.Location
-
-// TimeFormat specifies the format for displaying full datetime information.
-var TimeFormat = "2006-01-02 15:04:05 Z07:00"
-
-// DateFormat specifies the format for displaying date-only information.
-var DateFormat = "2006-01-02"
-
-func init() {
- // Initialize defaultTimezone to UTC as a fallback
- defaultTimezone = time.UTC
-
- // Attempt to load the preferred timezone
- if loc, err := time.LoadLocation(PreferredTimezone); err == nil {
- defaultTimezone = loc // Use preferred timezone if available
- }
-}
-
-// formatTime formats a given time.Time object into a string representation based on a pre-defined timezone and format.
-//
-// Parameters:
-// - t: The time.Time object to be formatted.
-//
-// Returns:
-// - A string representing the formatted time in the pre-defined timezone and format, or 'nil' if the time is a zero value.
-func formatTime(t time.Time) string {
- if t.IsZero() {
- return "nil"
- }
- tInLoc := t.In(defaultTimezone)
- // Use IsStartOfDay from helpers/dates to check if the time is at the start of the day
- if dates.IsStartOfDay(tInLoc, defaultTimezone) {
- return tInLoc.Format(DateFormat)
- }
- return tInLoc.Format(TimeFormat)
-}
diff --git a/models/options_expirations.go b/models/options_expirations.go
index b26d7ec..cfd2e05 100644
--- a/models/options_expirations.go
+++ b/models/options_expirations.go
@@ -7,20 +7,35 @@ import (
"github.com/MarketDataApp/sdk-go/helpers/dates"
)
-// OptionsExpirationsResponse represents the response structure for options expirations.
-// It includes a slice of expiration dates as strings and a timestamp for when the data was last updated.
+// OptionsExpirationsResponse encapsulates the expiration dates of options and the last update timestamp.
+//
+// # Generated By
+//
+// - OptionsExpirationsRequest.Packed(): Generates an OptionsExpirationsResponse after fetching data from Market Data.
+//
+// # Methods
+//
+// - IsValid() bool: Checks if the expiration dates are valid and correctly formatted.
+// - String() string: Returns a string representation of the OptionsExpirationsResponse.
+// - Unpack() ([]time.Time, error): Converts expiration date strings to a slice of time.Time objects.
+//
+// # Notes
+//
+// - The Expirations field contains dates in string format which should be parsed considering the "America/New_York" timezone.
type OptionsExpirationsResponse struct {
Expirations []string // Expirations is a slice of strings representing the expiration dates of options.
Updated int64 // Updated is a UNIX timestamp indicating when the data was last updated.
}
-// IsValid checks the validity of the options expirations response.
+// IsValid checks the validity of the OptionsExpirationsResponse. This method is primarily used to ensure that the Expirations slice is not empty and that each expiration date string within it can be successfully parsed into a time.Time object according to the "America/New_York" timezone. This validation is crucial for preventing errors in subsequent operations that rely on the integrity of the expiration dates data.
+//
+// # Returns
+//
+// - bool: Indicates whether the OptionsExpirationsResponse is valid. A return value of true means all expiration dates are correctly formatted and the Expirations slice is not empty.
//
-// It verifies that the Expirations slice is not empty and that each expiration date string can be parsed into a time.Time object.
-// This parsing is done according to the "America/New_York" timezone.
+// # Notes
//
-// Returns:
-// - A boolean indicating whether the OptionsExpirationsResponse is valid.
+// - The parsing of expiration date strings is sensitive to the timezone specified. Incorrect timezone handling may lead to validation errors.
func (oer *OptionsExpirationsResponse) IsValid() bool {
loc, _ := time.LoadLocation("America/New_York")
if len(oer.Expirations) == 0 {
@@ -35,24 +50,25 @@ func (oer *OptionsExpirationsResponse) IsValid() bool {
return true
}
-// String provides a string representation of the OptionsExpirationsResponse.
+// String returns a string representation of the OptionsExpirationsResponse. This method is primarily used for logging or debugging purposes, where a human-readable format of the OptionsExpirationsResponse is required. It formats the expirations and the updated timestamp into a readable string.
//
-// It formats the expirations and the updated timestamp into a readable string.
+// # Returns
//
-// Returns:
-// - A string that represents the OptionsExpirationsResponse object.
+// - string: A string that represents the OptionsExpirationsResponse object.
func (oer *OptionsExpirationsResponse) String() string {
return fmt.Sprintf("OptionsExpirationsResponse{Expirations: %v, Updated: %d}", oer.Expirations, oer.Updated)
}
-// Unpack converts the expiration date strings in the OptionsExpirationsResponse to a slice of time.Time objects.
+// Unpack converts the expiration date strings in the OptionsExpirationsResponse to a slice of time.Time objects, adjusting each to 4:00 PM Eastern Time, the typical expiration time for options contracts. This method is essential for users who need to work with the actual expiration times of options rather than just the dates.
+//
+// # Returns
+//
+// - []time.Time: A slice of time.Time objects representing the expiration dates and times.
+// - error: An error if any date string cannot be parsed or if the "America/New_York" timezone cannot be loaded.
//
-// It parses each date string in the Expirations slice into a time.Time object, adjusting the time to 4:00 PM Eastern Time,
-// which is the typical expiration time for options contracts.
+// # Notes
//
-// Returns:
-// - A slice of time.Time objects representing the expiration dates and times.
-// - An error if any date string cannot be parsed or if the "America/New_York" timezone cannot be loaded.
+// - This method assumes that all expiration times are at 4:00 PM Eastern Time, which may not be accurate for all options contracts.
func (oer *OptionsExpirationsResponse) Unpack() ([]time.Time, error) {
expirations := make([]time.Time, len(oer.Expirations))
loc, err := time.LoadLocation("America/New_York")
diff --git a/models/options_lookup.go b/models/options_lookup.go
index ac7c542..d7a5f40 100644
--- a/models/options_lookup.go
+++ b/models/options_lookup.go
@@ -4,33 +4,55 @@ import (
"fmt"
)
-// OptionLookupResponse represents the response structure for an option lookup request.
-// It contains the symbol of the option being looked up.
+// OptionLookupResponse encapsulates the response data for an option lookup request, primarily containing the option's symbol.
+//
+// # Generated By
+//
+// - OptionLookupRequest.Packed(): Unmarshals the JSON response from OptionLookupRequest into OptionLookupResponse.
+//
+// # Methods
+//
+// - IsValid() bool: Checks if the OptionLookupResponse is valid by verifying the OptionSymbol is not empty.
+// - String() string: Provides a string representation of the OptionLookupResponse, including the OptionSymbol.
+// - Unpack() (string, error): Validates the OptionLookupResponse and returns the OptionSymbol if valid; otherwise, returns an error.
+//
+// # Notes
+//
+// - This struct is primarily used for handling the response of an options lookup request in financial market data applications.
type OptionLookupResponse struct {
OptionSymbol string `json:"optionSymbol"` // OptionSymbol is the symbol of the option.
}
-// IsValid checks if the OptionLookupResponse is valid.
+// IsValid determines the validity of the OptionLookupResponse. It is primarily used to ensure that the response received from an option lookup request contains a non-empty OptionSymbol, indicating a successful lookup and a valid option.
+//
+// # Returns
//
-// Returns:
-// - bool: True if the OptionLookupResponse has a non-empty OptionSymbol, otherwise false.
+// - bool: Indicates the validity of the OptionLookupResponse. Returns true if the OptionSymbol is not empty, otherwise false.
func (olr *OptionLookupResponse) IsValid() bool {
return olr.OptionSymbol != ""
}
-// String returns a string representation of the OptionLookupResponse.
-//
-// Returns:
-// - string: A string that represents the OptionLookupResponse, including the OptionSymbol.
+// String provides a human-readable representation of the OptionLookupResponse, including the OptionSymbol. This method is useful for logging, debugging, or displaying the response in a format that is easy to read and understand.
+
+// # Returns
+// - string: A formatted string that encapsulates the OptionLookupResponse details, particularly the OptionSymbol.
+
+// # Notes
+// - This method is primarily intended for debugging purposes or when there's a need to log the response details in a human-readable format.
func (olr *OptionLookupResponse) String() string {
return fmt.Sprintf("OptionLookupResponse{OptionSymbol: %q}", olr.OptionSymbol)
}
-// Unpack validates the OptionLookupResponse and returns the OptionSymbol if valid.
+// Unpack checks the validity of the OptionLookupResponse and returns the OptionSymbol if the response is deemed valid. This method is primarily used when one needs to extract the OptionSymbol from a valid OptionLookupResponse, ensuring that the response is not empty or malformed before proceeding with further processing.
+//
+// # Returns
+//
+// - string: The OptionSymbol contained within a valid OptionLookupResponse.
+// - error: An error indicating that the OptionLookupResponse is invalid, typically due to an empty OptionSymbol.
+//
+// # Notes
//
-// Returns:
-// - string: The OptionSymbol of the OptionLookupResponse if it is valid.
-// - error: An error if the OptionLookupResponse is invalid.
+// - This method is crucial for error handling and data validation in financial market data applications, ensuring that only valid responses are processed.
func (olr *OptionLookupResponse) Unpack() (string, error) {
if !olr.IsValid() {
return "", fmt.Errorf("invalid OptionLookupResponse")
diff --git a/models/options_quotes.go b/models/options_quotes.go
index 552cfe5..c082612 100644
--- a/models/options_quotes.go
+++ b/models/options_quotes.go
@@ -3,6 +3,8 @@ package models
import (
"fmt"
"time"
+
+ "github.com/MarketDataApp/sdk-go/helpers/dates"
)
/* Example Response:
@@ -70,6 +72,15 @@ type OptionQuote struct {
ExtrinsicValue float64 // ExtrinsicValue is the value of the option above its intrinsic value.
}
+// Formats the implied volatility (IV) of an option into a string. This method is primarily used for displaying the IV in a human-readable format, which is useful for logging, debugging, or displaying the IV value in user interfaces.
+//
+// # Returns
+//
+// - string: The formatted IV value as a string. If the IV is nil, returns "nil".
+//
+// # Notes
+//
+// - The IV is formatted to a floating-point number as a string. If the IV is not set (nil), the method returns the string "nil".
func (oq OptionQuote) DisplayIV() string {
if oq.IV != nil {
return fmt.Sprintf("%f", *oq.IV)
@@ -77,6 +88,24 @@ func (oq OptionQuote) DisplayIV() string {
return "nil"
}
+// Formats the mid price of an option into a string. This method is primarily used for displaying the mid price in a human-readable format, which is useful for logging, debugging, or displaying the mid price value in user interfaces.
+//
+// # Returns
+//
+// - string: The formatted mid price value as a string.
+//
+// # Notes
+//
+// - The mid price is calculated as the average of the bid and ask prices. This method formats the mid price to a floating-point number as a string.
+func (oq OptionQuote) DisplayMid() string {
+ return fmt.Sprintf("%f", oq.Mid)
+}
+
+// DisplayDelta formats the Delta value of an OptionQuote into a string. Delta measures the rate of change of the option's price with respect to the underlying asset's price. This method is useful for displaying Delta in a human-readable format, especially in user interfaces or logs.
+//
+// # Returns
+//
+// - string: The formatted Delta value as a string. If Delta is nil, returns "nil".
func (oq OptionQuote) DisplayDelta() string {
if oq.Delta != nil {
return fmt.Sprintf("%f", *oq.Delta)
@@ -84,6 +113,11 @@ func (oq OptionQuote) DisplayDelta() string {
return "nil"
}
+// DisplayGamma formats the Gamma value of an OptionQuote into a string. Gamma measures the rate of change in Delta over the underlying asset's price movement. This method is useful for displaying Gamma in a human-readable format, particularly in user interfaces or logs.
+//
+// # Returns
+//
+// - string: The formatted Gamma value as a string. If Gamma is nil, returns "nil".
func (oq OptionQuote) DisplayGamma() string {
if oq.Gamma != nil {
return fmt.Sprintf("%f", *oq.Gamma)
@@ -91,6 +125,11 @@ func (oq OptionQuote) DisplayGamma() string {
return "nil"
}
+// DisplayTheta formats the Theta value of an OptionQuote into a string. Theta represents the rate of decline in the option's value with time. This method is useful for displaying Theta in a human-readable format, especially in user interfaces or logs.
+//
+// # Returns
+//
+// - string: The formatted Theta value as a string. If Theta is nil, returns "nil".
func (oq OptionQuote) DisplayTheta() string {
if oq.Theta != nil {
return fmt.Sprintf("%f", *oq.Theta)
@@ -98,6 +137,11 @@ func (oq OptionQuote) DisplayTheta() string {
return "nil"
}
+// DisplayVega formats the Vega value of an OptionQuote into a string. Vega measures sensitivity to volatility. This method is useful for displaying Vega in a human-readable format, particularly in user interfaces or logs.
+//
+// # Returns
+//
+// - string: The formatted Vega value as a string. If Vega is nil, returns "nil".
func (oq OptionQuote) DisplayVega() string {
if oq.Vega != nil {
return fmt.Sprintf("%f", *oq.Vega)
@@ -105,6 +149,11 @@ func (oq OptionQuote) DisplayVega() string {
return "nil"
}
+// DisplayRho formats the Rho value of an OptionQuote into a string. Rho measures sensitivity to the interest rate. This method is useful for displaying Rho in a human-readable format, especially in user interfaces or logs.
+//
+// # Returns
+//
+// - string: The formatted Rho value as a string. If Rho is nil, returns "nil".
func (oq OptionQuote) DisplayRho() string {
if oq.Rho != nil {
return fmt.Sprintf("%f", *oq.Rho)
@@ -112,22 +161,29 @@ func (oq OptionQuote) DisplayRho() string {
return "nil"
}
-// String returns a formatted string representation of an OptionQuote.
+// String provides a human-readable representation of an OptionQuote, encapsulating its key details in a formatted string. This method is primarily used for logging, debugging, or displaying the OptionQuote in a format that is easy to read and understand. It includes information such as the option symbol, underlying asset, expiration date, and more, formatted into a single string.
+//
+// # Returns
//
-// Parameters:
-// - oq: The OptionQuote instance.
+// - string: A formatted string that encapsulates the OptionQuote details, making it easier to read and understand.
//
-// Returns:
-// - A string that represents the OptionQuote in a human-readable format.
+// # Notes
+//
+// - This method is particularly useful for debugging purposes or when there's a need to log the OptionQuote details in a human-readable format.
func (oq OptionQuote) String() string {
return fmt.Sprintf("OptionQuote{OptionSymbol: %q, Underlying: %q, Expiration: %v, Side: %q, Strike: %v, FirstTraded: %v, DTE: %v, Ask: %v, AskSize: %v, Bid: %v, BidSize: %v, Mid: %v, Last: %v, Volume: %v, OpenInterest: %v, UnderlyingPrice: %v, InTheMoney: %v, Updated: %q, IV: %s, Delta: %s, Gamma: %s, Theta: %s, Vega: %s, Rho: %s, IntrinsicValue: %v, ExtrinsicValue: %v}",
- oq.OptionSymbol, oq.Underlying, formatTime(oq.Expiration), oq.Side, oq.Strike, formatTime(oq.FirstTraded), oq.DTE, oq.Ask, oq.AskSize, oq.Bid, oq.BidSize, oq.Mid, oq.Last, oq.Volume, oq.OpenInterest, oq.UnderlyingPrice, oq.InTheMoney, formatTime(oq.Updated), oq.DisplayIV(), oq.DisplayDelta(), oq.DisplayGamma(), oq.DisplayTheta(), oq.DisplayVega(), oq.DisplayRho(), oq.IntrinsicValue, oq.ExtrinsicValue)
+ oq.OptionSymbol, oq.Underlying, dates.TimeString(oq.Expiration), oq.Side, oq.Strike, dates.TimeString(oq.FirstTraded), oq.DTE, oq.Ask, oq.AskSize, oq.Bid, oq.BidSize, oq.Mid, oq.Last, oq.Volume, oq.OpenInterest, oq.UnderlyingPrice, oq.InTheMoney, dates.TimeString(oq.Updated), oq.DisplayIV(), oq.DisplayDelta(), oq.DisplayGamma(), oq.DisplayTheta(), oq.DisplayVega(), oq.DisplayRho(), oq.IntrinsicValue, oq.ExtrinsicValue)
}
-// IsValid checks if an OptionQuotesResponse is valid by utilizing the Validate method.
+// IsValid determines the validity of an OptionQuotesResponse by invoking the Validate method. This method is primarily used to ensure that the OptionQuotesResponse adheres to expected formats and contains all necessary data before proceeding with further processing or operations.
+//
+// # Returns
//
-// Returns:
-// - A boolean indicating if the OptionQuotesResponse is valid.
+// - bool: Indicates whether the OptionQuotesResponse is valid.
+//
+// # Notes
+//
+// - This method relies on the Validate method to check for inconsistencies or missing data in the OptionQuotesResponse.
func (oqr *OptionQuotesResponse) IsValid() bool {
if err := oqr.Validate(); err != nil {
return false
@@ -135,10 +191,15 @@ func (oqr *OptionQuotesResponse) IsValid() bool {
return true
}
-// Validate checks the consistency of the OptionQuotesResponse struct.
+// Validate ensures the integrity of the OptionQuotesResponse by verifying the consistency of data lengths across its fields. This method is crucial for maintaining data integrity, especially before performing operations that rely on the uniformity of data structure. It checks for the presence of option symbols and validates that the lengths of all slices are consistent with the expected length or are zero for optional fields.
+
+// # Returns
+//
+// - error: An error if there is an inconsistency in the lengths of slices or if there are no option symbols. Returns nil if all checks pass.
//
-// Returns:
-// - An error if there is an inconsistency in the lengths of slices or if there are no option symbols.
+// # Notes
+//
+// - This method is particularly important for preventing runtime errors that could occur when processing inconsistent data.
func (oqr *OptionQuotesResponse) Validate() error {
if len(oqr.OptionSymbol) == 0 {
return fmt.Errorf("no option symbols found in the response")
@@ -186,14 +247,20 @@ func (oqr *OptionQuotesResponse) Validate() error {
return nil
}
-// Unpack converts the OptionQuotesResponse into a slice of OptionQuote structs.
+// Unpack converts the OptionQuotesResponse into a slice of OptionQuote structs, allowing for the individual option quotes contained within the response to be accessed and manipulated more easily. This method is primarily used when there's a need to work with the data of each option quote separately after fetching a bulk response.
+//
+// # Parameters
+//
+// - *OptionQuotesResponse oqr: A pointer to the OptionQuotesResponse instance to be unpacked.
+//
+// # Returns
+//
+// - []OptionQuote: A slice of OptionQuote structs that represent the unpacked data.
+// - *error: An error if the time zone loading fails or if the validation fails.
//
-// Parameters:
-// - oqr: A pointer to the OptionQuotesResponse instance to be unpacked.
+// # Notes
//
-// Returns:
-// - A slice of OptionQuote structs that represent the unpacked data.
-// - An error if the time zone loading fails or if the validation fails.
+// - This method first validates the OptionQuotesResponse to ensure consistency before attempting to unpack it.
func (oqr *OptionQuotesResponse) Unpack() ([]OptionQuote, error) {
// Validate the OptionQuotesResponse before unpacking.
if err := oqr.Validate(); err != nil {
@@ -240,13 +307,19 @@ func (oqr *OptionQuotesResponse) Unpack() ([]OptionQuote, error) {
return optionQuotes, nil
}
-// String returns a formatted string representation of all OptionQuotes contained in the OptionQuotesResponse.
+// String generates a formatted string representation of all OptionQuotes contained within the OptionQuotesResponse. This method is primarily used for producing a human-readable summary of the OptionQuotes, which can be useful for logging, debugging, or displaying the data in a more accessible format.
+//
+// # Parameters
+//
+// - oqr *OptionQuotesResponse: A pointer to the OptionQuotesResponse instance.
+//
+// # Returns
+//
+// - string: A string that represents all OptionQuotes in a human-readable format.
//
-// Parameters:
-// - oqr: A pointer to the OptionQuotesResponse instance.
+// # Notes
//
-// Returns:
-// - A string that represents all OptionQuotes in a human-readable format.
+// - This method simplifies the visualization of complex OptionQuotes data by converting it into a string format.
func (oqr *OptionQuotesResponse) String() string {
// Convert slices of pointers to strings using the helper function.
ivStr := formatFloat64Slice(oqr.IV)
diff --git a/models/options_strikes.go b/models/options_strikes.go
index 1f68099..36eb816 100644
--- a/models/options_strikes.go
+++ b/models/options_strikes.go
@@ -7,6 +7,7 @@ import (
"strings"
"time"
+ "github.com/MarketDataApp/sdk-go/helpers/dates"
"github.com/iancoleman/orderedmap"
)
@@ -24,13 +25,42 @@ Example API Response JSON:
*/
-// OptionsStrikes represents the expiration date and strike prices for an option.
+// OptionsStrikes encapsulates the expiration date and available strike prices for an option contract.
+//
+// # Generated By
+//
+// - OptionsStrikesResponse.Unpack(): Converts an ordered map of strikes into a slice of OptionsStrikes.
+//
+// # Methods
+//
+// - String() string: Returns a string representation of the OptionsStrikes, detailing its expiration and formatted strike prices.
+//
+// # Notes
+//
+// - This struct is primarily used to represent the structured data of option strikes and their expiration dates after unpacking from a JSON response.
type OptionsStrikes struct {
Expiration time.Time // Expiration is the date and time when the option expires.
Strikes []float64 // Strikes is a slice of strike prices available for the option.
}
-// OptionsStrikesResponse encapsulates the response structure for a request to retrieve option strikes.
+// OptionsStrikesResponse encapsulates the response structure for a request to retrieve option strikes, including the last update timestamp and a map of strikes organized by expiration date. The map uses ordered keys to maintain the chronological order of expiration dates.
+//
+// # Generated By
+//
+// - OptionsStrikesRequest.Packed(): Makes the OptionsStrikesRequest and unmarshals JSON data into the OptionsStrikesResponse struct.
+//
+// # Methods
+//
+// - UnmarshalJSON(data []byte) error: Custom unmarshals JSON data, initializing the Strikes map with ordered expiration dates and their corresponding strike prices.
+// - IsValid() bool: Checks if the OptionsStrikesResponse contains valid data.
+// - Validate() error: Validates the integrity of the OptionsStrikesResponse, ensuring it contains valid strikes data.
+// - String() string: Returns a string representation of the OptionsStrikesResponse, detailing strikes and their prices.
+// - Unpack() ([]OptionsStrikes, error): Converts the ordered map of strikes into a slice of OptionsStrikes, each representing a set of strikes and their corresponding expiration date.
+//
+// # Notes
+//
+// - The Strikes field is represented as an ordered map to maintain the order of dates, which is crucial.
+// - The Updated field uses a UNIX timestamp to indicate the last time the data was updated.
type OptionsStrikesResponse struct {
Updated int `json:"updated"` // Updated is a UNIX timestamp indicating when the data was last updated.
Strikes *orderedmap.OrderedMap `json:"-"` // Strikes is a map where each key is a date string and the value is a slice of strike prices for that date.
@@ -38,13 +68,13 @@ type OptionsStrikesResponse struct {
// UnmarshalJSON custom unmarshals the JSON data into the OptionsStrikesResponse struct.
//
-// Parameters:
+// # Parameters
+//
// - data []byte: The JSON data to be unmarshaled.
//
-// Returns:
-// - error: An error if unmarshaling fails, nil otherwise.
+// # Returns
//
-// UnmarshalJSON custom unmarshals the JSON data into the OptionsStrikesResponse struct.
+// - error: An error if unmarshaling fails, nil otherwise.
func (osr *OptionsStrikesResponse) UnmarshalJSON(data []byte) error {
var aux map[string]interface{}
if err := json.Unmarshal(data, &aux); err != nil {
@@ -90,10 +120,15 @@ func (osr *OptionsStrikesResponse) UnmarshalJSON(data []byte) error {
return nil
}
-// String returns a string representation of the OptionsStrikes struct.
+// String provides a human-readable representation of the OptionsStrikes struct, including its expiration and strike prices. This method is primarily used for logging, debugging, or displaying the OptionsStrikes in a format that is easy to read and understand.
//
-// Returns:
-// - string: The string representation of the OptionsStrikes.
+// # Returns
+//
+// - string: A formatted string encapsulating the details of the OptionsStrikes, particularly its expiration and formatted strike prices.
+//
+// # Notes
+//
+// - This method formats strike prices to two decimal places and joins them with a space for readability.
func (os OptionsStrikes) String() string {
// Convert each strike price to a string with two decimal places
var strikesStrParts []string
@@ -103,21 +138,31 @@ func (os OptionsStrikes) String() string {
// Join the formatted strike prices with a space
strikesStr := strings.Join(strikesStrParts, " ")
- return fmt.Sprintf("OptionsStrikes{Expiration: %s, Strikes: [%s]}", formatTime(os.Expiration), strikesStr)
+ return fmt.Sprintf("OptionsStrikes{Expiration: %s, Strikes: [%s]}", dates.TimeString(os.Expiration), strikesStr)
}
-// IsValid checks if the OptionsStrikesResponse is valid by leveraging the Validate method.
+// IsValid determines the validity of the OptionsStrikesResponse object by invoking the Validate method. This method is primarily used to quickly assess whether the response received from an options strikes request adheres to the expected structure and contains valid data. It simplifies error handling by providing a boolean indicator of validity, which can be particularly useful in conditional logic where a binary valid/invalid decision is required.
+//
+// # Returns
//
-// Returns:
-// - bool: True if the response is valid, false otherwise.
+// - bool: Indicates whether the OptionsStrikesResponse is valid. A return value of true signifies a valid response, while false indicates an invalid response.
+//
+// # Notes
+//
+// - This method is a convenience wrapper around the Validate method, offering a simplified interface for validity checking.
func (osr *OptionsStrikesResponse) IsValid() bool {
return osr.Validate() == nil
}
-// Validate checks if the OptionsStrikesResponse is valid.
+// Validate assesses the integrity of the OptionsStrikesResponse object. It is primarily used to ensure that the response received from an options strikes request contains valid and expected data, such as non-empty strikes data. This method is crucial for error handling and data validation in financial market data applications, preventing the further processing of invalid responses.
+//
+// # Returns
+//
+// - error: An error indicating that the OptionsStrikesResponse is invalid, typically due to missing strikes data, or nil if the response is valid.
//
-// Returns:
-// - error: An error if the response is not valid, nil otherwise.
+// # Notes
+//
+// - This method is a fundamental part of the data validation process, ensuring that only responses with valid strikes data are processed.
func (osr *OptionsStrikesResponse) Validate() error {
if len(osr.Strikes.Keys()) == 0 {
return fmt.Errorf("invalid OptionsStrikesResponse: no strikes data")
@@ -125,10 +170,15 @@ func (osr *OptionsStrikesResponse) Validate() error {
return nil
}
-// String returns a string representation of the OptionsStrikesResponse struct.
+// String returns a string representation of the OptionsStrikesResponse struct, encapsulating the details of strikes and their corresponding prices in a human-readable format. This method is primarily used for logging, debugging, or any scenario where a textual representation of the OptionsStrikesResponse data is necessary for understanding or analysis.
+//
+// # Returns
+//
+// - string: The string representation of the OptionsStrikesResponse, detailing the strikes and their prices.
+//
+// # Notes
//
-// Returns:
-// - string: The string representation of the OptionsStrikesResponse.
+// - This method formats the strikes data into a string, making it easier to visualize the structure and content of the OptionsStrikesResponse.
func (osr *OptionsStrikesResponse) String() string {
var sb strings.Builder
sb.WriteString("OptionsStrikesResponse{Strikes: [")
@@ -154,7 +204,16 @@ func (osr *OptionsStrikesResponse) String() string {
return sb.String()
}
-// Unpack converts the ordered map of strikes in the response to a slice of OptionsStrikes.
+// Unpack converts the ordered map of strikes contained within the OptionsStrikesResponse into a slice of OptionsStrikes. This method is primarily used when a user needs to work with a structured list of strikes and their expiration dates, rather than dealing with the map data structure. It simplifies the process of iterating over strikes and performing operations on them.
+//
+// # Returns
+//
+// - []OptionsStrikes: A slice of OptionsStrikes, each representing a set of strikes and their corresponding expiration date.
+// - error: An error if the validation of the OptionsStrikesResponse fails or if there are issues parsing the dates.
+//
+// # Notes
+//
+// - This method first validates the OptionsStrikesResponse to ensure it contains valid data before attempting to unpack the strikes.
func (osr *OptionsStrikesResponse) Unpack() ([]OptionsStrikes, error) {
if err := osr.Validate(); err != nil {
return nil, err
diff --git a/models/stocks_bulkcandles.go b/models/stocks_bulkcandles.go
index e178260..c8c94a3 100644
--- a/models/stocks_bulkcandles.go
+++ b/models/stocks_bulkcandles.go
@@ -5,9 +5,22 @@ import (
"time"
)
-// StockCandlesResponse represents the JSON response structure for stock candles data.
-// It includes slices for time, open, high, low, close prices, and volume for each candle.
-// Optional fields VWAP and N are available for V2 candles.
+// BulkStockCandlesResponse encapsulates the data structure for the response received from the bulk stock candles endpoint.
+// It contains arrays of stock symbols, timestamps, opening, high, low, closing prices, and volumes for each candle.
+//
+// # Generated By
+//
+// - BulkStockCandlesRequest.Packed(): Generates a BulkStockCandlesResponse from a bulk stock candles request.
+//
+// # Methods
+//
+// - Unpack() ([]Candle, error): Converts the BulkStockCandlesResponse into a slice of Candle structs.
+// - String() string: Provides a string representation of the BulkStockCandlesResponse.
+//
+// # Notes
+//
+// - The Date field uses UNIX timestamps to represent the time for each candle.
+// - Ensure the slices within BulkStockCandlesResponse have equal lengths to prevent index out-of-range errors.
type BulkStockCandlesResponse struct {
Symbol []string `json:"symbol" human:"Symbol"` // Symbol holds the stock ticker of the candle.
Date []int64 `json:"t" human:"Date"` // Date holds UNIX timestamps for each candle.
@@ -25,10 +38,12 @@ type BulkStockCandlesResponse struct {
// The method ensures that each Candle struct is populated with the appropriate data, converting the UNIX timestamp to a time.Time object for the Date field.
// It is crucial that the slices within BulkStockCandlesResponse are of equal length to maintain data integrity and avoid index out-of-range errors.
//
-// Parameters:
-// - bscr *BulkStockCandlesResponse: A pointer to the BulkStockCandlesResponse instance containing the bulk stock candles data to be unpacked.
+// # Parameters
+//
+// - *BulkStockCandlesResponse: A pointer to the BulkStockCandlesResponse instance containing the bulk stock candles data to be unpacked.
+//
+// # Returns
//
-// Returns:
// - []Candle: A slice of Candle structs, each representing a single stock candle with data unpacked from the BulkStockCandlesResponse.
// - error: An error object that will be non-nil if the slices within BulkStockCandlesResponse are not of equal length, indicating a failure in the unpacking process.
func (bscr *BulkStockCandlesResponse) Unpack() ([]Candle, error) {
@@ -54,12 +69,9 @@ func (bscr *BulkStockCandlesResponse) Unpack() ([]Candle, error) {
// into a single string. This is particularly useful for logging or debugging purposes, where a quick textual
// representation of the BulkStockCandlesResponse is needed. The Date field is represented as UNIX timestamps.
//
-// Parameters:
-// - There are no parameters for this method as it operates on the BulkStockCandlesResponse instance it is called on.
+// # Returns:
//
-// Returns:
-// - string: A formatted string that contains the Symbol, Date (as UNIX timestamps), Open, High, Low, Close, and Volume
-// fields of the BulkStockCandlesResponse.
+// - string: A formatted string that contains the Symbol, Date (as UNIX timestamps), Open, High, Low, Close, and Volume fields of the BulkStockCandlesResponse.
func (bscr BulkStockCandlesResponse) String() string {
return fmt.Sprintf("BulkStockCandlesResponse{Symbol: %v, Date: %v, Open: %v, High: %v, Low: %v, Close: %v, Volume: %v}", bscr.Symbol, bscr.Date, bscr.Open, bscr.High, bscr.Low, bscr.Close, bscr.Volume)
}
diff --git a/models/stocks_candles.go b/models/stocks_candles.go
index 9f70a25..6ef022b 100644
--- a/models/stocks_candles.go
+++ b/models/stocks_candles.go
@@ -10,9 +10,30 @@ import (
"github.com/iancoleman/orderedmap"
)
-// StockCandlesResponse represents the JSON response structure for stock candles data.
-// It includes slices for time, open, high, low, close prices, and volume for each candle.
-// Optional fields VWAP and N are available for V2 candles.
+// StockCandlesResponse encapsulates the data structure for the JSON response of stock candles data. It includes
+// detailed information about stock prices at different times, such as opening, closing, highest, and lowest prices,
+// along with the trading volume. For version 2 candles, it optionally includes the Volume Weighted Average Price (VWAP)
+// and the number of trades.
+//
+// # Generated By
+//
+// - StockCandlesRequest.Packed(): Sends a StockCandlesRequest and unmarshals the response into StockCandlesResponse.
+//
+// # Methods
+//
+// - Unpack() ([]Candle, error): Converts a StockCandlesResponse into a slice of StockCandle.
+// - String() string: Returns a string representation of the StockCandlesResponse.
+// - IsValid() bool: Checks if a StockCandlesResponse is valid.
+// - Validate() error: Validates a StockCandlesResponse.
+// - MarshalJSON() ([]byte, error): Marshals a StockCandlesResponse into JSON.
+// - UnmarshalJSON(data []byte) error: Unmarshals JSON into a StockCandlesResponse.
+// - GetDateRange() (dates.DateRange, error): Returns the date range of a StockCandlesResponse.
+// - PruneOutsideDateRange(dr dates.DateRange) error: Removes data points outside a specified date range.
+//
+// # Notes
+//
+// - The optional fields VWAP and N are only available for version 2 candles.
+// - The Date field uses UNIX timestamps to represent the date and time of each candle.
type StockCandlesResponse struct {
Date []int64 `json:"t" human:"Date"` // Date holds UNIX timestamps for each candle.
Open []float64 `json:"o" human:"Open"` // Open holds the opening prices for each candle.
@@ -24,11 +45,18 @@ type StockCandlesResponse struct {
N *[]int64 `json:"n,omitempty" human:"No. of Trades,omitempty"` // N holds the number of trades for each candle, optional.
}
-// Unpack converts a StockCandlesResponse into a slice of StockCandle.
+// Unpack converts a StockCandlesResponse into a slice of StockCandle. This method is primarily used to transform the aggregated
+// stock candles data from a structured response format into a more accessible slice of individual candle data. It allows users
+// to iterate over or manipulate the stock candle data more conveniently in their applications.
//
-// Returns:
-// - A slice of StockCandle.
-// - An error if the slices within StockCandlesResponse are not of equal length.
+// # Returns
+//
+// - []Candle: A slice of Candle containing the unpacked data from the StockCandlesResponse.
+// - error: An error if the slices within StockCandlesResponse are not of equal length, indicating inconsistent data.
+//
+// # Notes
+//
+// - This method ensures that all slices within the StockCandlesResponse have the same length before unpacking to prevent data misalignment.
func (scr *StockCandlesResponse) Unpack() ([]Candle, error) {
if err := scr.checkForEqualSlices(); err != nil {
return nil, err
@@ -55,10 +83,15 @@ func (scr *StockCandlesResponse) Unpack() ([]Candle, error) {
return stockCandles, nil
}
-// String returns a string representation of a StockCandlesResponse.
+// String generates a string representation of a StockCandlesResponse. This method is primarily used for logging or debugging purposes, allowing developers to easily view the contents of a StockCandlesResponse in a human-readable format. It dynamically adjusts the output based on the presence of optional fields.
//
-// Returns:
-// - A string representation of the StockCandlesResponse.
+// # Returns
+//
+// - string: A string representation of the StockCandlesResponse.
+//
+// # Notes
+//
+// - The output format may vary depending on the version of the struct and the presence of optional fields.
func (s *StockCandlesResponse) String() string {
// Determine the version of the struct
version, _ := s.getVersion()
@@ -94,10 +127,15 @@ func (s *StockCandlesResponse) checkTimeInAscendingOrder() error {
return nil
}
-// IsValid checks if a StockCandlesResponse is valid.
+// IsValid determines the validity of a StockCandlesResponse. It is primarily used to ensure that the data within the response adheres to expected formats and logical constraints before further processing or analysis.
//
-// Returns:
-// - A boolean indicating if the StockCandlesResponse is valid.
+// # Returns
+//
+// - bool: Indicates whether the StockCandlesResponse is valid.
+//
+// # Notes
+//
+// - This method should be used to prevent the propagation of invalid or corrupt data within applications that rely on stock candle information.
func (s *StockCandlesResponse) IsValid() bool {
if err := s.Validate(); err != nil {
return false
@@ -105,10 +143,15 @@ func (s *StockCandlesResponse) IsValid() bool {
return true
}
-// Validate validates a StockCandlesResponse.
+// Validate checks the integrity and consistency of a StockCandlesResponse. It ensures that the data within the response adheres to expected formats and logical constraints, such as time being in ascending order and all data slices being of equal length. This method is crucial for preventing the propagation of invalid or corrupt data within an application that relies on stock candle information.
//
-// Returns:
-// - An error if the StockCandlesResponse is not valid.
+// # Returns
+//
+// - error: An error if the StockCandlesResponse is not valid. A nil error indicates a valid StockCandlesResponse.
+//
+// # Notes
+//
+// - This method performs multiple checks in parallel to efficiently validate the response.
func (s *StockCandlesResponse) Validate() error {
// Create a channel to handle errors
errChan := make(chan error, 4)
@@ -208,11 +251,14 @@ func (s *StockCandlesResponse) getVersion() (int, error) {
}
}
-// MarshalJSON marshals a StockCandlesResponse into JSON.
+// MarshalJSON converts a StockCandlesResponse instance into its JSON representation.
+// This method is primarily used for encoding the StockCandlesResponse into a JSON format that can be easily transmitted or stored.
+// It organizes the stock candle data into a structured JSON format, ensuring compatibility with systems that consume JSON.
//
-// Returns:
-// - A byte slice of the JSON representation.
-// - An error if marshaling fails.
+// # Returns
+//
+// - []byte: The JSON-encoded representation of the StockCandlesResponse.
+// - error: An error object that will be non-nil if the marshaling process encounters any issues.
func (s *StockCandlesResponse) MarshalJSON() ([]byte, error) {
// Create a new ordered map
o := orderedmap.New()
@@ -242,10 +288,19 @@ func (s *StockCandlesResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(o)
}
-// UnmarshalJSON unmarshals JSON into a StockCandlesResponse.
+// UnmarshalJSON converts JSON data into a StockCandlesResponse instance. This method is essential for decoding JSON data received from external sources into a structured StockCandlesResponse object. It facilitates the easy consumption of JSON data by converting it into a more manageable Go struct. Additionally, it performs validation on the unmarshalled data to ensure it meets the expected format and constraints of a StockCandlesResponse.
//
-// Returns:
-// - An error if unmarshaling or validation fails.
+// # Parameters
+//
+// - []byte: The JSON-encoded data that needs to be converted into a StockCandlesResponse.
+//
+// # Returns
+//
+// - error: An error object that will be non-nil if the unmarshaling process encounters any issues or if the validation of the unmarshalled data fails.
+//
+// # Notes
+//
+// - This method leverages an auxiliary struct to prevent infinite recursion during the unmarshalling process.
func (s *StockCandlesResponse) UnmarshalJSON(data []byte) error {
// Define a secondary type to prevent infinite recursion
type Alias StockCandlesResponse
@@ -271,11 +326,16 @@ func (s *StockCandlesResponse) UnmarshalJSON(data []byte) error {
return nil
}
-// GetDateRange returns the date range of a StockCandlesResponse.
+// GetDateRange calculates and returns the date range covered by the StockCandlesResponse. This method is useful for determining the span of time that the stock candle data encompasses, allowing users to understand the temporal scope of the data they are working with.
//
-// Returns:
-// - A DateRange object.
-// - An error if calculating the date range fails.
+// # Returns
+//
+// - dates.DateRange: The range of dates covered by the StockCandlesResponse.
+// - error: An error if calculating the date range fails.
+//
+// # Notes
+//
+// - This method is particularly useful when filtering data based on specific time frames.
func (s *StockCandlesResponse) GetDateRange() (dates.DateRange, error) {
// Pass the slice of timestamps directly to Earliest and Latest
min, err1 := dates.Earliest(s.Date)
@@ -377,13 +437,21 @@ func (s *StockCandlesResponse) pruneAfterIndex(index int) error {
return nil
}
-// PruneOutsideDateRange removes data points outside a specified date range from a StockCandlesResponse.
+// PruneOutsideDateRange method is used to filter out data points from a StockCandlesResponse that fall outside a specified date range.
+// This method is essential when the user needs to focus on analyzing stock candle data within a specific period,
+// thereby excluding irrelevant data points that do not fall within the desired date range.
//
-// Parameters:
-// - dr: A DateRange struct specifying the start and end dates for the range within which data points should be retained.
+// # Parameters
//
-// Returns:
-// - An error if pruning fails.
+// - dr dates.DateRange: A struct specifying the start and end dates for the range within which data points should be retained.
+//
+// # Returns
+//
+// - error: An error if pruning fails, otherwise nil.
+//
+// # Notes
+//
+// - This method modifies the StockCandlesResponse in place, removing any data points that are outside the specified date range.
func (s *StockCandlesResponse) PruneOutsideDateRange(dr dates.DateRange) error {
// Validate all timestamps
validTimestamps, invalidTimestamps := dr.ValidateTimestamps(s.Date...)
@@ -459,11 +527,13 @@ func (s *StockCandlesResponse) pruneIndex(index int) error {
// and then combines their data into a new StockCandlesResponse struct. If the versions are both V2,
// it also combines the VWAP and N slices. Finally, it validates the combined struct.
//
-// Parameters:
-// - s1 *StockCandlesResponse: The first StockCandlesResponse struct to be combined.
-// - s2 *StockCandlesResponse: The second StockCandlesResponse struct to be combined.
+// # Parameters
+//
+// - *StockCandlesResponse: The first StockCandlesResponse struct to be combined.
+// - *StockCandlesResponse: The second StockCandlesResponse struct to be combined.
+//
+// # Returns
//
-// Returns:
// - *StockCandlesResponse: A pointer to the newly combined StockCandlesResponse struct.
// - error: An error if the versions do not match, there is a time overlap, or the combined struct fails validation.
func CombineStockCandles(s1, s2 *StockCandlesResponse) (*StockCandlesResponse, error) {
diff --git a/models/stocks_earnings.go b/models/stocks_earnings.go
index 0a9a38c..46a1958 100644
--- a/models/stocks_earnings.go
+++ b/models/stocks_earnings.go
@@ -4,16 +4,32 @@ import (
"fmt"
"strings"
"time"
+
+ "github.com/MarketDataApp/sdk-go/helpers/dates"
)
-// StockEarningsResponse represents the response structure for stock earnings data.
-// It includes slices for symbols, fiscal years, fiscal quarters, dates (UNIX timestamp),
-// report dates (UNIX timestamp), report times, currencies, reported EPS (Earnings Per Share),
-// estimated EPS, surprise EPS, surprise EPS percentage, and last updated time (UNIX timestamp).
+// StockEarningsResponse encapsulates the data received as a response to a stock earnings data request.
+// It contains detailed information about stock earnings, including symbols, fiscal years, fiscal quarters,
+// dates, report dates, report times, currencies, reported EPS, estimated EPS, surprise EPS, surprise EPS
+// percentage, and last update times.
+//
+// # Generated By
+//
+// - StockEarningsRequest.Packed(): Generates this struct as a response to a stock earnings request.
+//
+// # Methods
+//
+// - String() string: Returns a string representation of the StockEarningsResponse.
+// - Unpack() ([]StockEarningsReport, error): Converts the response into a slice of StockEarningsReport structs.
+//
+// # Notes
+//
+// - The dates in this struct are represented as UNIX timestamps.
+// - EPS fields may be nil if the data is not available.
type StockEarningsResponse struct {
Symbol []string `json:"symbol"` // Symbol represents the stock symbols.
- FiscalYear []int64 `json:"fiscalYear"` // FiscalYear represents the fiscal years of the earnings report.
- FiscalQuarter []int64 `json:"fiscalQuarter"` // FiscalQuarter represents the fiscal quarters of the earnings report.
+ FiscalYear []int64 `json:"fiscalYear"` // FiscalYear represents the fiscal years of the earnings report.
+ FiscalQuarter []int64 `json:"fiscalQuarter"` // FiscalQuarter represents the fiscal quarters of the earnings report.
Date []int64 `json:"date"` // Date represents the earnings announcement dates in UNIX timestamp.
ReportDate []int64 `json:"reportDate"` // ReportDate represents the report release dates in UNIX timestamp.
ReportTime []string `json:"reportTime"` // ReportTime represents the time of day the earnings were reported.
@@ -25,10 +41,20 @@ type StockEarningsResponse struct {
Updated []int64 `json:"updated"` // Updated represents the last update time in UNIX timestamp.
}
-// StockEarningsReport represents a single earnings report for a stock.
-// It includes the stock symbol, fiscal year, fiscal quarter, date of the earnings,
-// report date, report time, currency of the report, reported EPS, estimated EPS,
-// surprise EPS, surprise EPS percentage, and the last updated time.
+// StockEarningsReport represents a single earnings report for a stock, encapsulating details such as the stock symbol, fiscal year, fiscal quarter, earnings date, report date and time, currency used in the report, reported EPS, estimated EPS, surprise EPS, surprise EPS percentage, and the last update time.
+//
+// # Generated By
+//
+// - Unpack(): Converts a StockEarningsResponse into a slice of StockEarningsReport structs.
+//
+// # Methods
+//
+// - String() string: Returns a string representation of the StockEarningsReport.
+//
+// # Notes
+//
+// - The Date, ReportDate, and Updated fields are represented as time.Time objects, providing a standardized format for date and time.
+// - EPS fields (ReportedEPS, EstimatedEPS, SurpriseEPS, SurpriseEPSpct) are pointers to float64, allowing for nil values to represent missing data.
type StockEarningsReport struct {
Symbol string // Symbol represents the stock symbol.
FiscalYear int64 // FiscalYear represents the fiscal year of the earnings report.
@@ -44,6 +70,16 @@ type StockEarningsReport struct {
Updated time.Time // Updated represents the last update time.
}
+// String returns a string representation of the StockEarningsReport struct. This method is primarily used for logging or debugging purposes, allowing developers to easily view the contents of a StockEarningsReport instance in a human-readable format. The method formats various fields of the struct, including handling nil pointers for EPS values gracefully by displaying them as "nil".
+//
+// # Returns
+//
+// - string: A formatted string that represents the StockEarningsReport instance, including all its fields. Fields that are pointers to float64 (ReportedEPS, EstimatedEPS, SurpriseEPS, SurpriseEPSpct) are displayed as their dereferenced values if not nil, otherwise "nil".
+//
+// # Notes
+//
+// - The Date, ReportDate, and Updated fields are formatted as "YYYY-MM-DD" for consistency and readability.
+// - This method ensures that nil pointer fields do not cause a panic by checking their existence before dereferencing.
func (ser StockEarningsReport) String() string {
reportedEPS := "nil"
if ser.ReportedEPS != nil {
@@ -66,14 +102,15 @@ func (ser StockEarningsReport) String() string {
}
return fmt.Sprintf("StockEarningsReport{Symbol: %q, FiscalYear: %d, FiscalQuarter: %d, Date: %q, ReportDate: %q, ReportTime: %q, Currency: %q, ReportedEPS: %s, EstimatedEPS: %s, SurpriseEPS: %s, SurpriseEPSPct: %s, Updated: %q}",
- ser.Symbol, ser.FiscalYear, ser.FiscalQuarter, ser.Date.Format("2006-01-02"), formatTime(ser.ReportDate), ser.ReportTime, ser.Currency, reportedEPS, estimatedEPS, surpriseEPS, surpriseEPSpct, formatTime(ser.Updated))
+ ser.Symbol, ser.FiscalYear, ser.FiscalQuarter, ser.Date.Format("2006-01-02"), dates.TimeString(ser.ReportDate), ser.ReportTime, ser.Currency, reportedEPS, estimatedEPS, surpriseEPS, surpriseEPSpct, dates.TimeString(ser.Updated))
}
// Unpack converts the StockEarningsResponse struct into a slice of StockEarningsReport structs.
//
// This method iterates over the fields of a StockEarningsResponse struct, creating a StockEarningsReport struct for each symbol present in the response. It then populates the fields of each StockEarningsReport struct with the corresponding data from the StockEarningsResponse struct. The method handles the conversion of Unix timestamps to time.Time objects for the Date, ReportDate, and Updated fields. It also directly assigns pointer fields for ReportedEPS, EstimatedEPS, SurpriseEPS, and SurpriseEPSpct to handle potential nil values gracefully.
//
-// Returns:
+// # Returns
+//
// - []StockEarningsReport: A slice of StockEarningsReport structs constructed from the StockEarningsResponse.
// - error: An error if the unpacking process fails, nil otherwise.
func (ser *StockEarningsResponse) Unpack() ([]StockEarningsReport, error) {
@@ -102,7 +139,8 @@ func (ser *StockEarningsResponse) Unpack() ([]StockEarningsReport, error) {
//
// This method formats the StockEarningsResponse fields into a readable string, including handling nil values for EPS fields and empty values for fiscalYear and fiscalQuarter gracefully by displaying them as "nil" or "empty" respectively.
//
-// Returns:
+// # Returns
+//
// - A string representation of the StockEarningsResponse.
func (ser *StockEarningsResponse) String() string {
var result strings.Builder
diff --git a/models/stocks_news.go b/models/stocks_news.go
index 9470970..0c569f8 100644
--- a/models/stocks_news.go
+++ b/models/stocks_news.go
@@ -4,11 +4,26 @@ import (
"fmt"
"strings"
"time"
+
+ "github.com/MarketDataApp/sdk-go/helpers/dates"
)
-// StockNewsResponse represents the JSON response structure for stock news.
-// It includes slices for symbols, headlines, content, sources, and publication dates,
-// as well as a timestamp for when the data was last updated.
+// StockNewsResponse encapsulates the data structure for a response containing news articles related to stock symbols.
+// It includes arrays for symbols, headlines, content, sources, and publication dates, along with a timestamp for the last update.
+//
+// # Generated By
+//
+// - StockNewsRequest.Packed(): Generates a StockNewsResponse from a request to the /stocks/news endpoint.
+//
+// # Methods
+//
+// - String(): Returns a string representation of the StockNewsResponse.
+// - Unpack(): Transforms the StockNewsResponse into a slice of StockNews structs.
+//
+// # Notes
+//
+// - The PublicationDate field uses UNIX timestamps to represent the publication dates of the news articles.
+// - This struct is primarily used to unpack and process JSON responses from stock news API endpoints.
type StockNewsResponse struct {
Symbol []string `json:"symbol"` // Symbol contains the stock symbols associated with the news.
Headline []string `json:"headline"` // Headline contains the headlines of the news articles.
@@ -18,8 +33,19 @@ type StockNewsResponse struct {
Updated int64 `json:"updated"` // Updated contains the timestamp of the last update to the news data.
}
-// StockNews represents a single news article related to a stock.
-// It includes the stock symbol, headline, content, source, and publication date.
+// StockNews represents a single news article related to a stock, encapsulating details such as the stock symbol, headline, content, source, and publication date.
+//
+// # Generated By
+//
+// - StockNewsResponse.Unpack(): Unpacks the StockNewsResponse into a slice of StockNews.
+//
+// # Methods
+//
+// - String(): Returns a formatted string representation of the StockNews struct.
+//
+// # Notes
+//
+// - The PublicationDate field is of type time.Time, ensuring that the date and time information is accurately represented according to Go's standard time package.
type StockNews struct {
Symbol string // Symbol is the stock symbol associated with the news article.
Headline string // Headline is the headline of the news article.
@@ -28,23 +54,32 @@ type StockNews struct {
PublicationDate time.Time // PublicationDate is the publication date of the news article.
}
-// String returns a formatted string representation of the StockNews struct.
+// String() method formats and returns a string representation of the StockNews struct, making it easier to read and understand the news article's details.
+// It is particularly useful for logging or displaying the article's information in a human-readable format. If the publication date is at the start of the day,
+// it simplifies the date to a YYYY-MM-DD format, omitting time and timezone information for clarity.
+//
+// # Returns
//
-// This method formats the StockNews fields into a readable string. If the publication date is at the start of the day,
-// it prints out the date in YYYY-MM-DD format without any time or timezone info.
+// - string: A formatted string representation of the StockNews struct.
//
-// Returns:
-// - A string representation of the StockNews struct.
+// # Notes
+//
+// - If the publication date is exactly at the start of a day (00:00:00), only the date part (YYYY-MM-DD) is included in the output string.
func (sn StockNews) String() string {
return fmt.Sprintf("StockNews{Symbol: %q, Headline: %q, Content: %q, Source: %q, PublicationDate: %q}",
- sn.Symbol, sn.Headline, sn.Content, sn.Source, formatTime(sn.PublicationDate))
+ sn.Symbol, sn.Headline, sn.Content, sn.Source, dates.TimeString(sn.PublicationDate))
}
-// Unpack transforms the StockNewsResponse struct into a slice of StockNews structs.
+// Unpack transforms the StockNewsResponse struct into a slice of StockNews structs, allowing for easy access and manipulation of individual news articles contained within the response. This method is primarily used when one needs to process or display the news articles represented by a StockNewsResponse in a more granular or article-by-article basis.
+//
+// # Returns
+//
+// - []StockNews: A slice of StockNews structs representing the unpacked news articles.
+// - error: An error if any issues occur during the unpacking process. This implementation always returns nil for error.
+//
+// # Notes
//
-// Returns:
-// - A slice of StockNews structs representing the unpacked news articles.
-// - An error if any issues occur during the unpacking process. This implementation always returns nil for error.
+// - This method assumes that the slices within the StockNewsResponse struct are all of equal length, corresponding to the number of news articles contained in the response.
func (snr *StockNewsResponse) Unpack() ([]StockNews, error) {
var stockNews []StockNews
for i := range snr.Symbol {
@@ -60,14 +95,11 @@ func (snr *StockNewsResponse) Unpack() ([]StockNews, error) {
return stockNews, nil
}
-// String generates a string representation of the StockNewsResponse struct.
+// String generates a string representation of the StockNewsResponse struct, primarily used for logging or debugging purposes. This method iterates over each news article contained within the StockNewsResponse, constructing a formatted string for each article and appending it to a strings.Builder instance. If the 'Updated' field within the struct is non-zero, indicating that the response has been updated, an "Updated" field is also appended to the final string representation. This method is useful for developers who need a quick, readable overview of the news articles contained within a StockNewsResponse, including any updates.
//
-// This method iterates over each news article in the StockNewsResponse, appending a formatted string
-// for each article to a strings.Builder. If the 'Updated' field is non-zero, it appends an "Updated" field
-// at the end of the string.
+// # Returns
//
-// Returns:
-// - A string representation of the StockNewsResponse struct.
+// - string: A comprehensive string representation of the StockNewsResponse struct, including details of each news article and any updates.
func (snr *StockNewsResponse) String() string {
var result strings.Builder
diff --git a/models/stocks_quotes.go b/models/stocks_quotes.go
index 782a50c..6c51bb3 100644
--- a/models/stocks_quotes.go
+++ b/models/stocks_quotes.go
@@ -4,11 +4,25 @@ import (
"fmt"
"strings"
"time"
+
+ "github.com/MarketDataApp/sdk-go/helpers/dates"
)
-// StockQuotesResponse represents the response structure for stock quotes.
-// It includes slices for symbols, ask prices, ask sizes, bid prices, bid sizes, mid prices, last trade prices,
-// changes, change percentages, 52-week highs, 52-week lows, volumes, and update timestamps.
+// StockQuotesResponse encapsulates the data structure for responses received from stock quote requests.
+// It contains arrays for various stock attributes such as symbols, prices, volumes, and timestamps.
+//
+// # Generated By
+//
+// - StockQuoteRequest.Packed(): Makes a StoStockQuoteRequest and returns a StockQuotesResponse.
+//
+// # Methods
+//
+// - String(): Returns a string representation of the StockQuotesResponse.
+// - Unpack(): Transforms the StockQuotesResponse into a slice of StockQuote structs.
+//
+// # Notes
+//
+// - The Change, ChangePct, High52, and Low52 fields are pointers to accommodate nil values, indicating that the data may not be applicable or available for some stocks.
type StockQuotesResponse struct {
Symbol []string `json:"symbol"` // Symbol holds the stock symbols.
Ask []float64 `json:"ask"` // Ask holds the asking prices for the stocks.
@@ -25,9 +39,19 @@ type StockQuotesResponse struct {
Updated []int64 `json:"updated"` // Updated holds the UNIX timestamps for when the quotes were last updated.
}
-// StockQuote represents a single stock quote.
-// It includes the stock symbol, ask price, ask size, bid price, bid size, mid price, last trade price,
-// change, change percentage, 52-week high, 52-week low, volume, and the time of the last update.
+// StockQuote represents a single stock quote, encapsulating various details such as prices, volumes, and timestamps.
+//
+// # Generated By
+//
+// - StockQuotesResponse.Unpack(): Transforms a StockQuotesResponse into a slice of StockQuote structs.
+//
+// # Methods
+//
+// - String(): Generates a string representation of the StockQuote struct.
+//
+// # Notes
+//
+// - The Change, ChangePct, High52, and Low52 fields are pointers to accommodate nil values, indicating that the data may not be applicable or available.
type StockQuote struct {
Symbol string // Symbol is the stock symbol.
Ask float64 // Ask is the asking price for the stock.
@@ -44,14 +68,16 @@ type StockQuote struct {
Updated time.Time // Updated is the time when the quote was last updated.
}
-// String generates a string representation of the StockQuote struct.
+// String generates a string representation of the StockQuote struct, providing a human-readable summary of a stock's details. This method is particularly useful for displaying stock information in a format that is easy to read and understand. It accounts for optional fields by conditionally including High52, Low52, Change, and ChangePct in the output, and formats the updated time to the America/New_York timezone.
+//
+// # Returns
+//
+// - string: A string representation of the StockQuote struct.
//
-// This method formats the fields of a StockQuote into a readable string. It includes conditional formatting
-// based on the presence of optional fields such as High52, Low52, Change, and ChangePct. The updated time
-// is formatted in the America/New_York timezone.
+// # Notes
//
-// Returns:
-// - A string representation of the StockQuote struct.
+// - Optional fields (High52, Low52, Change, and ChangePct) are displayed as "nil" if they are not available, ensuring clarity in the output.
+// - The updated time is converted to the America/New_York timezone for consistency in display.
func (sq StockQuote) String() string {
high52 := "nil"
if sq.High52 != nil {
@@ -70,18 +96,19 @@ func (sq StockQuote) String() string {
changePct = fmt.Sprintf("%v", *sq.ChangePct)
}
return fmt.Sprintf("StockQuote{Symbol: %q, Ask: %v, AskSize: %v, Bid: %v, BidSize: %v, Mid: %v, Last: %v, Volume: %v, Updated: %q, High52: %s, Low52: %s, Change: %s, ChangePct: %s}",
- sq.Symbol, sq.Ask, sq.AskSize, sq.Bid, sq.BidSize, sq.Mid, sq.Last, sq.Volume, formatTime(sq.Updated), high52, low52, change, changePct)
+ sq.Symbol, sq.Ask, sq.AskSize, sq.Bid, sq.BidSize, sq.Mid, sq.Last, sq.Volume, dates.TimeString(sq.Updated), high52, low52, change, changePct)
}
-// Unpack transforms the StockQuotesResponse into a slice of StockQuote structs.
+// Unpack transforms a StockQuotesResponse into a slice of StockQuote structs, effectively unpacking the bulk response into individual stock quotes. This method is primarily used to convert a grouped response of stock quotes into a more accessible format, where each stock quote is represented as a separate struct. It is particularly useful for scenarios where individual stock details need to be accessed or manipulated.
//
-// This method iterates over the fields of a StockQuotesResponse and constructs a slice of StockQuote
-// structs by assigning the corresponding values from the response to each StockQuote. It handles optional
-// fields such as Change, ChangePct, High52, and Low52 by checking for their existence before assignment.
+// # Returns
//
-// Returns:
-// - A slice of StockQuote structs representing the unpacked stock quotes.
-// - An error if any issues occur during the unpacking process (currently, this implementation always returns nil for error).
+// - []StockQuote: A slice of StockQuote structs representing the unpacked stock quotes.
+// - error: An error if any issues occur during the unpacking process. Currently, this implementation always returns nil for error.
+//
+// # Notes
+//
+// - This method handles optional fields such as Change, ChangePct, High52, and Low52 by checking for their existence before assignment, allowing for a flexible unpacking process that accommodates incomplete data.
func (sqr *StockQuotesResponse) Unpack() ([]StockQuote, error) {
var stockQuotes []StockQuote
for i := range sqr.Symbol {
@@ -115,13 +142,15 @@ func (sqr *StockQuotesResponse) Unpack() ([]StockQuote, error) {
return stockQuotes, nil
}
-// String returns a string representation of a StockQuotesResponse.
+// String constructs and returns a string representation of a StockQuotesResponse, encapsulating all relevant details of stock quotes including symbol, ask, bid, mid, last, change, change percentage, 52-week high, 52-week low, volume, and updated time. This method is primarily used for generating a human-readable summary of stock quotes response, which can be useful for logging, debugging, or displaying stock information in a textual format.
+//
+// # Returns
+//
+// - string: A comprehensive, human-readable string representation of the stock quotes response.
//
-// This method constructs a string that includes the symbol, ask, ask size, bid, bid size, mid, last, change (if available),
-// change percentage (if available), 52-week high (if available), 52-week low (if available), volume, and updated time of the stock quotes response.
+// # Notes
//
-// Returns:
-// - A string that represents the stock quotes response.
+// - Optional fields such as change, change percentage, 52-week high, and 52-week low are included in the string only if they are available.
func (sqr *StockQuotesResponse) String() string {
var result strings.Builder
diff --git a/models/stocks_tickers.go b/models/stocks_tickers.go
index 5024753..5b9edd1 100644
--- a/models/stocks_tickers.go
+++ b/models/stocks_tickers.go
@@ -10,12 +10,29 @@ import (
"sync"
"time"
+ "github.com/MarketDataApp/sdk-go/helpers/dates"
"github.com/iancoleman/orderedmap"
)
-// TickersResponse represents the response structure for the /stocks/tickers API endpoint.
-// It includes slices for various stock attributes such as symbol, name, type, currency, and exchange.
-// Optional fields are marked with 'omitempty' to exclude them from the JSON output if they are empty.
+// TickersResponse encapsulates the data structure returned by the /v2/stocks/tickers API endpoint. It includes arrays for various stock attributes such as symbols, names, types, currencies, and exchanges. Optional fields are omitted from the JSON output if they are empty.
+//
+// # Generated By
+//
+// - StockTickersRequestV2.Packed(): Makes a request for stock ticker data and returns a TickersResponse struct.
+//
+// # Methods
+//
+// - IsValid() bool: Checks if the response contains at least one symbol.
+// - String() string: Provides a string representation of the TickersResponse.
+// - Unpack() ([]Ticker, error): Converts the response into a slice of Ticker structs.
+// - UniqueSymbols() ([]string, error): Extracts a slice of unique stock symbols.
+// - ToMap() (map[string]Ticker, error): Converts the response into a map for quick access by symbol.
+// - MarshalJSON() ([]byte, error): Customizes the JSON encoding of the TickersResponse.
+//
+// # Notes
+//
+// - The Unpack method is particularly useful for processing or displaying ticker information on a per-symbol basis.
+// - The MarshalJSON method ensures the TickersResponse is encoded in a alphabetical order, which may be required by certain consumers of the JSON output.
type TickersResponse struct {
Symbol []string `json:"symbol"` // Symbol contains the stock symbols.
Name []string `json:"name,omitempty"` // Name contains the names of the stocks. Optional.
@@ -28,20 +45,29 @@ type TickersResponse struct {
Updated []int64 `json:"updated,omitempty"` // Updated contains UNIX timestamps of the last updates. Optional.
}
-// IsValid determines if the TickersResponse has at least one symbol.
+// IsValid checks whether the TickersResponse instance contains at least one symbol. This method is primarily used to quickly verify if the TickersResponse has any stock symbol data before proceeding with operations that require at least one symbol to be present.
//
-// Returns:
-// - true if there is at least one symbol; otherwise, false.
+// # Returns
+//
+// - bool: Returns true if there is at least one symbol; otherwise, false.
+//
+// # Notes
+//
+// - This method is useful for validating the TickersResponse before attempting to access its symbols, preventing errors related to empty symbol data.
func (tr *TickersResponse) IsValid() bool {
return len(tr.Symbol) > 0
}
-// String constructs a string representation of the TickersResponse.
-// It iterates through each symbol and its associated data, formatting them into a readable string.
-// If the 'Updated' field has a zero value, it prints as "nil".
+// String provides a human-readable representation of the TickersResponse struct. This method is primarily used for debugging or logging purposes, where a clear text format of the TickersResponse data is necessary. It includes all available stock attributes such as symbols, names, types, currencies, exchanges, FIGI codes, CIK numbers, and the last update times. For any stock attribute not updated, "nil" is printed instead of the timestamp.
+//
+// # Returns
+//
+// - string: A detailed string representation of the TickersResponse, enumerating all contained stock attributes and their values.
//
-// Returns:
-// - A string detailing the contents of the TickersResponse, including symbols, names, types, currencies, exchanges, FIGI codes, CIK numbers, and update times.
+// # Notes
+//
+// - This method is particularly useful for debugging or when a quick textual overview of the TickersResponse data is needed.
+// - The method ensures that even if certain optional fields are not populated, the output remains clear and understandable.
func (tr *TickersResponse) String() string {
var str strings.Builder
str.WriteString("TickersResponse{\n")
@@ -56,13 +82,16 @@ func (tr *TickersResponse) String() string {
return str.String()
}
-// Unpack converts a TickersResponse instance into a slice of Ticker structs.
+// Unpack converts a TickersResponse instance into a slice of Ticker structs, allowing for easy access and manipulation of individual ticker data. This method is particularly useful when you need to process or display ticker information on a per-symbol basis, ensuring that all relevant data is correctly associated with each symbol. It also handles the conversion of UNIX timestamps in the 'Updated' field to time.Time objects, providing a more usable format for date and time operations.
+//
+// # Returns
+//
+// - []Ticker: A slice of Ticker structs representing the unpacked tickers.
+// - error: An error if the TickersResponse is nil or if there is a mismatch in the lengths of the slices within the TickersResponse.
//
-// This method iterates through the fields of the TickersResponse struct, creating a Ticker struct for each symbol present in the response. It ensures that all corresponding fields are populated correctly. It converts the UNIX timestamp to a time.Time object for each Ticker struct if the 'Updated' field is present.
+// # Notes
//
-// Returns:
-// - A slice of Ticker structs representing the unpacked tickers.
-// - An error if the TickersResponse is nil or if there is a mismatch in the lengths of the slices within the TickersResponse.
+// - This method is essential for applications that require detailed and individualized ticker information for further processing or display.
func (tr *TickersResponse) Unpack() ([]Ticker, error) {
if tr == nil {
return nil, fmt.Errorf("TickersResponse is nil")
@@ -97,11 +126,16 @@ func safeIndex(slice []string, i int) string {
return ""
}
-// UniqueSymbols extracts and returns a slice of unique stock symbols from the TickersResponse.
+// UniqueSymbols extracts and returns a slice of unique stock symbols from the TickersResponse. This method is primarily used when you need to identify distinct stock symbols within a larger dataset, such as when consolidating data from multiple sources or filtering out duplicates for analysis purposes.
+//
+// # Returns
//
-// Returns:
// - []string: A slice of unique stock symbols.
// - error: An error encountered during the conversion to a map, if any.
+//
+// # Notes
+//
+// - This method leverages a map to ensure uniqueness, which may result in a different order of symbols than originally present in the TickersResponse.
func (tr *TickersResponse) UniqueSymbols() ([]string, error) {
tickerMap, err := tr.ToMap()
if err != nil {
@@ -116,11 +150,16 @@ func (tr *TickersResponse) UniqueSymbols() ([]string, error) {
return uniqueSymbols, nil
}
-// ToMap converts a TickersResponse into a map where each key is a stock symbol and its value is the corresponding Ticker struct.
+// ToMap converts a TickersResponse into a map, facilitating quick access to Ticker information by stock symbol. This method is particularly useful when you need to retrieve Ticker details for a specific symbol without iterating through a slice. It simplifies the process of accessing Ticker data by using stock symbols as keys in the resulting map.
+//
+// # Returns
+//
+// - map[string]Ticker: A map where each key is a stock symbol and its value is the corresponding Ticker struct, enabling efficient data retrieval.
+// - error: An error encountered during the conversion process, if any.
//
-// Returns:
-// - map[string]Ticker: A map with stock symbols as keys and Ticker structs as values.
-// - error: An error if the conversion fails.
+// # Notes
+//
+// - This method is ideal for scenarios where quick lookup of Ticker information is required.
func (tr *TickersResponse) ToMap() (map[string]Ticker, error) {
tickerInfos, err := tr.Unpack()
if err != nil {
@@ -134,11 +173,16 @@ func (tr *TickersResponse) ToMap() (map[string]Ticker, error) {
return tickerMap, nil
}
-// MarshalJSON customizes the JSON encoding for the TickersResponse struct.
+// MarshalJSON customizes the JSON encoding for the TickersResponse struct, providing a tailored representation of the TickersResponse data in JSON format. This method is primarily used when a TickersResponse instance needs to be serialized into JSON, either for storage, transmission over a network, or for use in web APIs.
+//
+// # Returns
//
-// Returns:
// - []byte: The JSON-encoded representation of the TickersResponse.
-// - error: An error if the encoding fails.
+// - error: An error if the encoding fails, encapsulating details of the failure.
+//
+// # Notes
+//
+// - This method ensures that the TickersResponse is encoded in a specific order, which may be required by certain consumers of the JSON output.
func (tr *TickersResponse) MarshalJSON() ([]byte, error) {
if tr == nil {
return nil, fmt.Errorf("TickersResponse is nil")
@@ -164,7 +208,20 @@ func (tr *TickersResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(o)
}
-// Ticker represents the information of a ticker.
+// Ticker represents the detailed information of a stock ticker, including its symbol, name, type, currency, exchange, FIGI codes, CIK number, and the last update time. This struct is designed to encapsulate all relevant data for a single stock ticker, making it easier to manage and access stock information in a structured manner.
+//
+// # Generated By
+//
+// - TickersResponse.Unpack(): Converts a TickersResponse instance into a slice of Ticker structs.
+//
+// # Methods
+//
+// - String(): Generates a string representation of the Ticker struct, detailing all its properties in a readable format.
+//
+// # Notes
+//
+// - The Updated field uses the time.Time type to represent the last update time in a format that can be easily manipulated within Go programs.
+// - Optional fields like Name, Type, Currency, Exchange, FigiShares, FigiComposite, and Cik are omitted from JSON output if empty, thanks to the `omitempty` JSON tag.
type Ticker struct {
Symbol string `json:"symbol"`
Name string `json:"name,omitempty"`
@@ -177,25 +234,36 @@ type Ticker struct {
Updated time.Time `json:"updated,omitempty"`
}
-// String generates a string representation of the Ticker struct.
+// String generates a string representation of the Ticker struct, providing a human-readable format of its properties. This method is primarily used for logging, debugging, or displaying the Ticker's information in a clear and concise manner.
+//
+// # Returns
+//
+// - string: A formatted string detailing the Ticker's properties in a readable format.
//
-// Returns:
-// - A string detailing the Ticker's properties in a readable format.
+// # Notes
+//
+// - This method is particularly useful when a quick overview of the Ticker's data is needed without accessing each property individually.
func (ti Ticker) String() string {
updated := "nil"
if !ti.Updated.IsZero() {
- updated = formatTime(ti.Updated)
+ updated = dates.TimeString(ti.Updated)
}
return fmt.Sprintf("Ticker{Symbol: %s, Name: %s, Type: %s, Currency: %s, Exchange: %s, FigiShares: %s, FigiComposite: %s, Cik: %s, Updated: %s}", ti.Symbol, ti.Name, ti.Type, ti.Currency, ti.Exchange, ti.FigiShares, ti.FigiComposite, ti.Cik, updated)
}
-// MapToTickersResponse converts a map of Ticker structs into a TickersResponse struct.
+// MapToTickersResponse aggregates a collection of Ticker structs, indexed by their ticker symbols, into a single TickersResponse struct. This method is primarily used when there is a need to consolidate individual ticker information into a unified response format, suitable for further processing or serialization.
+//
+// # Parameters
+//
+// - map[string]Ticker: A map where the key is a string representing the ticker symbol, and the value is a Ticker struct.
+//
+// # Returns
+//
+// - *TickersResponse: A pointer to a TickersResponse struct that aggregates the information from the input map.
//
-// Parameters:
-// - tickerMap: A map where the key is a string representing the ticker symbol, and the value is a Ticker struct.
+// # Notes
//
-// Returns:
-// - A pointer to a TickersResponse struct that aggregates the information from the input map.
+// - This method is particularly useful for converting a collection of dispersed ticker data into a structured and easily manageable format.
func MapToTickersResponse(tickerMap map[string]Ticker) *TickersResponse {
var tr TickersResponse
keys := make([]string, 0, len(tickerMap))
@@ -219,14 +287,16 @@ func MapToTickersResponse(tickerMap map[string]Ticker) *TickersResponse {
return &tr
}
-// SaveToCSV writes the contents of tickerMap to a CSV file specified by filename.
+// SaveToCSV serializes the ticker data from a map into a CSV file. This method is primarily used for exporting ticker information into a structured file format, allowing for easy data sharing and analysis outside the application context.
//
-// Parameters:
-// - tickerMap: A map where the key is a string representing the ticker symbol, and the value is a Ticker struct.
-// - filename: The name of the file to which the CSV data will be written.
+// # Parameters
//
-// Returns:
-// - An error if writing to the CSV file fails, otherwise nil.
+// - map[string]Ticker: A map containing ticker symbols as keys and Ticker structs as values.
+// - string: The filename of the CSV file to be created and written to.
+//
+// # Returns
+//
+// - error: An error object if the CSV file could not be written; otherwise, nil.
func SaveToCSV(tickerMap map[string]Ticker, filename string) error {
if tickerMap == nil {
return fmt.Errorf("tickerMap is nil")
@@ -261,18 +331,20 @@ func SaveToCSV(tickerMap map[string]Ticker, filename string) error {
return nil
}
-// CombineTickerResponses combines multiple TickersResponses into a single map.
+// CombineTickerResponses merges multiple TickersResponse instances into a single map, facilitating the aggregation of ticker data from various sources. This method is particularly useful when consolidating ticker information obtained from different API calls or datasets into a unified structure for easier access and manipulation. It ensures thread safety by using a mutex to manage concurrent access to the resulting map.
+//
+// # Parameters
+//
+// - []*TickersResponse: A slice of pointers to TickersResponse structs intended for combination.
+//
+// # Returns
//
-// This function takes a slice of pointers to TickersResponse structs and combines them into a single map
-// where the key is a string representing the ticker symbol and the value is a Ticker struct. It handles
-// concurrent access to the map using a mutex to ensure thread safety.
+// - map[string]Ticker: A map consolidating ticker symbols and their corresponding Ticker structs.
+// - error: An error object indicating failure during the combination process, if any.
//
-// Parameters:
-// - responses: A slice of pointers to TickersResponse structs that are to be combined.
+// # Notes
//
-// Returns:
-// - A map where the key is a string representing the ticker symbol and the value is a Ticker struct.
-// - An error if any of the TickersResponse structs cannot be converted to a map or if any other error occurs during the process.
+// - This method employs a mutex to prevent race conditions, ensuring the integrity of the combined map in concurrent environments.
func CombineTickerResponses(responses []*TickersResponse) (map[string]Ticker, error) {
tickerMap := make(map[string]Ticker)
var mutex sync.Mutex