From 33d3f8fdd397f5cd75d25bc4cf7cc35ea34df19b Mon Sep 17 00:00:00 2001 From: MarketDataApp Date: Wed, 14 Feb 2024 18:04:05 -0300 Subject: [PATCH] updated docs --- .scripts/candles.mdx | 1455 ++++++++++++++++++++++++++ .scripts/gomarkdoc.sh | 6 + .scripts/indices_candles_request.md | 376 +++++++ .scripts/indices_candles_response.md | 1067 +++++++++++++++++++ .scripts/process_markdown.py | 59 +- README.md | 4 +- indices_candles.go | 21 +- models/candle.go | 5 +- models/candle_test.go | 205 ++++ models/indices_candles.go | 3 +- 10 files changed, 3181 insertions(+), 20 deletions(-) create mode 100644 .scripts/candles.mdx create mode 100644 .scripts/indices_candles_request.md create mode 100644 .scripts/indices_candles_response.md create mode 100644 models/candle_test.go diff --git a/.scripts/candles.mdx b/.scripts/candles.mdx new file mode 100644 index 0000000..5cfb744 --- /dev/null +++ b/.scripts/candles.mdx @@ -0,0 +1,1455 @@ +--- +title: Candles +sidebar_position: 1 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + + +Get historical price candles for any supported stock index. + +## Making Requests + +Use [IndicesCandlesRequest](<#IndicesCandlesRequest>) to make requests to the endpoint using any of the three supported execution methods: + +| Method | Execution | Return Type | Description | +|------------|---------------|----------------------------|-----------------------------------------------------------------------------------------------------------| +| **Get** | Direct | `[]Candle` | Directly returns a slice of `[]Candle`, making it straightforward to access each candle individually. | +| **Packed** | Intermediate | `IndicesCandlesResponse` | Returns a packed `IndicesCandlesResponse` object. Must be unpacked to access the `[]Candle` slice. | +| **Raw** | Low-level | `resty.Response` | Provides the raw `resty.Response` for maximum flexibility. Direct access to raw JSON or `*http.Response`. | + + + +## type IndicesCandlesRequest + +```go +type IndicesCandlesRequest struct { + // contains filtered or unexported fields +} +``` + +IndicesCandlesRequest represents a request to the [/v1/indices/candles/]() endpoint. It encapsulates parameters for resolution, symbol, and dates to be used in the request. + +#### Generated By + +- `IndexCandles(client ...*MarketDataClient) *IndicesCandlesRequest` + + IndexCandles creates a new \*IndicesCandlesRequest and returns a pointer to the request allowing for method chaining. + + +#### Setter Methods + +These methods are used to set the parameters of the request. They allow for method chaining by returning a pointer to the \*IndicesCandlesRequest instance they modify. + +- `Resolution(string) *IndicesCandlesRequest` + + Sets the resolution parameter for the request. + +- `Symbol(string) *IndicesCandlesRequest` + + Sets the symbol parameter for the request. + +- `Date(interface{}) *IndicesCandlesRequest` + + Sets the date parameter for the request. + +- `From(interface{}) *IndicesCandlesRequest` + + Sets the 'from' date parameter for the request. + + +#### Execution Methods + +These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint. + +- `Get(...*MarketDataClient) ([]Candle, error)` + + Sends the request, unpacks the response, and returns the data in a user\-friendly format. + +- `Packed(...*MarketDataClient) (*IndicesCandlesResponse, error)` + + Packs the request parameters and sends the request, returning a structured response. + +- `Raw(...*MarketDataClient) (*resty.Response, error)` + + Sends the request as is and returns the raw HTTP response. + + + + + + + + + + +```go +vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2022-01-01").To("2022-01-05").Get() +if err != nil { + println("Error retrieving VIX index candles:", err.Error()) + return +} + +for _, candle := range vix { + fmt.Println(candle) +} +``` + +#### Output + +``` +Candle{Date: 2022-01-03, Open: 17.6, High: 18.54, Low: 16.56, Close: 16.6} +Candle{Date: 2022-01-04, Open: 16.57, High: 17.81, Low: 16.34, Close: 16.91} +Candle{Date: 2022-01-05, Open: 17.07, High: 20.17, Low: 16.58, Close: 19.73} +``` + + + + + + + + +```go +vix, err := IndexCandles().Symbol("VIX").Resolution("D").To("2022-01-05").Countback(3).Packed() +if err != nil { + println("Error retrieving VIX index candles:", err.Error()) + return +} +fmt.Println(vix) +``` + +#### Output + +``` +IndicesCandlesResponse{Time: [1641186000 1641272400 1641358800], Open: [17.6 16.57 17.07], High: [18.54 17.81 20.17], Low: [16.56 16.34 16.58], Close: [16.6 16.91 19.73]} +``` + + + + + + + + +```go +vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2022-01-01").To("2022-01-05").Raw() +if err != nil { + println("Error retrieving VIX index candles:", err.Error()) + return +} +fmt.Println(vix) +``` + +#### Output + +``` +{"s":"ok","t":[1641186000,1641272400,1641358800],"o":[17.6,16.57,17.07],"h":[18.54,17.81,20.17],"l":[16.56,16.34,16.58],"c":[16.6,16.91,19.73]} +``` + + + + + +### func IndexCandles + +```go +func IndexCandles(client ...*MarketDataClient) *IndicesCandlesRequest +``` + +IndexCandles creates a new [IndicesCandlesRequest](<#IndicesCandlesRequest>) and associates it with the provided client. If no client is provided, it uses the default client. This function initializes the request with default parameters for date, resolution, and symbol, and sets the request path based on the predefined endpoints for indices candles. + +#### Parameters + +- `...*MarketDataClient` + + A variadic parameter that can accept zero or one \*MarketDataClient pointer. If no client is provided, the default client is used. + + +#### Returns + +- `*IndicesCandlesRequest` + + A pointer to the newly created \*IndicesCandlesRequest with default parameters and associated client. + + + +### func \(\*IndicesCandlesRequest\) Countback + +```go +func (icr *IndicesCandlesRequest) Countback(q int) *IndicesCandlesRequest +``` + +Countback sets the countback parameter for the IndicesCandlesRequest. It specifies the number of candles to return, counting backwards from the 'to' date. + +#### Parameters + +- `int` + + An int representing the number of candles to return. + + +#### Returns + +- `*IndicesCandlesRequest` + + A pointer to the \*IndicesCandlesRequest instance to allow for method chaining. + + + +### func \(\*IndicesCandlesRequest\) Date + +```go +func (icr *IndicesCandlesRequest) Date(q interface{}) *IndicesCandlesRequest +``` + +Date sets the date parameter for the IndicesCandlesRequest. This method is used to specify the date for which the candle data is requested. It modifies the 'date' field of the IndicesCandlesRequest instance to store the date value. + +#### Parameters + +- `interface{}` + + An interface\{\} representing the date to be set. It can be a string, a time.Time object, a Unix int, or any other type that the underlying dates package method can process. + + +#### Returns + +- `*IndicesCandlesRequest` + + This method returns a pointer to the \*IndicesCandlesRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement. + + +#### Notes + +- If an error occurs while setting the date \(e.g., if the date value is not supported\), the Error field of the request is set with the encountered error, but the method still returns the \*IndicesCandlesRequest instance to allow for further method calls. + + +### func \(\*IndicesCandlesRequest\) From + +```go +func (icr *IndicesCandlesRequest) From(q interface{}) *IndicesCandlesRequest +``` + +From sets the 'from' date parameter for the IndicesCandlesRequest. It configures the starting point of the date range for which the candle data is requested. + +#### Parameters + +- `interface{}` + + An interface\{\} that represents the starting date. It can be a string, a time.Time object, a Unix timestamp or any other type that the underlying dates package can process. + + +#### Returns + +- `*IndicesCandlesRequest` + + A pointer to the \*IndicesCandlesRequest instance to allow for method chaining. + + + +### func \(\*IndicesCandlesRequest\) Get + +```go +func (icr *IndicesCandlesRequest) Get(optionalClients ...*MarketDataClient) ([]models.Candle, error) +``` + +Get sends the [IndicesCandlesRequest](<#IndicesCandlesRequest>), unpacks the \[IndicesCandlesResponse\], and returns a slice of \[IndexCandle\]. It returns an error if the request or unpacking fails. This method is crucial for obtaining the actual candle data from the indices candles request. The method first checks if the IndicesCandlesRequest receiver is nil, which would result in an error as the request cannot be sent. It then proceeds to send the request using the Packed method. Upon receiving the response, it unpacks the data into a slice of IndexCandle using the Unpack method from the response. An optional MarketDataClient can be passed to replace the client used in the request. + +#### Parameters + +- `...*MarketDataClient` + + A variadic parameter that can accept zero or one \*MarketDataClient pointer. If a client is provided, it replaces the current client for this request. + + +#### Returns + +- `[]Candle` + + A slice of \[\]Candle containing the unpacked candle data from the response. + +- `error` + + An error object that indicates a failure in sending the request or unpacking the response. + + + +### func \(\*IndicesCandlesRequest\) Packed + +```go +func (icr *IndicesCandlesRequest) Packed(optionalClients ...*MarketDataClient) (*models.IndicesCandlesResponse, error) +``` + +Packed sends the IndicesCandlesRequest and returns the IndicesCandlesResponse. This method checks if the IndicesCandlesRequest receiver is nil, returning an error if true. An optional MarketDataClient can be passed to replace the client used in the request. Otherwise, it proceeds to send the request and returns the IndicesCandlesResponse along with any error encountered during the request. + +#### Parameters + +- `...*MarketDataClient` + + A variadic parameter that can accept zero or one \*MarketDataClient pointer. If a client is provided, it replaces the current client for this request. + + +#### Returns + +- `*models.IndicesCandlesResponse` + + A pointer to the \*IndicesCandlesResponse obtained from the request. + +- `error` + + An error object that indicates a failure in sending the request. + + + +### func \(\*IndicesCandlesRequest\) Resolution + +```go +func (icr *IndicesCandlesRequest) Resolution(q string) *IndicesCandlesRequest +``` + +Resolution sets the resolution parameter for the [IndicesCandlesRequest](<#IndicesCandlesRequest>). This method is used to specify the granularity of the candle data to be retrieved. It modifies the resolutionParams field of the IndicesCandlesRequest instance to store the resolution value. + +#### Parameters + +- `string` + + A string representing the resolution to be set. Valid resolutions may include values like "D", "5", "1h", etc. See the API's supported resolutions. + + +#### Returns + +- `*IndicesCandlesRequest` + + This method returns a pointer to the \*IndicesCandlesRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement. If the receiver \(\*IndicesCandlesRequest\) is nil, it returns nil to prevent a panic. + + +#### Notes + +- If an error occurs while setting the resolution \(e.g., if the resolution value is not supported\), the Error field of the \*IndicesCandlesRequest is set with the encountered error, but the method still returns the IndicesCandlesRequest instance to allow for further method calls by the caller. + + +### func \(\*IndicesCandlesRequest\) Symbol + +```go +func (icr *IndicesCandlesRequest) Symbol(q string) *IndicesCandlesRequest +``` + +Symbol sets the symbol parameter for the [IndicesCandlesRequest](<#IndicesCandlesRequest>). This method is used to specify the index symbol for which the candle data is requested. + +#### Parameters + +- `string` + + A string representing the index symbol to be set. + + +#### Returns + +- `*IndicesCandlesRequest` + + This method returns a pointer to the \*IndicesCandlesRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement. If the receiver \(\*IndicesCandlesRequest\) is nil, it returns nil to prevent a panic. + + +#### Notes + +- If an error occurs while setting the symbol \(e.g., if the symbol value is not supported\), the Error field of the IndicesCandlesRequest is set with the encountered error, but the method still returns the IndicesCandlesRequest instance to allow for further method calls or error handling by the caller. + + +### func \(\*IndicesCandlesRequest\) To + +```go +func (icr *IndicesCandlesRequest) To(q interface{}) *IndicesCandlesRequest +``` + +To sets the 'to' date parameter for the IndicesCandlesRequest. It configures the ending point of the date range for which the candle data is requested. + +#### Parameters + +- `interface{}` + + An interface\{\} that represents the ending date. It can be a string, a time.Time object, or any other type that the underlying SetTo method can process. + + +#### Returns + +- `*IndicesCandlesRequest` + + A pointer to the \*IndicesCandlesRequest instance to allow for method chaining. + + + + + + + + + + + +## type ByClose + +```go +type ByClose []Candle +``` + +ByClose implements sort.Interface for \[\]Candle based on the Close field. + + + + + + + + + +```go +// 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 + +```go +func (a ByClose) Len() int +``` + + + + +### func \(ByClose\) Less + +```go +func (a ByClose) Less(i, j int) bool +``` + + + + +### func \(ByClose\) Swap + +```go +func (a ByClose) Swap(i, j int) +``` + + + + +## type ByDate + +```go +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. + + + + + + + + + +```go +// 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 + +```go +func (a ByDate) Len() int +``` + + + + +### func \(ByDate\) Less + +```go +func (a ByDate) Less(i, j int) bool +``` + + + + +### func \(ByDate\) Swap + +```go +func (a ByDate) Swap(i, j int) +``` + + + + +## type ByHigh + +```go +type ByHigh []Candle +``` + +ByHigh implements sort.Interface for \[\]Candle based on the High field. + + + + + + + + + +```go +// 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 + +```go +func (a ByHigh) Len() int +``` + + + + +### func \(ByHigh\) Less + +```go +func (a ByHigh) Less(i, j int) bool +``` + + + + +### func \(ByHigh\) Swap + +```go +func (a ByHigh) Swap(i, j int) +``` + + + + +## type ByLow + +```go +type ByLow []Candle +``` + +ByLow implements sort.Interface for \[\]Candle based on the Low field. + + + + + + + + + +```go +// 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 + +```go +func (a ByLow) Len() int +``` + + + + +### func \(ByLow\) Less + +```go +func (a ByLow) Less(i, j int) bool +``` + + + + +### func \(ByLow\) Swap + +```go +func (a ByLow) Swap(i, j int) +``` + + + + +## type ByN + +```go +type ByN []Candle +``` + +ByN implements sort.Interface for \[\]Candle based on the N field. + + + + + + + + + +```go +// 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 + +```go +func (a ByN) Len() int +``` + + + + +### func \(ByN\) Less + +```go +func (a ByN) Less(i, j int) bool +``` + + + + +### func \(ByN\) Swap + +```go +func (a ByN) Swap(i, j int) +``` + + + + +## type ByOpen + +```go +type ByOpen []Candle +``` + +ByOpen implements sort.Interface for \[\]Candle based on the Open field. + + + + + + + + + +```go +// 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 + +```go +func (a ByOpen) Len() int +``` + + + + +### func \(ByOpen\) Less + +```go +func (a ByOpen) Less(i, j int) bool +``` + + + + +### func \(ByOpen\) Swap + +```go +func (a ByOpen) Swap(i, j int) +``` + + + + +## type BySymbol + +```go +type BySymbol []Candle +``` + +BySymbol implements sort.Interface for \[\]Candle based on the Symbol field. Candles are sorted in ascending order. + + + + + + + + + +```go +// 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 + +```go +func (a BySymbol) Len() int +``` + + + + +### func \(BySymbol\) Less + +```go +func (a BySymbol) Less(i, j int) bool +``` + + + + +### func \(BySymbol\) Swap + +```go +func (a BySymbol) Swap(i, j int) +``` + + + + +## type ByVWAP + +```go +type ByVWAP []Candle +``` + +ByVWAP implements sort.Interface for \[\]Candle based on the VWAP field. + + + + + + + + + +```go +// 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 + +```go +func (a ByVWAP) Len() int +``` + + + + +### func \(ByVWAP\) Less + +```go +func (a ByVWAP) Less(i, j int) bool +``` + + + + +### func \(ByVWAP\) Swap + +```go +func (a ByVWAP) Swap(i, j int) +``` + + + + +## type ByVolume + +```go +type ByVolume []Candle +``` + +ByVolume implements sort.Interface for \[\]Candle based on the Volume field. + + + + + + + + + +```go +// 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 + +```go +func (a ByVolume) Len() int +``` + + + + +### func \(ByVolume\) Less + +```go +func (a ByVolume) Less(i, j int) bool +``` + + + + +### func \(ByVolume\) Swap + +```go +func (a ByVolume) Swap(i, j int) +``` + + + + +## type Candle + +```go +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 + +```go +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 + +```go +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 + +```go +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 + +- `other Candle` + + The 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 + +```go +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 + +- `other Candle` + + The 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 + +```go +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 + +```go +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 + +```go +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 + +```go +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 IndicesCandlesResponse + +```go +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 + +```go +func (icr *IndicesCandlesResponse) IsValid() bool +``` + +#### Returns + +- `bool` + + Indicates whether the IndicesCandlesResponse is valid. + + + +### func \(\*IndicesCandlesResponse\) MarshalJSON + +```go +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 + +```go +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 + +```go +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 + +```go +func (icr *IndicesCandlesResponse) Unpack() ([]Candle, error) +``` + +Unpack converts the IndicesCandlesResponse into a slice of IndexCandle. + +#### Returns + +- `[]Candle` + + A slice of [Candle](<#Candle>) that holds the OHLC data. + +- `error` + + An error object that indicates a failure in unpacking the response. + + + +### func \(\*IndicesCandlesResponse\) Validate + +```go +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. + + + + + diff --git a/.scripts/gomarkdoc.sh b/.scripts/gomarkdoc.sh index 14bd759..6e7f6bf 100755 --- a/.scripts/gomarkdoc.sh +++ b/.scripts/gomarkdoc.sh @@ -14,6 +14,9 @@ TEST_FILE="indices_candles_test.go" # Corresponding test file MODELS_DIR="models" # Models directory relative to the project root MODEL_MAIN_FILE="$MODELS_DIR/indices_candles.go" # Main model file MODEL_TEST_FILE="$MODELS_DIR/indices_candles_test.go" # Model test file +CANDLES_MAIN_FILE="$MODELS_DIR/candle.go" # Main model file +CANDLES_TEST_FILE="$MODELS_DIR/candle_test.go" # Main model file + # Step 1: Documentation for main files TMP_DIR=$(create_tmp_dir) @@ -36,6 +39,9 @@ echo "Using new temporary directory for model files: $TMP_DIR" # Copy the model file and its test file to the new temporary directory cp "$SRC_DIR/$MODEL_MAIN_FILE" "$TMP_DIR" cp "$SRC_DIR/$MODEL_TEST_FILE" "$TMP_DIR" +cp "$SRC_DIR/$CANDLES_MAIN_FILE" "$TMP_DIR" +cp "$SRC_DIR/$CANDLES_TEST_FILE" "$TMP_DIR" + # Run gomarkdoc on the new temporary directory for model files gomarkdoc --output "$OUTPUT_DIR/indices_candles_response.md" "$TMP_DIR" diff --git a/.scripts/indices_candles_request.md b/.scripts/indices_candles_request.md new file mode 100644 index 0000000..878fd33 --- /dev/null +++ b/.scripts/indices_candles_request.md @@ -0,0 +1,376 @@ + + + + +Get historical price candles for any supported stock index. + +## Making Requests + +Use [IndicesCandlesRequest](<#IndicesCandlesRequest>) to make requests to the endpoint using any of the three supported execution methods: + +| Method | Execution | Return Type | Description | +|------------|---------------|----------------------------|-----------------------------------------------------------------------------------------------------------| +| **Get** | Direct | `[]Candle` | Directly returns a slice of `[]Candle`, making it straightforward to access each candle individually. | +| **Packed** | Intermediate | `IndicesCandlesResponse` | Returns a packed `IndicesCandlesResponse` object. Must be unpacked to access the `[]Candle` slice. | +| **Raw** | Low-level | `resty.Response` | Provides the raw `resty.Response` for maximum flexibility. Direct access to raw JSON or `*http.Response`. | + + + +## type IndicesCandlesRequest + +```go +type IndicesCandlesRequest struct { + // contains filtered or unexported fields +} +``` + +IndicesCandlesRequest represents a request to the [/v1/indices/candles/]() endpoint. It encapsulates parameters for resolution, symbol, and dates to be used in the request. + +#### Generated By + +- `IndexCandles(client ...*MarketDataClient) *IndicesCandlesRequest` + + IndexCandles creates a new \*IndicesCandlesRequest and returns a pointer to the request allowing for method chaining. + + +#### Setter Methods + +These methods are used to set the parameters of the request. They allow for method chaining by returning a pointer to the \*IndicesCandlesRequest instance they modify. + +- `Resolution(string) *IndicesCandlesRequest` + + Sets the resolution parameter for the request. + +- `Symbol(string) *IndicesCandlesRequest` + + Sets the symbol parameter for the request. + +- `Date(interface{}) *IndicesCandlesRequest` + + Sets the date parameter for the request. + +- `From(interface{}) *IndicesCandlesRequest` + + Sets the 'from' date parameter for the request. + + +#### Execution Methods + +These methods are used to send the request in different formats or retrieve the data. They handle the actual communication with the API endpoint. + +- `Get(...*MarketDataClient) ([]Candle, error)` + + Sends the request, unpacks the response, and returns the data in a user\-friendly format. + +- `Packed(...*MarketDataClient) (*IndicesCandlesResponse, error)` + + Packs the request parameters and sends the request, returning a structured response. + +- `Raw(...*MarketDataClient) (*resty.Response, error)` + + Sends the request as is and returns the raw HTTP response. + + + + + + + + + + +```go +vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2022-01-01").To("2022-01-05").Get() +if err != nil { + println("Error retrieving VIX index candles:", err.Error()) + return +} + +for _, candle := range vix { + fmt.Println(candle) +} +``` + +#### Output + +``` +Candle{Date: 2022-01-03, Open: 17.6, High: 18.54, Low: 16.56, Close: 16.6} +Candle{Date: 2022-01-04, Open: 16.57, High: 17.81, Low: 16.34, Close: 16.91} +Candle{Date: 2022-01-05, Open: 17.07, High: 20.17, Low: 16.58, Close: 19.73} +``` + + + + + + + + +```go +vix, err := IndexCandles().Symbol("VIX").Resolution("D").To("2022-01-05").Countback(3).Packed() +if err != nil { + println("Error retrieving VIX index candles:", err.Error()) + return +} +fmt.Println(vix) +``` + +#### Output + +``` +IndicesCandlesResponse{Time: [1641186000 1641272400 1641358800], Open: [17.6 16.57 17.07], High: [18.54 17.81 20.17], Low: [16.56 16.34 16.58], Close: [16.6 16.91 19.73]} +``` + + + + + + + + +```go +vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2022-01-01").To("2022-01-05").Raw() +if err != nil { + println("Error retrieving VIX index candles:", err.Error()) + return +} +fmt.Println(vix) +``` + +#### Output + +``` +{"s":"ok","t":[1641186000,1641272400,1641358800],"o":[17.6,16.57,17.07],"h":[18.54,17.81,20.17],"l":[16.56,16.34,16.58],"c":[16.6,16.91,19.73]} +``` + + + + + +### func IndexCandles + +```go +func IndexCandles(client ...*MarketDataClient) *IndicesCandlesRequest +``` + +IndexCandles creates a new [IndicesCandlesRequest](<#IndicesCandlesRequest>) and associates it with the provided client. If no client is provided, it uses the default client. This function initializes the request with default parameters for date, resolution, and symbol, and sets the request path based on the predefined endpoints for indices candles. + +#### Parameters + +- `...*MarketDataClient` + + A variadic parameter that can accept zero or one \*MarketDataClient pointer. If no client is provided, the default client is used. + + +#### Returns + +- `*IndicesCandlesRequest` + + A pointer to the newly created \*IndicesCandlesRequest with default parameters and associated client. + + + +### func \(\*IndicesCandlesRequest\) Countback + +```go +func (icr *IndicesCandlesRequest) Countback(q int) *IndicesCandlesRequest +``` + +Countback sets the countback parameter for the IndicesCandlesRequest. It specifies the number of candles to return, counting backwards from the 'to' date. + +#### Parameters + +- `int` + + An int representing the number of candles to return. + + +#### Returns + +- `*IndicesCandlesRequest` + + A pointer to the \*IndicesCandlesRequest instance to allow for method chaining. + + + +### func \(\*IndicesCandlesRequest\) Date + +```go +func (icr *IndicesCandlesRequest) Date(q interface{}) *IndicesCandlesRequest +``` + +Date sets the date parameter for the IndicesCandlesRequest. This method is used to specify the date for which the candle data is requested. It modifies the 'date' field of the IndicesCandlesRequest instance to store the date value. + +#### Parameters + +- `interface{}` + + An interface\{\} representing the date to be set. It can be a string, a time.Time object, a Unix int, or any other type that the underlying dates package method can process. + + +#### Returns + +- `*IndicesCandlesRequest` + + This method returns a pointer to the \*IndicesCandlesRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement. + + +#### Notes + +- If an error occurs while setting the date \(e.g., if the date value is not supported\), the Error field of the request is set with the encountered error, but the method still returns the \*IndicesCandlesRequest instance to allow for further method calls. + + +### func \(\*IndicesCandlesRequest\) From + +```go +func (icr *IndicesCandlesRequest) From(q interface{}) *IndicesCandlesRequest +``` + +From sets the 'from' date parameter for the IndicesCandlesRequest. It configures the starting point of the date range for which the candle data is requested. + +#### Parameters + +- `interface{}` + + An interface\{\} that represents the starting date. It can be a string, a time.Time object, a Unix timestamp or any other type that the underlying dates package can process. + + +#### Returns + +- `*IndicesCandlesRequest` + + A pointer to the \*IndicesCandlesRequest instance to allow for method chaining. + + + +### func \(\*IndicesCandlesRequest\) Get + +```go +func (icr *IndicesCandlesRequest) Get(optionalClients ...*MarketDataClient) ([]models.Candle, error) +``` + +Get sends the [IndicesCandlesRequest](<#IndicesCandlesRequest>), unpacks the \[IndicesCandlesResponse\], and returns a slice of \[IndexCandle\]. It returns an error if the request or unpacking fails. This method is crucial for obtaining the actual candle data from the indices candles request. The method first checks if the IndicesCandlesRequest receiver is nil, which would result in an error as the request cannot be sent. It then proceeds to send the request using the Packed method. Upon receiving the response, it unpacks the data into a slice of IndexCandle using the Unpack method from the response. An optional MarketDataClient can be passed to replace the client used in the request. + +#### Parameters + +- `...*MarketDataClient` + + A variadic parameter that can accept zero or one \*MarketDataClient pointer. If a client is provided, it replaces the current client for this request. + + +#### Returns + +- `[]Candle` + + A slice of \[\]Candle containing the unpacked candle data from the response. + +- `error` + + An error object that indicates a failure in sending the request or unpacking the response. + + + +### func \(\*IndicesCandlesRequest\) Packed + +```go +func (icr *IndicesCandlesRequest) Packed(optionalClients ...*MarketDataClient) (*models.IndicesCandlesResponse, error) +``` + +Packed sends the IndicesCandlesRequest and returns the IndicesCandlesResponse. This method checks if the IndicesCandlesRequest receiver is nil, returning an error if true. An optional MarketDataClient can be passed to replace the client used in the request. Otherwise, it proceeds to send the request and returns the IndicesCandlesResponse along with any error encountered during the request. + +#### Parameters + +- `...*MarketDataClient` + + A variadic parameter that can accept zero or one \*MarketDataClient pointer. If a client is provided, it replaces the current client for this request. + + +#### Returns + +- `*models.IndicesCandlesResponse` + + A pointer to the \*IndicesCandlesResponse obtained from the request. + +- `error` + + An error object that indicates a failure in sending the request. + + + +### func \(\*IndicesCandlesRequest\) Resolution + +```go +func (icr *IndicesCandlesRequest) Resolution(q string) *IndicesCandlesRequest +``` + +Resolution sets the resolution parameter for the [IndicesCandlesRequest](<#IndicesCandlesRequest>). This method is used to specify the granularity of the candle data to be retrieved. It modifies the resolutionParams field of the IndicesCandlesRequest instance to store the resolution value. + +#### Parameters + +- `string` + + A string representing the resolution to be set. Valid resolutions may include values like "D", "5", "1h", etc. See the API's supported resolutions. + + +#### Returns + +- `*IndicesCandlesRequest` + + This method returns a pointer to the \*IndicesCandlesRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement. If the receiver \(\*IndicesCandlesRequest\) is nil, it returns nil to prevent a panic. + + +#### Notes + +- If an error occurs while setting the resolution \(e.g., if the resolution value is not supported\), the Error field of the \*IndicesCandlesRequest is set with the encountered error, but the method still returns the IndicesCandlesRequest instance to allow for further method calls by the caller. + + +### func \(\*IndicesCandlesRequest\) Symbol + +```go +func (icr *IndicesCandlesRequest) Symbol(q string) *IndicesCandlesRequest +``` + +Symbol sets the symbol parameter for the [IndicesCandlesRequest](<#IndicesCandlesRequest>). This method is used to specify the index symbol for which the candle data is requested. + +#### Parameters + +- `string` + + A string representing the index symbol to be set. + + +#### Returns + +- `*IndicesCandlesRequest` + + This method returns a pointer to the \*IndicesCandlesRequest instance it was called on. This allows for method chaining, where multiple setter methods can be called in a single statement. If the receiver \(\*IndicesCandlesRequest\) is nil, it returns nil to prevent a panic. + + +#### Notes + +- If an error occurs while setting the symbol \(e.g., if the symbol value is not supported\), the Error field of the IndicesCandlesRequest is set with the encountered error, but the method still returns the IndicesCandlesRequest instance to allow for further method calls or error handling by the caller. + + +### func \(\*IndicesCandlesRequest\) To + +```go +func (icr *IndicesCandlesRequest) To(q interface{}) *IndicesCandlesRequest +``` + +To sets the 'to' date parameter for the IndicesCandlesRequest. It configures the ending point of the date range for which the candle data is requested. + +#### Parameters + +- `interface{}` + + An interface\{\} that represents the ending date. It can be a string, a time.Time object, or any other type that the underlying SetTo method can process. + + +#### Returns + +- `*IndicesCandlesRequest` + + A pointer to the \*IndicesCandlesRequest instance to allow for method chaining. + + + diff --git a/.scripts/indices_candles_response.md b/.scripts/indices_candles_response.md new file mode 100644 index 0000000..16ddb1c --- /dev/null +++ b/.scripts/indices_candles_response.md @@ -0,0 +1,1067 @@ + + + + + + +## type ByClose + +```go +type ByClose []Candle +``` + +ByClose implements sort.Interface for \[\]Candle based on the Close field. + + + + + + + + + +```go +// 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 + +```go +func (a ByClose) Len() int +``` + + + + +### func \(ByClose\) Less + +```go +func (a ByClose) Less(i, j int) bool +``` + + + + +### func \(ByClose\) Swap + +```go +func (a ByClose) Swap(i, j int) +``` + + + + +## type ByDate + +```go +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. + + + + + + + + + +```go +// 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 + +```go +func (a ByDate) Len() int +``` + + + + +### func \(ByDate\) Less + +```go +func (a ByDate) Less(i, j int) bool +``` + + + + +### func \(ByDate\) Swap + +```go +func (a ByDate) Swap(i, j int) +``` + + + + +## type ByHigh + +```go +type ByHigh []Candle +``` + +ByHigh implements sort.Interface for \[\]Candle based on the High field. + + + + + + + + + +```go +// 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 + +```go +func (a ByHigh) Len() int +``` + + + + +### func \(ByHigh\) Less + +```go +func (a ByHigh) Less(i, j int) bool +``` + + + + +### func \(ByHigh\) Swap + +```go +func (a ByHigh) Swap(i, j int) +``` + + + + +## type ByLow + +```go +type ByLow []Candle +``` + +ByLow implements sort.Interface for \[\]Candle based on the Low field. + + + + + + + + + +```go +// 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 + +```go +func (a ByLow) Len() int +``` + + + + +### func \(ByLow\) Less + +```go +func (a ByLow) Less(i, j int) bool +``` + + + + +### func \(ByLow\) Swap + +```go +func (a ByLow) Swap(i, j int) +``` + + + + +## type ByN + +```go +type ByN []Candle +``` + +ByN implements sort.Interface for \[\]Candle based on the N field. + + + + + + + + + +```go +// 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 + +```go +func (a ByN) Len() int +``` + + + + +### func \(ByN\) Less + +```go +func (a ByN) Less(i, j int) bool +``` + + + + +### func \(ByN\) Swap + +```go +func (a ByN) Swap(i, j int) +``` + + + + +## type ByOpen + +```go +type ByOpen []Candle +``` + +ByOpen implements sort.Interface for \[\]Candle based on the Open field. + + + + + + + + + +```go +// 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 + +```go +func (a ByOpen) Len() int +``` + + + + +### func \(ByOpen\) Less + +```go +func (a ByOpen) Less(i, j int) bool +``` + + + + +### func \(ByOpen\) Swap + +```go +func (a ByOpen) Swap(i, j int) +``` + + + + +## type BySymbol + +```go +type BySymbol []Candle +``` + +BySymbol implements sort.Interface for \[\]Candle based on the Symbol field. Candles are sorted in ascending order. + + + + + + + + + +```go +// 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 + +```go +func (a BySymbol) Len() int +``` + + + + +### func \(BySymbol\) Less + +```go +func (a BySymbol) Less(i, j int) bool +``` + + + + +### func \(BySymbol\) Swap + +```go +func (a BySymbol) Swap(i, j int) +``` + + + + +## type ByVWAP + +```go +type ByVWAP []Candle +``` + +ByVWAP implements sort.Interface for \[\]Candle based on the VWAP field. + + + + + + + + + +```go +// 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 + +```go +func (a ByVWAP) Len() int +``` + + + + +### func \(ByVWAP\) Less + +```go +func (a ByVWAP) Less(i, j int) bool +``` + + + + +### func \(ByVWAP\) Swap + +```go +func (a ByVWAP) Swap(i, j int) +``` + + + + +## type ByVolume + +```go +type ByVolume []Candle +``` + +ByVolume implements sort.Interface for \[\]Candle based on the Volume field. + + + + + + + + + +```go +// 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 + +```go +func (a ByVolume) Len() int +``` + + + + +### func \(ByVolume\) Less + +```go +func (a ByVolume) Less(i, j int) bool +``` + + + + +### func \(ByVolume\) Swap + +```go +func (a ByVolume) Swap(i, j int) +``` + + + + +## type Candle + +```go +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 + +```go +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 + +```go +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 + +```go +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 + +- `other Candle` + + The 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 + +```go +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 + +- `other Candle` + + The 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 + +```go +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 + +```go +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 + +```go +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 + +```go +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 IndicesCandlesResponse + +```go +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 + +```go +func (icr *IndicesCandlesResponse) IsValid() bool +``` + +#### Returns + +- `bool` + + Indicates whether the IndicesCandlesResponse is valid. + + + +### func \(\*IndicesCandlesResponse\) MarshalJSON + +```go +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 + +```go +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 + +```go +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 + +```go +func (icr *IndicesCandlesResponse) Unpack() ([]Candle, error) +``` + +Unpack converts the IndicesCandlesResponse into a slice of IndexCandle. + +#### Returns + +- `[]Candle` + + A slice of [Candle](<#Candle>) that holds the OHLC data. + +- `error` + + An error object that indicates a failure in unpacking the response. + + + +### func \(\*IndicesCandlesResponse\) Validate + +```go +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. + + + diff --git a/.scripts/process_markdown.py b/.scripts/process_markdown.py index 0fd260e..a465b28 100755 --- a/.scripts/process_markdown.py +++ b/.scripts/process_markdown.py @@ -8,6 +8,52 @@ # Add more mappings as needed } +def remove_code_block_delimiters(content, section_title): + """ + Find the section by title and remove the first two occurrences of code block delimiters (```) after the section title. + """ + lines = content.split('\n') + new_lines = [] + in_section = False + code_block_delimiters_removed = 0 + + for line in lines: + if line.strip() == section_title: + in_section = True + elif in_section and line.strip() == '```' and code_block_delimiters_removed < 2: + # Skip the first two occurrences of code block delimiters after the section title + code_block_delimiters_removed += 1 + continue + new_lines.append(line) + # If we've removed two code block delimiters, we can stop checking further lines + if code_block_delimiters_removed == 2: + in_section = False + + return '\n'.join(new_lines) + + +def remove_first_sentence(content): + """Remove the first sentence from the content, searching from top to bottom for a line that begins with 'Package client'.""" + # Split the content into lines + lines = content.split('\n') + new_lines = [] + found = False + + for line in lines: + if not found and line.startswith('Package'): + # Find the first period in the line + period_index = line.find('.') + if period_index != -1: + # Remove up to and including the first period + new_line = line[period_index + 1:].lstrip() + if new_line: # If there's any content left in the line, add it + new_lines.append(new_line) + found = True # Mark as found to stop modifying lines + continue + new_lines.append(line) + + return '\n'.join(new_lines) + def add_anchor_tags(content): """Process the parameters block of text as specified, including 'Setter Methods' and 'Execution Methods'. Insert before and after lines that start with a dash (-).""" @@ -47,9 +93,7 @@ def add_anchor_tags(content): else: anchor = line[line.find('`')+1:line.find('(')].strip() # Insert before and after the line - processed_lines.append(f'') - processed_lines.append(line) - processed_lines.append('') # Ensure an additional new line after closing tag for better readability + processed_lines.append('- ' + f'' +'`' + line[3:] + '') elif line.strip() == '' or line.startswith(' '): processed_lines.append(line) continue @@ -227,11 +271,10 @@ def is_next_non_blank_line_tabitem(start_index, direction): def convert_details_to_tabitem(content): """Convert
tags to with dynamic attributes based on the summary content, and remove the trailing

.""" detail_pattern = re.compile( - r'

(.*?) \((.*?)\)\n

', + r'

(.*?)\n

', re.DOTALL ) - return re.sub(detail_pattern, r'\n', content) - + return re.sub(detail_pattern, r'\n', content) def read_file_content(file_path): """Read and return the content of the file.""" try: @@ -268,6 +311,7 @@ def process_file(file_path, patterns, replacements): content = remove_pattern(content, patterns) if replacements: content = replace_content(content, replacements) + content = remove_first_sentence(content) content = convert_details_to_tabitem(content) # Convert

to and remove trailing

content = add_tabs_tags(content) # Add and tags content = remove_output_blocks(content) # Remove output blocks @@ -276,6 +320,8 @@ def process_file(file_path, patterns, replacements): content = correct_escaping_in_links(content) # Correct escaping in links content = move_all_struct_definitions(content) # Move all struct definitions content = add_anchor_tags(content) + content = remove_code_block_delimiters(content, "## Making Requests") + # content = add_anchor_tags_to_generated_by(content) # Add anchor tags to 'Generated By' sections write_file_content(file_path, content) @@ -328,6 +374,7 @@ def combine_files_into_mdx(file_paths, output_mdx_path): [''] ] replacements = { + '### Making Requests': '## Making Requests', '### Setter Methods': '#### Setter Methods', '### Execution Methods': '#### Execution Methods', '### Methods': '#### Methods', diff --git a/README.md b/README.md index a1fb6f3..c70feb8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@

-# Go SDK for Market Data v1.0 +# Go SDK for Market Data v1.1 ### Access Financial Data with Ease > This is the official Go SDK for [Market Data](https://www.marketdata.app/). It provides developers with a powerful, easy-to-use interface to obtain real-time and historical financial data. Ideal for building financial applications, trading bots, and investment strategies. @@ -12,7 +12,7 @@ [![License](https://img.shields.io/github/license/MarketDataApp/sdk-go.svg)](https://github.com/MarketDataApp/sdk-go/blob/master/LICENSE) ![SDK Version](https://img.shields.io/badge/version-1.0.0-blue.svg) ![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/MarketDataApp/sdk-go) -![Lines of Code](https://img.shields.io/badge/lines_of_code-8339-blue) +![Lines of Code](https://img.shields.io/badge/lines_of_code-8347-blue) #### Connect With The Market Data Community diff --git a/indices_candles.go b/indices_candles.go index 05ba9e0..9675beb 100644 --- a/indices_candles.go +++ b/indices_candles.go @@ -1,12 +1,15 @@ -// Package client includes types and methods to access the Index Candles endpoint. +// Package client includes types and methods to access the Index Candles endpoint. Get historical price candles for any supported stock index. // -// # Making Index Candle Requests +// # Making Requests // -// Get historical price candles for an index. Use [IndicesCandlesRequest] to make requests to the endpoint using any of the three supported execution methods: +// Use [IndicesCandlesRequest] to make requests to the endpoint using any of the three supported execution methods: +// +// | Method | Execution | Return Type | Description | +// |------------|---------------|----------------------------|-----------------------------------------------------------------------------------------------------------| +// | **Get** | Direct | `[]Candle` | Directly returns a slice of `[]Candle`, making it straightforward to access each candle individually. | +// | **Packed** | Intermediate | `IndicesCandlesResponse` | Returns a packed `IndicesCandlesResponse` object. Must be unpacked to access the `[]Candle` slice. | +// | **Raw** | Low-level | `resty.Response` | Provides the raw `resty.Response` for maximum flexibility. Direct access to raw JSON or `*http.Response`. | // -// 1. [IndicesCandlesRequest.Get] returns a slice of [models.Candle]. -// 2. [IndicesCandlesRequest.Packed] will generate a [models.IndicesCandlesResponse] which can then be unpacked using the [models.IndicesCandlesResponse.Unpack] method into [models.Candle]. -// 3. [IndicesCandlesRequest.Raw] will give you access to the raw resty.Response and you can access the raw JSON or the [http.Response] using any of the Resty library's methods. package client import ( @@ -38,9 +41,9 @@ import ( // These methods are used to send the request in different formats or retrieve the data. // They handle the actual communication with the API endpoint. // -// - Raw(...*MarketDataClient) (*resty.Response, error): Sends the request as is and returns the raw HTTP response. -// - Packed(...*MarketDataClient) (*IndicesCandlesResponse, error): Packs the request parameters and sends the request, returning a structured response. // - Get(...*MarketDataClient) ([]Candle, error): Sends the request, unpacks the response, and returns the data in a user-friendly format. +// - Packed(...*MarketDataClient) (*IndicesCandlesResponse, error): Packs the request parameters and sends the request, returning a structured response. +// - Raw(...*MarketDataClient) (*resty.Response, error): Sends the request as is and returns the raw HTTP response. // // [/v1/indices/candles/]: https://www.marketdata.app/docs/api/indices/candles type IndicesCandlesRequest struct { @@ -238,7 +241,7 @@ func (icr *IndicesCandlesRequest) Packed(optionalClients ...*MarketDataClient) ( // // # Returns // -// - []models.IndexCandle: A slice of [IndexCandle] containing the unpacked candle data from the response. +// - []Candle: A slice of []Candle containing the unpacked candle data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. func (icr *IndicesCandlesRequest) Get(optionalClients ...*MarketDataClient) ([]models.Candle, error) { if icr == nil { diff --git a/models/candle.go b/models/candle.go index 7c031f1..c4bac01 100644 --- a/models/candle.go +++ b/models/candle.go @@ -164,6 +164,7 @@ func (c *Candle) UnmarshalJSON(data []byte) error { } // 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. type ByDate []Candle func (a ByDate) Len() int { return len(a) } @@ -252,7 +253,7 @@ func (c Candle) Clone() Candle { // // # Parameters // -// - other Candle: The Candle instance to compare with the current Candle instance. +// - Candle: The other Candle instance to compare with the current Candle instance. // // # Returns // @@ -271,7 +272,7 @@ func (c Candle) IsBefore(other Candle) bool { // // # Parameters // -// - other Candle: The Candle instance to compare with the current Candle instance. +// - Candle: The other Candle instance to compare with the current Candle instance. // // # Returns // diff --git a/models/candle_test.go b/models/candle_test.go new file mode 100644 index 0000000..6f75c0d --- /dev/null +++ b/models/candle_test.go @@ -0,0 +1,205 @@ +package models + +import ( + "fmt" + "sort" + "time" +) + +func ExampleByDate() { + // 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 ExampleByVolume() { + // 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 ExampleByOpen() { + // 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 ExampleByHigh() { + // 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 ExampleByLow() { + // 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 ExampleByClose() { + // 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 ExampleByVWAP() { + // 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 ExampleByN() { + // 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 ExampleBySymbol() { + // 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 +} diff --git a/models/indices_candles.go b/models/indices_candles.go index 096ddbf..1709846 100644 --- a/models/indices_candles.go +++ b/models/indices_candles.go @@ -105,7 +105,8 @@ func (icr *IndicesCandlesResponse) checkForEmptySlices() error { // // # Returns // -// - A slice of IndexCandle, error if there's an inconsistency in the data slices. +// - []Candle: A slice of [Candle] that holds the OHLC data. +// - error: An error object that indicates a failure in unpacking the response. func (icr *IndicesCandlesResponse) Unpack() ([]Candle, error) { if err := icr.checkForEqualSlices(); err != nil { return nil, err