models

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2024 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package models defines the data structures used to represent the responses from the Market Data API. It includes models for stock quotes, options quotes, stock candles, market status, and more. Each model is designed to parse and validate the JSON responses from the API, providing a structured 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.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CombineTickerResponses

func CombineTickerResponses(responses []*TickersResponse) (map[string]Ticker, error)

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

  • 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.

Notes

  • This method employs a mutex to prevent race conditions, ensuring the integrity of the combined map in concurrent environments.

func SaveToCSV

func SaveToCSV(tickerMap map[string]Ticker, filename string) error

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

  • 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.

Types

type BulkStockCandlesResponse added in v1.0.0

type BulkStockCandlesResponse struct {
	Symbol []string  `json:"symbol"` // Symbol holds the stock ticker of the candle.
	Date   []int64   `json:"t"`      // Date holds UNIX timestamps for each candle.
	Open   []float64 `json:"o"`      // Open holds the opening prices for each candle.
	High   []float64 `json:"h"`      // High holds the highest prices reached in each candle.
	Low    []float64 `json:"l"`      // Low holds the lowest prices reached in each candle.
	Close  []float64 `json:"c"`      // Close holds the closing prices for each candle.
	Volume []int64   `json:"v"`      // Volume represents the trading volume in each candle.
}

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.

func (BulkStockCandlesResponse) String added in v1.0.0

func (bscr BulkStockCandlesResponse) String() string

String returns a string representation of the BulkStockCandlesResponse struct.

This method formats the BulkStockCandlesResponse's fields (Symbol, Date, Open, High, Low, Close, Volume) 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.

Returns:

  • string: A formatted string that contains the Symbol, Date (as UNIX timestamps), Open, High, Low, Close, and Volume fields of the BulkStockCandlesResponse.

func (*BulkStockCandlesResponse) Unpack added in v1.0.0

func (bscr *BulkStockCandlesResponse) Unpack() ([]Candle, error)

Unpack converts a BulkStockCandlesResponse into a slice of Candle.

This method iterates through the slices of stock candle data contained within the BulkStockCandlesResponse struct. It constructs a Candle struct for each set of corresponding data across the slices (symbol, date, open, high, low, close, volume). 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

  • *BulkStockCandlesResponse: A pointer to the BulkStockCandlesResponse instance containing the bulk stock candles data to be unpacked.

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.

type ByClose added in v1.0.0

type ByClose []Candle

ByClose implements sort.Interface for []Candle based on the Close field.

Example
// Create a slice of Candle instances
candles := []Candle{
	{Symbol: "AAPL", Date: time.Now(), Open: 100, High: 105, Low: 95, Close: 102, Volume: 1000},
	{Symbol: "AAPL", Date: time.Now(), Open: 102, High: 106, Low: 98, Close: 104, Volume: 1500},
	{Symbol: "AAPL", Date: time.Now(), Open: 99, High: 103, Low: 97, Close: 100, Volume: 1200},
}

// Sort the candles by their Close value using sort.Sort and ByClose
sort.Sort(ByClose(candles))

// Print the sorted candles to demonstrate the order
for _, candle := range candles {
	fmt.Printf("Close: %v\n", candle.Close)
}
Output:

Close: 100
Close: 102
Close: 104

func (ByClose) Len added in v1.0.0

func (a ByClose) Len() int

func (ByClose) Less added in v1.0.0

func (a ByClose) Less(i, j int) bool

func (ByClose) Swap added in v1.0.0

func (a ByClose) Swap(i, j int)

type ByDate added in v1.0.0

type ByDate []Candle

ByDate implements sort.Interface for []Candle based on the Date field. This allows for sorting a slice of Candle instances by their Date field in ascending order.

Example
// Assuming the Candle struct has at least a Date field of type time.Time
candles := []Candle{
	{Date: time.Date(2023, 3, 10, 0, 0, 0, 0, time.UTC)},
	{Date: time.Date(2023, 1, 5, 0, 0, 0, 0, time.UTC)},
	{Date: time.Date(2023, 2, 20, 0, 0, 0, 0, time.UTC)},
}

// Sorting the slice of Candle instances by their Date field in ascending order
sort.Sort(ByDate(candles))

// Printing out the sorted dates to demonstrate the order
for _, candle := range candles {
	fmt.Println(candle.Date.Format("2006-01-02"))
}
Output:

2023-01-05
2023-02-20
2023-03-10

func (ByDate) Len added in v1.0.0

func (a ByDate) Len() int

func (ByDate) Less added in v1.0.0

func (a ByDate) Less(i, j int) bool

func (ByDate) Swap added in v1.0.0

func (a ByDate) Swap(i, j int)

type ByHigh added in v1.0.0

type ByHigh []Candle

ByHigh implements sort.Interface for []Candle based on the High field.

Example
// Assuming the Candle struct has at least a High field of type float64
candles := []Candle{
	{High: 15.2},
	{High: 11.4},
	{High: 13.5},
}

// Sorting the slice of Candle instances by their High field in ascending order
sort.Sort(ByHigh(candles))

// Printing out the sorted High values to demonstrate the order
for _, candle := range candles {
	fmt.Printf("%.1f\n", candle.High)
}
Output:

11.4
13.5
15.2

func (ByHigh) Len added in v1.0.0

func (a ByHigh) Len() int

func (ByHigh) Less added in v1.0.0

func (a ByHigh) Less(i, j int) bool

func (ByHigh) Swap added in v1.0.0

func (a ByHigh) Swap(i, j int)

type ByLow added in v1.0.0

type ByLow []Candle

ByLow implements sort.Interface for []Candle based on the Low field.

Example
// Assuming the Candle struct has at least a Low field of type float64
candles := []Candle{
	{Low: 5.5},
	{Low: 7.2},
	{Low: 6.3},
}

// Sorting the slice of Candle instances by their Low field in ascending order
sort.Sort(ByLow(candles))

// Printing out the sorted Low values to demonstrate the order
for _, candle := range candles {
	fmt.Printf("%.1f\n", candle.Low)
}
Output:

5.5
6.3
7.2

func (ByLow) Len added in v1.0.0

func (a ByLow) Len() int

func (ByLow) Less added in v1.0.0

func (a ByLow) Less(i, j int) bool

func (ByLow) Swap added in v1.0.0

func (a ByLow) Swap(i, j int)

type ByN added in v1.0.0

type ByN []Candle

ByN implements sort.Interface for []Candle based on the N field.

Example
// Assuming the Candle struct has at least an N field of type int (or any comparable type)
candles := []Candle{
	{N: 3},
	{N: 1},
	{N: 2},
}

// Sorting the slice of Candle instances by their N field in ascending order
sort.Sort(ByN(candles))

// Printing out the sorted N values to demonstrate the order
for _, candle := range candles {
	fmt.Println(candle.N)
}
Output:

1
2
3

func (ByN) Len added in v1.0.0

func (a ByN) Len() int

func (ByN) Less added in v1.0.0

func (a ByN) Less(i, j int) bool

func (ByN) Swap added in v1.0.0

func (a ByN) Swap(i, j int)

type ByOpen added in v1.0.0

type ByOpen []Candle

ByOpen implements sort.Interface for []Candle based on the Open field.

Example
// Assuming the Candle struct has at least an Open field of type float64
candles := []Candle{
	{Open: 10.5},
	{Open: 8.2},
	{Open: 9.7},
}

// Sorting the slice of Candle instances by their Open field in ascending order
sort.Sort(ByOpen(candles))

// Printing out the sorted Open values to demonstrate the order
for _, candle := range candles {
	fmt.Printf("%.1f\n", candle.Open)
}
Output:

8.2
9.7
10.5

func (ByOpen) Len added in v1.0.0

func (a ByOpen) Len() int

func (ByOpen) Less added in v1.0.0

func (a ByOpen) Less(i, j int) bool

func (ByOpen) Swap added in v1.0.0

func (a ByOpen) Swap(i, j int)

type BySymbol added in v1.0.0

type BySymbol []Candle

BySymbol implements sort.Interface for []Candle based on the Symbol field. Candles are sorted in ascending order.

Example
// Create a slice of Candle instances with different symbols
candles := []Candle{
	{Symbol: "MSFT", Date: time.Date(2023, 4, 10, 0, 0, 0, 0, time.UTC), Open: 250.0, High: 255.0, Low: 248.0, Close: 252.0, Volume: 3000},
	{Symbol: "AAPL", Date: time.Date(2023, 4, 10, 0, 0, 0, 0, time.UTC), Open: 150.0, High: 155.0, Low: 149.0, Close: 152.0, Volume: 2000},
	{Symbol: "GOOGL", Date: time.Date(2023, 4, 10, 0, 0, 0, 0, time.UTC), Open: 1200.0, High: 1210.0, Low: 1195.0, Close: 1205.0, Volume: 1000},
}

// Sort the candles by their Symbol using sort.Sort and BySymbol
sort.Sort(BySymbol(candles))

// Print the sorted candles to demonstrate the order
for _, candle := range candles {
	fmt.Printf("Symbol: %s, Close: %.2f\n", candle.Symbol, candle.Close)
}
Output:

Symbol: AAPL, Close: 152.00
Symbol: GOOGL, Close: 1205.00
Symbol: MSFT, Close: 252.00

func (BySymbol) Len added in v1.0.0

func (a BySymbol) Len() int

func (BySymbol) Less added in v1.0.0

func (a BySymbol) Less(i, j int) bool

func (BySymbol) Swap added in v1.0.0

func (a BySymbol) Swap(i, j int)

type ByVWAP added in v1.0.0

type ByVWAP []Candle

ByVWAP implements sort.Interface for []Candle based on the VWAP field.

Example
// Assuming the Candle struct has at least a VWAP (Volume Weighted Average Price) field of type float64
candles := []Candle{
	{VWAP: 10.5},
	{VWAP: 8.2},
	{VWAP: 9.7},
}

// Sorting the slice of Candle instances by their VWAP field in ascending order
sort.Sort(ByVWAP(candles))

// Printing out the sorted VWAP values to demonstrate the order
for _, candle := range candles {
	fmt.Printf("%.1f\n", candle.VWAP)
}
Output:

8.2
9.7
10.5

func (ByVWAP) Len added in v1.0.0

func (a ByVWAP) Len() int

func (ByVWAP) Less added in v1.0.0

func (a ByVWAP) Less(i, j int) bool

func (ByVWAP) Swap added in v1.0.0

func (a ByVWAP) Swap(i, j int)

type ByVolume added in v1.0.0

type ByVolume []Candle

ByVolume implements sort.Interface for []Candle based on the Volume field.

Example
// Assuming the Candle struct has at least a Volume field of type int
candles := []Candle{
	{Volume: 300},
	{Volume: 100},
	{Volume: 200},
}

// Sorting the slice of Candle instances by their Volume field in ascending order
sort.Sort(ByVolume(candles))

// Printing out the sorted volumes to demonstrate the order
for _, candle := range candles {
	fmt.Println(candle.Volume)
}
Output:

100
200
300

func (ByVolume) Len added in v1.0.0

func (a ByVolume) Len() int

func (ByVolume) Less added in v1.0.0

func (a ByVolume) Less(i, j int) bool

func (ByVolume) Swap added in v1.0.0

func (a ByVolume) Swap(i, j int)

type Candle added in v1.0.0

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.
	Open   float64   `json:"o"`                // Open is the opening price of the candle.
	High   float64   `json:"h"`                // High is the highest price reached during the candle's time.
	Low    float64   `json:"l"`                // Low is the lowest price reached during the candle's time.
	Close  float64   `json:"c"`                // Close is the closing price of the candle.
	Volume int64     `json:"v,omitempty"`      // Volume represents the trading volume during the candle's time.
	VWAP   float64   `json:"vwap,omitempty"`   // VWAP is the Volume Weighted Average Price, optional.
	N      int64     `json:"n,omitempty"`      // N is the number of trades that occurred, optional.
}

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.

func (Candle) Clone added in v1.0.0

func (c Candle) Clone() Candle

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 (Candle) Equals added in v1.0.0

func (c Candle) Equals(other Candle) bool

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 (Candle) IsAfter added in v1.0.0

func (c Candle) IsAfter(other Candle) bool

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

  • Candle: The other Candle instance to compare with the current Candle instance.

Returns

  • bool: Indicates whether the current Candle's date is after the 'other' Candle's date. Returns true if it is; otherwise, false.

func (Candle) IsBefore added in v1.0.0

func (c Candle) IsBefore(other Candle) bool

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

  • Candle: The other Candle instance to compare with the current Candle instance.

Returns

  • bool: Returns true if the date of the current Candle instance is before the date of the 'other' Candle instance; otherwise, returns false.

Notes

  • This method only compares the dates of the Candle instances, ignoring other fields such as Open, Close, High, Low, etc.

func (Candle) IsValid added in v1.0.0

func (c Candle) IsValid() bool

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

  • bool: Indicates whether the Candle is valid based on its financial data. Returns true if all validity criteria are met; otherwise, false.

func (Candle) MarshalJSON added in v1.0.0

func (c Candle) MarshalJSON() ([]byte, error)

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 (Candle) String added in v1.0.0

func (c Candle) String() string

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

  • 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 (*Candle) UnmarshalJSON added in v1.0.0

func (c *Candle) UnmarshalJSON(data []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.

type FundCandlesResponse added in v1.2.0

type FundCandlesResponse struct {
	Date  []int64   `json:"t"` // Date holds UNIX timestamps for each candle.
	Open  []float64 `json:"o"` // Open holds the opening prices for each candle.
	High  []float64 `json:"h"` // High holds the highest prices reached in each candle.
	Low   []float64 `json:"l"` // Low holds the lowest prices reached in each candle.
	Close []float64 `json:"c"` // Close holds the closing prices for each candle.
}

FundCandlesResponse encapsulates the data structure for the JSON response of mutual fund candles data. It includes detailed information about fund 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

  • FundCandlesRequest.Packed(): Sends a FundCandlesRequest and unmarshals the response into FundCandlesResponse.

Methods

  • Unpack() ([]Candle, error): Converts a FundCandlesResponse into a slice of Candle.
  • String() string: Returns a string representation of the FundCandlesResponse.
  • IsValid() bool: Checks if a FundCandlesResponse is valid.
  • Validate() error: Validates a FundCandlesResponse.
  • MarshalJSON() ([]byte, error): Marshals a FundCandlesResponse into JSON.
  • UnmarshalJSON(data []byte) error: Unmarshals JSON into a FundCandlesResponse.
  • GetDateRange() (dates.DateRange, error): Returns the date range of a FundCandlesResponse.
  • 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.

func CombineFundCandles added in v1.2.0

func CombineFundCandles(f1, f2 *FundCandlesResponse) (*FundCandlesResponse, error)

CombineFundCandles merges two FundCandlesResponse structs into a single one. It checks if the versions of the two structs are the same, ensures there is no time overlap between them, and then combines their data into a new FundCandlesResponse struct. If the versions do not match or there is a time overlap, it returns an error.

Parameters

  • *FundCandlesResponse: The first FundCandlesResponse struct to be combined.
  • *FundCandlesResponse: The second FundCandlesResponse struct to be combined.

Returns

  • *FundCandlesResponse: A pointer to the newly combined FundCandlesResponse struct.
  • error: An error if the versions do not match, there is a time overlap, or the combined struct fails validation.

func (*FundCandlesResponse) GetDateRange added in v1.2.0

func (f *FundCandlesResponse) GetDateRange() (dates.DateRange, error)

GetDateRange calculates and returns the date range covered by the FundCandlesResponse. This method is useful for determining the span of time that the mutual fund candle data encompasses, allowing users to understand the temporal scope of the data they are working with.

Returns

  • dates.DateRange: The range of dates covered by the FundCandlesResponse.
  • error: An error if calculating the date range fails.

Notes

  • This method is particularly useful when filtering data based on specific time frames.

func (*FundCandlesResponse) IsValid added in v1.2.0

func (f *FundCandlesResponse) IsValid() bool

IsValid determines the validity of a FundCandlesResponse. 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

  • bool: Indicates whether the FundCandlesResponse is valid.

Notes

  • This method should be used to prevent the propagation of invalid or corrupt data within applications that rely on mutual fund candle information.

func (*FundCandlesResponse) MarshalJSON added in v1.2.0

func (f *FundCandlesResponse) MarshalJSON() ([]byte, error)

MarshalJSON converts a FundCandlesResponse instance into its JSON representation. This method is primarily used for encoding the FundCandlesResponse into a JSON format that can be easily transmitted or stored. It organizes the mutual fund candle data into a structured JSON format, ensuring compatibility with systems that consume JSON.

Returns

  • []byte: The JSON-encoded representation of the FundCandlesResponse.
  • error: An error object that will be non-nil if the marshaling process encounters any issues.

func (*FundCandlesResponse) PruneOutsideDateRange added in v1.2.0

func (f *FundCandlesResponse) PruneOutsideDateRange(dr dates.DateRange) error

PruneOutsideDateRange method is used to filter out data points from a FundCandlesResponse that fall outside a specified date range. This method is essential when the user needs to focus on analyzing fund candle data within a specific period, thereby excluding irrelevant data points that do not fall within the desired date range.

Parameters

  • 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 FundCandlesResponse in place, removing any data points that are outside the specified date range.

func (*FundCandlesResponse) String added in v1.2.0

func (f *FundCandlesResponse) String() string

String generates a string representation of a FundCandlesResponse. This method is primarily used for logging or debugging purposes, allowing developers to easily view the contents of a FundCandlesResponse in a human-readable format.

Returns

  • string: A string representation of the FundCandlesResponse.

Notes

  • Mutual fund candles do not include Volume, VWAP, or transaction quantities (n).

func (*FundCandlesResponse) UnmarshalJSON added in v1.2.0

func (f *FundCandlesResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON converts JSON data into a FundCandlesResponse instance. This method is essential for decoding JSON data received from external sources into a structured FundCandlesResponse 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 FundCandlesResponse.

Parameters

  • []byte: The JSON-encoded data that needs to be converted into a FundCandlesResponse.

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 (*FundCandlesResponse) Unpack added in v1.2.0

func (fcr *FundCandlesResponse) Unpack() ([]Candle, error)

Unpack converts a FundCandlesResponse into a slice of Candle. This method is primarily used to transform the aggregated mutual fund 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 mutual fund candle data more conveniently in their applications.

Returns

  • []Candle: A slice of Candle containing the unpacked data from the FundCandlesResponse.
  • error: An error if the slices within FundCandlesResponse are not of equal length, indicating inconsistent data.

Notes

  • This method ensures that all slices within the FundCandlesResponse have the same length before unpacking to prevent data misalignment.

func (*FundCandlesResponse) Validate added in v1.2.0

func (f *FundCandlesResponse) Validate() error

Validate checks the integrity and consistency of a FundCandlesResponse. 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 mutual fund candle information.

Returns

  • error: An error if the FundCandlesResponse is not valid. A nil error indicates a valid FundCandlesResponse.

Notes

  • This method performs multiple checks in parallel to efficiently validate the response.

type IndexQuote

type IndexQuote struct {
	Symbol    string    // Symbol is the stock symbol or ticker.
	Last      float64   // Last is the last traded price.
	Change    *float64  // Change represents the change in price, can be nil if not applicable.
	ChangePct *float64  // ChangePct represents the percentage change in price, can be nil if not applicable.
	High52    *float64  // High52 is the 52-week high price, can be nil if not applicable.
	Low52     *float64  // Low52 is the 52-week low price, can be nil if not applicable.
	Volume    int64     // Volume is the number of shares traded.
	Updated   time.Time // Updated is the timestamp of the last update.
}

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

  • IndexQuotesResponse.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.

func (IndexQuote) String

func (iq IndexQuote) String() string

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

  • 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.

type IndexQuotesResponse

type IndexQuotesResponse struct {
	Symbol    []string   `json:"symbol"`               // Symbols are the stock symbols or tickers.
	Last      []float64  `json:"last"`                 // Last contains the last traded prices.
	Change    []*float64 `json:"change,omitempty"`     // Change represents the change in price, can be nil if not applicable.
	ChangePct []*float64 `json:"changepct,omitempty"`  // ChangePct represents the percentage change in price, can be nil if not applicable.
	High52    *[]float64 `json:"52weekHigh,omitempty"` // High52 points to a slice of 52-week high prices, can be nil if not applicable.
	Low52     *[]float64 `json:"52weekLow,omitempty"`  // Low52 points to a slice of 52-week low prices, can be nil if not applicable.
	Updated   []int64    `json:"updated"`              // Updated contains timestamps of the last updates.
}

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.

func (*IndexQuotesResponse) String

func (iqr *IndexQuotesResponse) String() string

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

  • string: A formatted string containing the contents of the IndexQuotesResponse.

func (*IndexQuotesResponse) Unpack

func (iqr *IndexQuotesResponse) Unpack() ([]IndexQuote, error)

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

  • []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.

type IndicesCandlesResponse

type IndicesCandlesResponse struct {
	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.
}

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.

func (*IndicesCandlesResponse) IsValid

func (icr *IndicesCandlesResponse) IsValid() bool

Returns

  • bool: Indicates whether the IndicesCandlesResponse is valid.

func (*IndicesCandlesResponse) MarshalJSON

func (icr *IndicesCandlesResponse) MarshalJSON() ([]byte, error)

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

  • []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 (*IndicesCandlesResponse) String

func (icr *IndicesCandlesResponse) String() string

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

  • string: A formatted string containing the time, open, high, low, and close values of the indices.

func (*IndicesCandlesResponse) UnmarshalJSON

func (icr *IndicesCandlesResponse) UnmarshalJSON(data []byte) error

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

  • []byte: A byte slice of the JSON object to be unmarshaled.

Returns

  • error: An error if unmarshaling or validation fails, otherwise nil.

func (*IndicesCandlesResponse) Unpack

func (icr *IndicesCandlesResponse) Unpack() ([]Candle, error)

Unpack converts the IndicesCandlesResponse into a slice of IndexCandle.

Returns

  • []Candle: A slice of Candle that holds the OHLC data.
  • error: An error object that indicates a failure in unpacking the response.

func (*IndicesCandlesResponse) Validate

func (icr *IndicesCandlesResponse) Validate() error

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

  • error: An error if any validation check fails, otherwise nil. This allows for easy identification of data integrity issues.

type MarketStatusReport added in v0.0.5

type MarketStatusReport struct {
	Date   time.Time `json:"date"`
	Open   bool      `json:"open"`
	Closed bool      `json:"closed"`
}

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.

func (MarketStatusReport) String added in v0.0.5

func (ms MarketStatusReport) String() string

String returns a string representation of the MarketStatusReport.

Returns

  • string: A string representation of the MarketStatusReport.

type MarketStatusResponse

type MarketStatusResponse struct {
	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.
}

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.

func (*MarketStatusResponse) GetClosedDates

func (msr *MarketStatusResponse) GetClosedDates() ([]time.Time, error)

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 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 (*MarketStatusResponse) GetDateRange

func (msr *MarketStatusResponse) GetDateRange() (*dates.DateRange, error)

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 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 (*MarketStatusResponse) GetOpenDates

func (msr *MarketStatusResponse) GetOpenDates() ([]time.Time, error)

Returns

  • []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 (*MarketStatusResponse) IsValid

func (msr *MarketStatusResponse) IsValid() bool

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: Indicates whether there is at least one date entry in the MarketStatusResponse. True if at least one date is present, false otherwise.

func (*MarketStatusResponse) String

func (msr *MarketStatusResponse) String() string

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 formatted string containing the dates and their corresponding statuses.

func (*MarketStatusResponse) Unpack

func (msr *MarketStatusResponse) Unpack() ([]MarketStatusReport, error)

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

  • []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.

type OptionLookupResponse added in v0.0.5

type OptionLookupResponse struct {
	OptionSymbol string `json:"optionSymbol"` // OptionSymbol is the symbol of the option.
}

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.

func (*OptionLookupResponse) IsValid added in v0.0.5

func (olr *OptionLookupResponse) IsValid() bool

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

  • bool: Indicates the validity of the OptionLookupResponse. Returns true if the OptionSymbol is not empty, otherwise false.

func (*OptionLookupResponse) String added in v0.0.5

func (olr *OptionLookupResponse) String() string

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 (*OptionLookupResponse) Unpack added in v0.0.5

func (olr *OptionLookupResponse) Unpack() (string, error)

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

  • This method is crucial for error handling and data validation in financial market data applications, ensuring that only valid responses are processed.

type OptionQuote added in v0.0.5

type OptionQuote struct {
	OptionSymbol    string    // OptionSymbol is the symbol of the option.
	Underlying      string    // Underlying is the symbol of the underlying asset.
	Expiration      time.Time // Expiration is the time when the option expires.
	Side            string    // Side indicates whether the option is a call or a put.
	Strike          float64   // Strike is the strike price of the option.
	FirstTraded     time.Time // FirstTraded is the time when the option was first traded.
	DTE             int       // DTE (Days to Expiration) is the number of days until the option expires.
	Ask             float64   // Ask is the ask price of the option.
	AskSize         int64     // AskSize is the size of the ask order.
	Bid             float64   // Bid is the bid price of the option.
	BidSize         int64     // BidSize is the size of the bid order.
	Mid             float64   // Mid is the mid price calculated between the bid and ask prices.
	Last            float64   // Last is the last traded price of the option.
	Volume          int64     // Volume is the trading volume of the option.
	OpenInterest    int64     // OpenInterest is the total number of outstanding contracts.
	UnderlyingPrice float64   // UnderlyingPrice is the price of the underlying asset.
	InTheMoney      bool      // InTheMoney indicates whether the option is in the money.
	Updated         time.Time // Updated is the time when the option data was last updated.
	IV              *float64  // IV (Implied Volatility) is the implied volatility of the option.
	Delta           *float64  // Delta measures the rate of change of the option's price with respect to the underlying asset's price.
	Gamma           *float64  // Gamma measures the rate of change in delta over the underlying asset's price movement.
	Theta           *float64  // Theta represents the rate of decline in the option's value with time.
	Vega            *float64  // Vega measures sensitivity to volatility.
	Rho             *float64  // Rho measures sensitivity to the interest rate.
	IntrinsicValue  float64   // IntrinsicValue is the value of the option if it were exercised now.
	ExtrinsicValue  float64   // ExtrinsicValue is the value of the option above its intrinsic value.
}

OptionQuote represents a single option quote with detailed information such as the symbol, underlying asset, expiration time, and pricing information.

func (OptionQuote) DisplayDelta added in v0.1.0

func (oq OptionQuote) DisplayDelta() string

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 (OptionQuote) DisplayGamma added in v0.1.0

func (oq OptionQuote) DisplayGamma() string

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 (OptionQuote) DisplayIV added in v0.1.0

func (oq OptionQuote) DisplayIV() string

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 (OptionQuote) DisplayMid added in v1.1.0

func (oq OptionQuote) DisplayMid() string

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 (OptionQuote) DisplayRho added in v0.1.0

func (oq OptionQuote) DisplayRho() string

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 (OptionQuote) DisplayTheta added in v0.1.0

func (oq OptionQuote) DisplayTheta() string

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 (OptionQuote) DisplayVega added in v0.1.0

func (oq OptionQuote) DisplayVega() string

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 (OptionQuote) String added in v0.0.5

func (oq OptionQuote) String() string

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

  • string: A formatted string that encapsulates the OptionQuote details, making it easier to read and understand.

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.

type OptionQuotesResponse added in v0.0.5

type OptionQuotesResponse struct {
	OptionSymbol    []string   `json:"optionSymbol"`    // OptionSymbol holds the symbols of the options.
	Underlying      []string   `json:"underlying"`      // Underlying contains the symbols of the underlying assets.
	Expiration      []int64    `json:"expiration"`      // Expiration stores UNIX timestamps for when the options expire.
	Side            []string   `json:"side"`            // Side indicates whether the option is a call or a put.
	Strike          []float64  `json:"strike"`          // Strike represents the strike prices of the options.
	FirstTraded     []int64    `json:"firstTraded"`     // FirstTraded stores UNIX timestamps for when the options were first traded.
	DTE             []int      `json:"dte"`             // DTE (Days to Expiration) indicates the number of days until the options expire.
	Ask             []float64  `json:"ask"`             // Ask contains the ask prices of the options.
	AskSize         []int64    `json:"askSize"`         // AskSize holds the sizes of the ask orders.
	Bid             []float64  `json:"bid"`             // Bid contains the bid prices of the options.
	BidSize         []int64    `json:"bidSize"`         // BidSize holds the sizes of the bid orders.
	Mid             []float64  `json:"mid"`             // Mid represents the mid prices calculated between the bid and ask prices.
	Last            []float64  `json:"last"`            // Last contains the last traded prices of the options.
	Volume          []int64    `json:"volume"`          // Volume indicates the trading volumes of the options.
	OpenInterest    []int64    `json:"openInterest"`    // OpenInterest represents the total number of outstanding contracts.
	UnderlyingPrice []float64  `json:"underlyingPrice"` // UnderlyingPrice contains the prices of the underlying assets.
	InTheMoney      []bool     `json:"inTheMoney"`      // InTheMoney indicates whether the options are in the money.
	Updated         []int64    `json:"updated"`         // Updated stores UNIX timestamps for when the option data was last updated.
	IV              []*float64 `json:"iv,omitempty"`    // IV (Implied Volatility) represents the implied volatilities of the options.
	Delta           []*float64 `json:"delta,omitempty"` // Delta measures the rate of change of the option's price with respect to the underlying asset's price.
	Gamma           []*float64 `json:"gamm,omitempty"`  // Gamma measures the rate of change in delta over the underlying asset's price movement.
	Theta           []*float64 `json:"theta,omitempty"` // Theta represents the rate of decline in the option's value with time.
	Vega            []*float64 `json:"vega,omitempty"`  // Vega measures sensitivity to volatility.
	Rho             []*float64 `json:"rho,omitempty"`   // Rho measures sensitivity to the interest rate.
	IntrinsicValue  []float64  `json:"intrinsicValue"`  // IntrinsicValue represents the value of the option if it were exercised now.
	ExtrinsicValue  []float64  `json:"extrinsicValue"`  // ExtrinsicValue represents the value of the option above its intrinsic value.
}

OptionQuotesResponse represents the JSON structure of the response received for option quotes. It includes slices for various option attributes such as symbols, underlying assets, expiration times, and pricing information.

func (*OptionQuotesResponse) IsValid added in v0.1.0

func (oqr *OptionQuotesResponse) IsValid() bool

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

  • 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 (*OptionQuotesResponse) String added in v0.0.5

func (oqr *OptionQuotesResponse) String() string

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.

Notes

  • This method simplifies the visualization of complex OptionQuotes data by converting it into a string format.

func (*OptionQuotesResponse) Unpack added in v0.0.5

func (oqr *OptionQuotesResponse) Unpack() ([]OptionQuote, error)

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.

Notes

  • This method first validates the OptionQuotesResponse to ensure consistency before attempting to unpack it.

func (*OptionQuotesResponse) Validate added in v0.1.0

func (oqr *OptionQuotesResponse) Validate() error

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.

Notes

  • This method is particularly important for preventing runtime errors that could occur when processing inconsistent data.

type OptionStrikes added in v1.1.0

type OptionStrikes 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.
}

OptionStrikes encapsulates the expiration date and available strike prices for an option contract.

Generated By

  • OptionStrikesResponse.Unpack(): Converts an ordered map of strikes into a slice of OptionStrikes.

Methods

  • String() string: Returns a string representation of the OptionStrikes, 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.

func (OptionStrikes) String added in v1.1.0

func (os OptionStrikes) String() string

String provides a human-readable representation of the OptionStrikes struct, including its expiration and strike prices. This method is primarily used for logging, debugging, or displaying the OptionStrikes in a format that is easy to read and understand.

Returns

  • string: A formatted string encapsulating the details of the OptionStrikes, 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.

type OptionStrikesResponse added in v1.1.0

type OptionStrikesResponse 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.
}

OptionStrikesResponse 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

  • OptionStrikesRequest.Packed(): Makes the OptionStrikesRequest and unmarshals JSON data into the OptionStrikesResponse 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 OptionStrikesResponse contains valid data.
  • Validate() error: Validates the integrity of the OptionStrikesResponse, ensuring it contains valid strikes data.
  • String() string: Returns a string representation of the OptionStrikesResponse, detailing strikes and their prices.
  • Unpack() ([]OptionStrikes, error): Converts the ordered map of strikes into a slice of OptionStrikes, 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.

func (*OptionStrikesResponse) IsValid added in v1.1.0

func (osr *OptionStrikesResponse) IsValid() bool

IsValid determines the validity of the OptionStrikesResponse 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

  • bool: Indicates whether the OptionStrikesResponse 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 (*OptionStrikesResponse) String added in v1.1.0

func (osr *OptionStrikesResponse) String() string

String returns a string representation of the OptionStrikesResponse 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 OptionStrikesResponse data is necessary for understanding or analysis.

Returns

  • string: The string representation of the OptionStrikesResponse, detailing the strikes and their prices.

Notes

  • This method formats the strikes data into a string, making it easier to visualize the structure and content of the OptionStrikesResponse.

func (*OptionStrikesResponse) UnmarshalJSON added in v1.1.0

func (osr *OptionStrikesResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON custom unmarshals the JSON data into the OptionStrikesResponse struct.

Parameters

  • data []byte: The JSON data to be unmarshaled.

Returns

  • error: An error if unmarshaling fails, nil otherwise.

func (*OptionStrikesResponse) Unpack added in v1.1.0

func (osr *OptionStrikesResponse) Unpack() ([]OptionStrikes, error)

Unpack converts the ordered map of strikes contained within the OptionStrikesResponse into a slice of OptionStrikes. 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

  • []OptionStrikes: A slice of OptionStrikes, each representing a set of strikes and their corresponding expiration date.
  • error: An error if the validation of the OptionStrikesResponse fails or if there are issues parsing the dates.

Notes

  • This method first validates the OptionStrikesResponse to ensure it contains valid data before attempting to unpack the strikes.

func (*OptionStrikesResponse) Validate added in v1.1.0

func (osr *OptionStrikesResponse) Validate() error

Validate assesses the integrity of the OptionStrikesResponse 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 OptionStrikesResponse is invalid, typically due to missing strikes data, or nil if the response is valid.

Notes

  • This method is a fundamental part of the data validation process, ensuring that only responses with valid strikes data are processed.

type OptionsExpirationsResponse

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.
}

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.

func (*OptionsExpirationsResponse) IsValid

func (oer *OptionsExpirationsResponse) IsValid() bool

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.

Notes

  • The parsing of expiration date strings is sensitive to the timezone specified. Incorrect timezone handling may lead to validation errors.

func (*OptionsExpirationsResponse) String

func (oer *OptionsExpirationsResponse) String() string

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.

Returns

  • string: A string that represents the OptionsExpirationsResponse object.

func (*OptionsExpirationsResponse) Unpack

func (oer *OptionsExpirationsResponse) Unpack() ([]time.Time, error)

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.

Notes

  • This method assumes that all expiration times are at 4:00 PM Eastern Time, which may not be accurate for all options contracts.

type StockCandlesResponse

type StockCandlesResponse struct {
	Date   []int64    `json:"t"`              // Date holds UNIX timestamps for each candle.
	Open   []float64  `json:"o"`              // Open holds the opening prices for each candle.
	High   []float64  `json:"h"`              // High holds the highest prices reached in each candle.
	Low    []float64  `json:"l"`              // Low holds the lowest prices reached in each candle.
	Close  []float64  `json:"c"`              // Close holds the closing prices for each candle.
	Volume []int64    `json:"v"`              // Volume represents the trading volume in each candle.
	VWAP   *[]float64 `json:"vwap,omitempty"` // VWAP holds the Volume Weighted Average Price for each candle, optional.
	N      *[]int64   `json:"n,omitempty"`    // N holds the number of trades for each candle, optional.
}

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 Candle.
  • 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.

func CombineStockCandles

func CombineStockCandles(s1, s2 *StockCandlesResponse) (*StockCandlesResponse, error)

CombineStockCandles merges two StockCandlesResponse structs into a single one. It checks if the versions of the two structs are the same, ensures there is no time overlap between them, 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

  • *StockCandlesResponse: The first StockCandlesResponse struct to be combined.
  • *StockCandlesResponse: The second StockCandlesResponse struct to be combined.

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 (*StockCandlesResponse) GetDateRange

func (s *StockCandlesResponse) GetDateRange() (dates.DateRange, error)

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

  • 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 (*StockCandlesResponse) IsValid

func (s *StockCandlesResponse) IsValid() bool

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

  • 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 (*StockCandlesResponse) MarshalJSON

func (s *StockCandlesResponse) MarshalJSON() ([]byte, error)

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

  • []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 (*StockCandlesResponse) PruneOutsideDateRange

func (s *StockCandlesResponse) PruneOutsideDateRange(dr dates.DateRange) error

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 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 (*StockCandlesResponse) String

func (s *StockCandlesResponse) String() string

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

  • 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 (*StockCandlesResponse) UnmarshalJSON

func (s *StockCandlesResponse) UnmarshalJSON(data []byte) error

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.

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 (*StockCandlesResponse) Unpack

func (scr *StockCandlesResponse) Unpack() ([]Candle, error)

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

  • []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 (*StockCandlesResponse) Validate

func (s *StockCandlesResponse) Validate() error

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

  • 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.

type StockEarningsReport

type StockEarningsReport struct {
	Symbol         string    // Symbol represents the stock symbol.
	FiscalYear     int64     // FiscalYear represents the fiscal year of the earnings report.
	FiscalQuarter  int64     // FiscalQuarter represents the fiscal quarter of the earnings report.
	Date           time.Time // Date represents the earnings announcement date.
	ReportDate     time.Time // ReportDate represents the report release date.
	ReportTime     string    // ReportTime represents the time of day the earnings were reported.
	Currency       string    // Currency represents the currency used in the earnings report.
	ReportedEPS    *float64  // ReportedEPS represents the actual earnings per share reported.
	EstimatedEPS   *float64  // EstimatedEPS represents the consensus earnings per share estimate.
	SurpriseEPS    *float64  // SurpriseEPS represents the difference between reported EPS and estimated EPS.
	SurpriseEPSpct *float64  // SurpriseEPSpct represents the percentage difference between reported and estimated EPS.
	Updated        time.Time // Updated represents the last update 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.

func (StockEarningsReport) String

func (ser StockEarningsReport) String() string

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.

type StockEarningsResponse

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.
	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.
	Currency       []string   `json:"currency"`       // Currency represents the currency used in the earnings report.
	ReportedEPS    []*float64 `json:"reportedEPS"`    // ReportedEPS represents the actual earnings per share reported.
	EstimatedEPS   []*float64 `json:"estimatedEPS"`   // EstimatedEPS represents the consensus earnings per share estimate.
	SurpriseEPS    []*float64 `json:"surpriseEPS"`    // SurpriseEPS represents the difference between reported EPS and estimated EPS.
	SurpriseEPSpct []*float64 `json:"surpriseEPSpct"` // SurpriseEPSpct represents the percentage difference between reported and estimated EPS.
	Updated        []int64    `json:"updated"`        // Updated represents the last update time in 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.

func (*StockEarningsResponse) String

func (ser *StockEarningsResponse) String() string

String generates a string representation of the StockEarningsResponse.

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

  • A string representation of the StockEarningsResponse.

func (*StockEarningsResponse) Unpack

func (ser *StockEarningsResponse) Unpack() ([]StockEarningsReport, error)

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

  • []StockEarningsReport: A slice of StockEarningsReport structs constructed from the StockEarningsResponse.
  • error: An error if the unpacking process fails, nil otherwise.

type StockNews added in v0.0.5

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.
	Content         string    // Content is the full text content of the news article.
	Source          string    // Source is the source from which the news article was obtained.
	PublicationDate time.Time // PublicationDate is the publication date of the news article.
}

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.

func (StockNews) String added in v0.0.5

func (sn StockNews) String() string

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

  • string: A formatted 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.

type StockNewsResponse added in v0.0.5

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.
	Content         []string `json:"content"`         // Content contains the full text content of the news articles.
	Source          []string `json:"source"`          // Source contains the sources from which the news articles were obtained.
	PublicationDate []int64  `json:"publicationDate"` // PublicationDate contains the publication dates of the news articles as UNIX timestamps.
	Updated         int64    `json:"updated"`         // Updated contains the timestamp of the last update to the news data.
}

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.

func (*StockNewsResponse) String added in v0.0.5

func (snr *StockNewsResponse) String() string

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.

Returns

  • string: A comprehensive string representation of the StockNewsResponse struct, including details of each news article and any updates.

func (*StockNewsResponse) Unpack added in v0.0.5

func (snr *StockNewsResponse) Unpack() ([]StockNews, error)

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

  • 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.

type StockQuote

type StockQuote struct {
	Symbol    string    // Symbol is the stock symbol.
	Ask       float64   // Ask is the asking price for the stock.
	AskSize   int64     // AskSize is the size (quantity) of the ask.
	Bid       float64   // Bid is the bidding price for the stock.
	BidSize   int64     // BidSize is the size (quantity) of the bid.
	Mid       float64   // Mid is the mid price calculated between the ask and bid prices.
	Last      float64   // Last is the last traded price for the stock.
	Change    *float64  // Change is the price change, can be nil if not applicable.
	ChangePct *float64  // ChangePct is the percentage change in price, can be nil if not applicable.
	High52    *float64  // High52 is the 52-week high price, can be nil if not applicable.
	Low52     *float64  // Low52 is the 52-week low price, can be nil if not applicable.
	Volume    int64     // Volume is the trading volume for the stock.
	Updated   time.Time // Updated is the time when the quote was last updated.
}

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.

func (StockQuote) String

func (sq StockQuote) String() string

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.

Notes

  • 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.

type StockQuotesResponse

type StockQuotesResponse struct {
	Symbol    []string   `json:"symbol"`               // Symbol holds the stock symbols.
	Ask       []float64  `json:"ask"`                  // Ask holds the asking prices for the stocks.
	AskSize   []int64    `json:"askSize"`              // AskSize holds the sizes (quantities) of the asks.
	Bid       []float64  `json:"bid"`                  // Bid holds the bidding prices for the stocks.
	BidSize   []int64    `json:"bidSize"`              // BidSize holds the sizes (quantities) of the bids.
	Mid       []float64  `json:"mid"`                  // Mid holds the mid prices calculated between the ask and bid prices.
	Last      []float64  `json:"last"`                 // Last holds the last traded prices for the stocks.
	Change    []*float64 `json:"change,omitempty"`     // Change holds the price changes, can be nil if not applicable.
	ChangePct []*float64 `json:"changepct,omitempty"`  // ChangePct holds the percentage changes in prices, can be nil if not applicable.
	High52    *[]float64 `json:"52weekHigh,omitempty"` // High52 holds the 52-week high prices, can be nil if not applicable.
	Low52     *[]float64 `json:"52weekLow,omitempty"`  // Low52 holds the 52-week low prices, can be nil if not applicable.
	Volume    []int64    `json:"volume"`               // Volume holds the trading volumes for the stocks.
	Updated   []int64    `json:"updated"`              // Updated holds the UNIX timestamps for when the quotes were last updated.
}

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.

func (*StockQuotesResponse) String

func (sqr *StockQuotesResponse) String() string

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.

Notes

  • 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 (*StockQuotesResponse) Unpack

func (sqr *StockQuotesResponse) Unpack() ([]StockQuote, error)

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.

Returns

  • []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.

type Ticker added in v0.0.5

type Ticker struct {
	Symbol        string    `json:"symbol"`
	Name          string    `json:"name,omitempty"`
	Type          string    `json:"type,omitempty"`
	Currency      string    `json:"currency,omitempty"`
	Exchange      string    `json:"exchange,omitempty"`
	FigiShares    string    `json:"figiShares,omitempty"`
	FigiComposite string    `json:"figiComposite,omitempty"`
	Cik           string    `json:"cik,omitempty"`
	Updated       time.Time `json:"updated,omitempty"`
}

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.

func (Ticker) String added in v0.0.5

func (ti Ticker) String() string

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.

Notes

  • This method is particularly useful when a quick overview of the Ticker's data is needed without accessing each property individually.

type TickersResponse

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.
	Type          []string `json:"type,omitempty"`          // Type contains the types of the stocks. Optional.
	Currency      []string `json:"currency,omitempty"`      // Currency contains the currencies in which the stocks are traded. Optional.
	Exchange      []string `json:"exchange,omitempty"`      // Exchange contains the stock exchanges on which the stocks are listed. Optional.
	FigiShares    []string `json:"figiShares,omitempty"`    // FigiShares contains the FIGI codes for the shares. Optional.
	FigiComposite []string `json:"figiComposite,omitempty"` // FigiComposite contains the composite FIGI codes. Optional.
	Cik           []string `json:"cik,omitempty"`           // Cik contains the Central Index Key (CIK) numbers. Optional.
	Updated       []int64  `json:"updated,omitempty"`       // Updated contains UNIX timestamps of the last updates. Optional.
}

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.

func MapToTickersResponse

func MapToTickersResponse(tickerMap map[string]Ticker) *TickersResponse

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.

Notes

  • This method is particularly useful for converting a collection of dispersed ticker data into a structured and easily manageable format.

func (*TickersResponse) IsValid

func (tr *TickersResponse) IsValid() bool

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

  • 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 (*TickersResponse) MarshalJSON

func (tr *TickersResponse) MarshalJSON() ([]byte, error)

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

  • []byte: The JSON-encoded representation of the TickersResponse.
  • 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 (*TickersResponse) String

func (tr *TickersResponse) String() string

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.

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 (*TickersResponse) ToMap

func (tr *TickersResponse) ToMap() (map[string]Ticker, error)

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.

Notes

  • This method is ideal for scenarios where quick lookup of Ticker information is required.

func (*TickersResponse) UniqueSymbols

func (tr *TickersResponse) UniqueSymbols() ([]string, error)

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

  • []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 (*TickersResponse) Unpack

func (tr *TickersResponse) Unpack() ([]Ticker, error)

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.

Notes

  • This method is essential for applications that require detailed and individualized ticker information for further processing or display.

Jump to

Keyboard shortcuts

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