From bfa1fac8ced284c19cac40c2018bdad8cf0f9d82 Mon Sep 17 00:00:00 2001 From: MarketDataApp Date: Tue, 10 Sep 2024 19:14:37 -0300 Subject: [PATCH] Added context support --- .vscode/settings.json | 4 +++- baseRequest.go | 5 +++-- client.go | 15 ++++++++----- client_helper.go | 8 +++---- examples/examples.go | 11 +++++---- examples/examples_indices.go | 7 ++++-- examples/examples_options.go | 16 +++++++++----- examples/examples_stocks.go | 14 +++++++----- examples/examples_v2.go | 17 ++++++++------ funds_candles.go | 43 +++++++++++++++++++++++------------- funds_candles_test.go | 14 ++++++++---- indices_candles.go | 31 ++++++++++++++++++-------- indices_candles_test.go | 15 ++++++++----- indices_quotes.go | 31 ++++++++++++++++++-------- indices_quotes_test.go | 7 ++++-- logging_test.go | 4 +++- markets_status.go | 32 +++++++++++++++++++-------- markets_status_test.go | 9 ++++---- options_chain.go | 33 ++++++++++++++++++--------- options_chain_test.go | 11 +++++---- options_expirations.go | 35 ++++++++++++++++++++--------- options_expirations_test.go | 11 ++++++--- options_lookup.go | 32 +++++++++++++++++++-------- options_lookup_test.go | 11 ++++++--- options_quotes.go | 35 ++++++++++++++++++++--------- options_quotes_test.go | 14 ++++++++---- options_strikes.go | 31 ++++++++++++++++++-------- options_strikes_test.go | 11 ++++++--- stocks_bulkcandles.go | 33 ++++++++++++++++++--------- stocks_bulkcandles_test.go | 14 ++++++++---- stocks_bulkquotes.go | 31 ++++++++++++++++++-------- stocks_bulkquotes_test.go | 14 +++++++----- stocks_candles.go | 35 ++++++++++++++++++++--------- stocks_candles_test.go | 16 +++++++++----- stocks_candles_v2.go | 21 +++++++++++++----- stocks_candles_v2_test.go | 13 ++++++----- stocks_earnings.go | 31 ++++++++++++++++++-------- stocks_earnings_test.go | 10 ++++++--- stocks_news.go | 31 ++++++++++++++++++-------- stocks_news_test.go | 16 +++++++++----- stocks_quotes.go | 31 ++++++++++++++++++-------- stocks_quotes_test.go | 13 +++++++---- stocks_tickers_v2.go | 21 +++++++++++++----- stocks_tickers_v2_test.go | 10 ++++++--- 44 files changed, 584 insertions(+), 263 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 93f8616..e70ea59 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,6 +2,8 @@ "cSpell.words": [ "bulkcandles", "bulkquotes", - "datekey" + "datekey", + "Ratelimit", + "resty" ] } \ No newline at end of file diff --git a/baseRequest.go b/baseRequest.go index 8579fa2..1356b25 100644 --- a/baseRequest.go +++ b/baseRequest.go @@ -41,6 +41,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -265,7 +266,7 @@ func (br *baseRequest) getError() error { // // - *resty.Response: The raw response from the executed request. // - error: An error object if the baseRequest is nil, or if an error occurs during the request execution. -func (request *baseRequest) Raw() (*resty.Response, error) { +func (request *baseRequest) Raw(ctx context.Context) (*resty.Response, error) { if request == nil { return nil, fmt.Errorf("baseRequest is nil") } @@ -274,6 +275,6 @@ func (request *baseRequest) Raw() (*resty.Response, error) { return nil, fmt.Errorf("MarketDataClient is nil") } - response, err := request.client.getRawResponse(request) + response, err := request.client.getRawResponse(ctx, request) return response, err } diff --git a/client.go b/client.go index 3a22a81..4a2e0ac 100644 --- a/client.go +++ b/client.go @@ -34,6 +34,7 @@ import ( "strconv" "sync" "time" + "context" "github.com/go-resty/resty/v2" _ "github.com/joho/godotenv/autoload" @@ -349,7 +350,7 @@ func (c *MarketDataClient) updateRateLimit(resp *resty.Response) { // prepareAndExecuteRequest prepares the request based on the provided baseRequest and executes it. // It returns the response from the server or an error if the request preparation or execution fails. -func (c *MarketDataClient) prepareAndExecuteRequest(br *baseRequest, result interface{}) (*resty.Response, error) { +func (c *MarketDataClient) prepareAndExecuteRequest(ctx context.Context, br *baseRequest, result interface{}) (*resty.Response, error) { // Check for any errors in the base request. if err := br.getError(); err != nil { @@ -385,6 +386,9 @@ func (c *MarketDataClient) prepareAndExecuteRequest(br *baseRequest, result inte return nil, err } + // Use the provided context for the request + req = req.SetContext(ctx) + // Execute the GET request to the specified path. resp, err := req.Get(path) if err != nil { @@ -419,9 +423,9 @@ func (c *MarketDataClient) prepareAndExecuteRequest(br *baseRequest, result inte // // - A pointer to a resty.Response object containing the response from the server. // - An error object if an error occurred during the request execution or if the response contains an error. -func (c *MarketDataClient) getFromRequest(br *baseRequest, result interface{}) (*resty.Response, error) { +func (c *MarketDataClient) getFromRequest(ctx context.Context, br *baseRequest, result interface{}) (*resty.Response, error) { // Execute the prepared request and capture the response and any error. - resp, err := c.prepareAndExecuteRequest(br, result) + resp, err := c.prepareAndExecuteRequest(ctx, br, result) if err != nil { // Return the response and the error if an error occurred during request execution. return resp, err @@ -442,14 +446,15 @@ func (c *MarketDataClient) getFromRequest(br *baseRequest, result interface{}) ( // // # Parameters // +// - ctx: A context.Context object to control the request's lifecycle. // - br: A pointer to a baseRequest object containing the request details. // // # Returns // // - A pointer to a resty.Response object containing the raw response from the server. // - An error object if an error occurred during the request execution. -func (c *MarketDataClient) getRawResponse(br *baseRequest) (*resty.Response, error) { - return c.prepareAndExecuteRequest(br, nil) +func (c *MarketDataClient) getRawResponse(ctx context.Context, br *baseRequest) (*resty.Response, error) { + return c.prepareAndExecuteRequest(ctx, br, nil) } // GetClient checks for an existing instance of MarketDataClient and returns it. diff --git a/client_helper.go b/client_helper.go index 14c95b7..7f75ed6 100644 --- a/client_helper.go +++ b/client_helper.go @@ -50,7 +50,7 @@ const ( ) // getRateLimitConsumed extracts the rate limit consumed value from the response headers. -// It specifically looks for the "X-Api-RateLimit-Consumed" header and attempts to convert its value to an integer. +// It specifically looks for the "X-Api-Ratelimit-Consumed" header and attempts to convert its value to an integer. // // # Parameters // @@ -58,12 +58,12 @@ const ( // // # Returns // -// - int: The integer value of the "X-Api-RateLimit-Consumed" header if present and successfully converted. +// - int: The integer value of the "X-Api-Ratelimit-Consumed" header if present and successfully converted. // - error: An error if the header is missing or if the conversion to an integer fails. func getRateLimitConsumed(resp *resty.Response) (int, error) { - rateLimitConsumedStr := resp.Header().Get("X-Api-RateLimit-Consumed") + rateLimitConsumedStr := resp.Header().Get("X-Api-Ratelimit-Consumed") if rateLimitConsumedStr == "" { - return 0, errors.New("error: missing 'x-Api-RateLimit-Consumed' header") + return 0, errors.New("error: missing 'x-Api-Ratelimit-Consumed' header") } rateLimitConsumed, err := strconv.Atoi(rateLimitConsumedStr) if err != nil { diff --git a/examples/examples.go b/examples/examples.go index 9100f2f..2a84b82 100644 --- a/examples/examples.go +++ b/examples/examples.go @@ -1,13 +1,15 @@ package examples import ( + "context" "fmt" api "github.com/MarketDataApp/sdk-go" ) func RawHttpResponseExample() { - resp, err := api.StockQuote().Symbol("AAPL").Raw() + ctx := context.TODO() + resp, err := api.StockQuote().Symbol("AAPL").Raw(ctx) if err != nil { fmt.Print(err) return @@ -17,7 +19,8 @@ func RawHttpResponseExample() { } func LogExample() { - _, err := api.IndexQuotes().Symbol("VIX").FiftyTwoWeek(true).Get() + ctx := context.TODO() + _, err := api.IndexQuotes().Symbol("VIX").FiftyTwoWeek(true).Get(ctx) if err != nil { fmt.Print(err) return @@ -28,8 +31,8 @@ func LogExample() { } func MarketStatusExample() { - - msr, err := api.MarketStatus().From("2022-01-01").To("2022-01-10").Packed() + ctx := context.TODO() + msr, err := api.MarketStatus().From("2022-01-01").To("2022-01-10").Packed(ctx) if err != nil { fmt.Print(err) return diff --git a/examples/examples_indices.go b/examples/examples_indices.go index 3fb0f4c..1555b35 100644 --- a/examples/examples_indices.go +++ b/examples/examples_indices.go @@ -1,6 +1,7 @@ package examples import ( + "context" "fmt" "time" @@ -8,7 +9,8 @@ import ( ) func IndexQuoteExample() { - iqe, err := api.IndexQuotes().Symbol("VIX").FiftyTwoWeek(true).Packed() + ctx := context.TODO() + iqe, err := api.IndexQuotes().Symbol("VIX").FiftyTwoWeek(true).Packed(ctx) if err != nil { fmt.Print(err) return @@ -32,7 +34,8 @@ func IndexQuoteExample() { func IndexCandlesExample() { oneWeekAgo := time.Now().AddDate(0, 0, -7) - ice, err := api.IndexCandles().Resolution("D").Symbol("VIX").From(oneWeekAgo).To("today").Packed() + ctx := context.TODO() + ice, err := api.IndexCandles().Resolution("D").Symbol("VIX").From(oneWeekAgo).To("today").Packed(ctx) if err != nil { fmt.Print(err) return diff --git a/examples/examples_options.go b/examples/examples_options.go index eb57696..7fb4f69 100644 --- a/examples/examples_options.go +++ b/examples/examples_options.go @@ -1,13 +1,15 @@ package examples import ( + "context" "fmt" api "github.com/MarketDataApp/sdk-go" ) func OptionsChainExample() { - resp, err := api.OptionChain().UnderlyingSymbol("AAPL").Side("call").DTE(60).StrikeLimit(2).Get() + ctx := context.TODO() + resp, err := api.OptionChain().UnderlyingSymbol("AAPL").Side("call").DTE(60).StrikeLimit(2).Get(ctx) if err != nil { fmt.Print(err) return @@ -20,7 +22,8 @@ func OptionsChainExample() { } func OptionsQuotesExample() { - resp, err := api.OptionQuote().OptionSymbol("AAPL250117C00150000").Get() + ctx := context.TODO() + resp, err := api.OptionQuote().OptionSymbol("AAPL250117C00150000").Get(ctx) if err != nil { fmt.Print(err) return @@ -31,7 +34,8 @@ func OptionsQuotesExample() { } func OptionStrikesExample() { - resp, err := api.OptionStrikes().UnderlyingSymbol("AAPL").Get() + ctx := context.TODO() + resp, err := api.OptionStrikes().UnderlyingSymbol("AAPL").Get(ctx) if err != nil { fmt.Print(err) return @@ -43,7 +47,8 @@ func OptionStrikesExample() { } func OptionsLookupExample() { - resp, err := api.OptionLookup().UserInput("AAPL 7/28/2023 200 Call").Get() + ctx := context.TODO() + resp, err := api.OptionLookup().UserInput("AAPL 7/28/2023 200 Call").Get(ctx) if err != nil { fmt.Print(err) return @@ -53,7 +58,8 @@ func OptionsLookupExample() { } func OptionsExpirationsExample() { - resp, err := api.OptionsExpirations().UnderlyingSymbol("AAPL").Strike(200).Get() + ctx := context.TODO() + resp, err := api.OptionsExpirations().UnderlyingSymbol("AAPL").Strike(200).Get(ctx) if err != nil { fmt.Print(err) return diff --git a/examples/examples_stocks.go b/examples/examples_stocks.go index ef83d71..8b422cc 100644 --- a/examples/examples_stocks.go +++ b/examples/examples_stocks.go @@ -1,13 +1,15 @@ package examples import ( + "context" "fmt" api "github.com/MarketDataApp/sdk-go" ) func StockQuoteExample() { - sqe, err := api.StockQuote().Symbol("AAPL").FiftyTwoWeek(true).Packed() + ctx := context.TODO() + sqe, err := api.StockQuote().Symbol("AAPL").FiftyTwoWeek(true).Packed(ctx) if err != nil { fmt.Print(err) return @@ -29,8 +31,8 @@ func StockQuoteExample() { } func StockCandlesExample() { - - sce, err := api.StockCandles().Resolution("1").Symbol("AAPL").From("2023-01-01").To("2023-01-04").Packed() + ctx := context.TODO() + sce, err := api.StockCandles().Resolution("1").Symbol("AAPL").From("2023-01-01").To("2023-01-04").Packed(ctx) if err != nil { fmt.Print(err) return @@ -49,7 +51,8 @@ func StockCandlesExample() { } func StockEarningsExample() { - see, err := api.StockEarnings().Symbol("AAPL").From("2022-01-01").To("2022-12-31").Packed() + ctx := context.TODO() + see, err := api.StockEarnings().Symbol("AAPL").From("2022-01-01").To("2022-12-31").Packed(ctx) if err != nil { fmt.Print(err) return @@ -71,7 +74,8 @@ func StockEarningsExample() { } func StockNewsExample() { - resp, err := api.StockNews().Symbol("AAPL").Get() + ctx := context.TODO() + resp, err := api.StockNews().Symbol("AAPL").Get(ctx) if err != nil { fmt.Print(err) return diff --git a/examples/examples_v2.go b/examples/examples_v2.go index 7bb992f..228938a 100644 --- a/examples/examples_v2.go +++ b/examples/examples_v2.go @@ -1,6 +1,7 @@ package examples import ( + "context" "fmt" "log" "sort" @@ -11,8 +12,8 @@ import ( ) func StockCandlesV2Example() { - - sce, err := api.StockCandlesV2().Resolution("1").Symbol("AAPL").DateKey("2023-01").Packed() + ctx := context.TODO() + sce, err := api.StockCandlesV2().Resolution("1").Symbol("AAPL").DateKey("2023-01").Packed(ctx) if err != nil { fmt.Print(err) return @@ -30,7 +31,8 @@ func StockCandlesV2Example() { } func StocksTickersV2Example() { - tickers, err := api.StockTickers().DateKey("2023-01-05").Packed() + ctx := context.TODO() + tickers, err := api.StockTickers().DateKey("2023-01-05").Packed(ctx) if err != nil { fmt.Print(err) return @@ -41,8 +43,8 @@ func StocksTickersV2Example() { func SaveTickersToCSV(startDate, endDate string, filename string) error { // Initialize the markets client - - marketStatusResp, err := api.MarketStatus().From(startDate).To(endDate).Packed() + ctx := context.TODO() + marketStatusResp, err := api.MarketStatus().From(startDate).To(endDate).Packed(ctx) if err != nil { log.Fatalf("Failed to get market status: %v", err) } @@ -74,7 +76,7 @@ func SaveTickersToCSV(startDate, endDate string, filename string) error { dateStr := date.Format("2006-01-02") // Get the TickersResponse for the date - response, err := tickers.DateKey(dateStr).Packed() + response, err := tickers.DateKey(dateStr).Packed(ctx) if err != nil { return err } @@ -125,7 +127,8 @@ func SaveSingleDayTickersToCSV(date time.Time, filename string) error { dateStr := date.Format("2006-01-02") // Get the TickersResponse for the date - response, err := tickers.DateKey(dateStr).Packed() + ctx := context.TODO() + response, err := tickers.DateKey(dateStr).Packed(ctx) if err != nil { return err } diff --git a/funds_candles.go b/funds_candles.go index 172bb00..80f5afd 100644 --- a/funds_candles.go +++ b/funds_candles.go @@ -12,6 +12,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -199,30 +200,38 @@ func (fcr *FundCandlesRequest) getParams() ([]parameters.MarketDataParam, error) return params, nil } -// Raw executes the FundCandlesRequest and returns the raw *resty.Response. +// Raw executes the FundCandlesRequest with the provided context and returns the raw *resty.Response. // This method returns the raw JSON or *http.Response for further processing without accepting an alternative MarketDataClient. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed request. // - error: An error object if the request fails due to execution errors. -func (fcr *FundCandlesRequest) Raw() (*resty.Response, error) { - return fcr.baseRequest.Raw() +func (fcr *FundCandlesRequest) Raw(ctx context.Context) (*resty.Response, error) { + return fcr.baseRequest.Raw(ctx) } -// Packed sends the FundCandlesRequest and returns the FundCandlesResponse. -//// +// Packed sends the FundCandlesRequest with the provided context and returns the FundCandlesResponse. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *FundCandlesResponse: A pointer to the FundCandlesResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (fcr *FundCandlesRequest) Packed() (*models.FundCandlesResponse, error) { +func (fcr *FundCandlesRequest) Packed(ctx context.Context) (*models.FundCandlesResponse, error) { if fcr == nil { return nil, fmt.Errorf("FundCandlesRequest is nil") } var fcrResp models.FundCandlesResponse - _, err := fcr.baseRequest.client.getFromRequest(fcr.baseRequest, &fcrResp) + _, err := fcr.baseRequest.client.getFromRequest(ctx, fcr.baseRequest, &fcrResp) if err != nil { return nil, err } @@ -230,20 +239,24 @@ func (fcr *FundCandlesRequest) Packed() (*models.FundCandlesResponse, error) { return &fcrResp, nil } -// Get sends the FundCandlesRequest, unpacks the FundCandlesResponse, and returns a slice of StockCandle. +// Get sends the FundCandlesRequest with the provided context, unpacks the FundCandlesResponse, and returns a slice of StockCandle. // It returns an error if the request or unpacking fails. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # 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 (fcr *FundCandlesRequest) Get() ([]models.Candle, error) { +func (fcr *FundCandlesRequest) Get(ctx context.Context) ([]models.Candle, error) { if fcr == nil { return nil, fmt.Errorf("FundCandlesRequest is nil") } // Use the Packed method to make the request - fcrResp, err := fcr.Packed() + fcrResp, err := fcr.Packed(ctx) if err != nil { return nil, err } @@ -259,7 +272,7 @@ func (fcr *FundCandlesRequest) Get() ([]models.Candle, error) { // FundCandles initializes a new FundCandlesRequest with default parameters. // This function prepares a request to fetch stock candle data. It sets up all necessary parameters -// and configurations to make the request ready to be sent. +// and configurations to make the request ready to be sent. // // # Returns // @@ -269,10 +282,10 @@ func FundCandles() *FundCandlesRequest { baseReq.path = endpoints[1]["funds"]["candles"] fcr := &FundCandlesRequest{ - baseRequest: baseReq, - dateParams: ¶meters.DateParams{}, - resolutionParams: ¶meters.ResolutionParams{}, - symbolParams: ¶meters.SymbolParams{}, + baseRequest: baseReq, + dateParams: ¶meters.DateParams{}, + resolutionParams: ¶meters.ResolutionParams{}, + symbolParams: ¶meters.SymbolParams{}, } // Set the date to the current time diff --git a/funds_candles_test.go b/funds_candles_test.go index 750eb02..1270f01 100644 --- a/funds_candles_test.go +++ b/funds_candles_test.go @@ -1,9 +1,13 @@ package client -import "fmt" +import ( + "context" + "fmt" +) func ExampleFundCandlesRequest_raw() { - fcr, err := FundCandles().Resolution("D").Symbol("VFINX").From("2023-01-01").To("2023-01-06").Raw() + ctx := context.TODO() + fcr, err := FundCandles().Resolution("D").Symbol("VFINX").From("2023-01-01").To("2023-01-06").Raw(ctx) if err != nil { fmt.Print(err) return @@ -14,7 +18,8 @@ func ExampleFundCandlesRequest_raw() { } func ExampleFundCandlesRequest_packed() { - fcr, err := FundCandles().Resolution("D").Symbol("VFINX").From("2023-01-01").To("2023-01-06").Packed() + ctx := context.TODO() + fcr, err := FundCandles().Resolution("D").Symbol("VFINX").From("2023-01-01").To("2023-01-06").Packed(ctx) if err != nil { fmt.Print(err) return @@ -25,7 +30,8 @@ func ExampleFundCandlesRequest_packed() { } func ExampleFundCandlesRequest_get() { - fcr, err := FundCandles().Resolution("D").Symbol("VFINX").From("2023-01-01").To("2023-01-06").Get() + ctx := context.TODO() + fcr, err := FundCandles().Resolution("D").Symbol("VFINX").From("2023-01-01").To("2023-01-06").Get(ctx) if err != nil { fmt.Print(err) return diff --git a/indices_candles.go b/indices_candles.go index 0b21547..4571c4a 100644 --- a/indices_candles.go +++ b/indices_candles.go @@ -12,6 +12,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -194,32 +195,40 @@ func (icr *IndicesCandlesRequest) getParams() ([]parameters.MarketDataParam, err return params, nil } -// Raw executes the IndicesCandlesRequest and returns the raw *resty.Response. +// Raw executes the IndicesCandlesRequest with the provided context and returns the raw *resty.Response. // The *resty.Response can be directly used to access the raw JSON or *http.Response for further processing. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed IndicesCandlesRequest. // - error: An error object if the IndicesCandlesRequest is nil or if an error occurs during the request execution. -func (icr *IndicesCandlesRequest) Raw() (*resty.Response, error) { - return icr.baseRequest.Raw() +func (icr *IndicesCandlesRequest) Raw(ctx context.Context) (*resty.Response, error) { + return icr.baseRequest.Raw(ctx) } -// Packed sends the IndicesCandlesRequest and returns the IndicesCandlesResponse. +// Packed sends the IndicesCandlesRequest with the provided context and returns the IndicesCandlesResponse. // This method checks if the IndicesCandlesRequest receiver is nil, returning an error if true. // It proceeds to send the request and returns the IndicesCandlesResponse along with any error encountered during the request. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *models.IndicesCandlesResponse: A pointer to the *IndicesCandlesResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (icr *IndicesCandlesRequest) Packed() (*models.IndicesCandlesResponse, error) { +func (icr *IndicesCandlesRequest) Packed(ctx context.Context) (*models.IndicesCandlesResponse, error) { if icr == nil { return nil, fmt.Errorf("IndicesCandlesRequest is nil") } var icrResp models.IndicesCandlesResponse - _, err := icr.baseRequest.client.getFromRequest(icr.baseRequest, &icrResp) + _, err := icr.baseRequest.client.getFromRequest(ctx, icr.baseRequest, &icrResp) if err != nil { return nil, err } @@ -227,22 +236,26 @@ func (icr *IndicesCandlesRequest) Packed() (*models.IndicesCandlesResponse, erro return &icrResp, nil } -// Get sends the IndicesCandlesRequest, unpacks the IndicesCandlesResponse, and returns a slice of IndexCandle. +// Get sends the IndicesCandlesRequest with the provided context, 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. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.Candle: A slice of []models.Candle containing the unpacked candle data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (icr *IndicesCandlesRequest) Get() ([]models.Candle, error) { +func (icr *IndicesCandlesRequest) Get(ctx context.Context) ([]models.Candle, error) { if icr == nil { return nil, fmt.Errorf("IndicesCandlesRequest is nil") } - icrResp, err := icr.Packed() + icrResp, err := icr.Packed(ctx) if err != nil { return nil, err } diff --git a/indices_candles_test.go b/indices_candles_test.go index ee4e41d..6d5d717 100644 --- a/indices_candles_test.go +++ b/indices_candles_test.go @@ -1,9 +1,13 @@ package client -import "fmt" +import ( + "context" + "fmt" +) func ExampleIndicesCandlesRequest_get() { - vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2024-01-01").To("2024-01-05").Get() + ctx := context.TODO() + vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2024-01-01").To("2024-01-05").Get(ctx) if err != nil { println("Error retrieving VIX index candles:", err.Error()) return @@ -19,7 +23,8 @@ func ExampleIndicesCandlesRequest_get() { } func ExampleIndicesCandlesRequest_packed() { - vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2024-01-01").To("2024-01-05").Packed() + ctx := context.TODO() + vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2024-01-01").To("2024-01-05").Packed(ctx) if err != nil { println("Error retrieving VIX index candles:", err.Error()) return @@ -29,7 +34,8 @@ func ExampleIndicesCandlesRequest_packed() { } func ExampleIndicesCandlesRequest_raw() { - vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2024-01-01").To("2024-01-05").Raw() + ctx := context.TODO() + vix, err := IndexCandles().Symbol("VIX").Resolution("D").From("2024-01-01").To("2024-01-05").Raw(ctx) if err != nil { println("Error retrieving VIX index candles:", err.Error()) return @@ -37,5 +43,4 @@ func ExampleIndicesCandlesRequest_raw() { fmt.Println(vix) // Output: {"s":"ok","t":[1704171600,1704258000,1704344400,1704430800],"o":[13.21,13.38,13.97,14.24],"h":[14.23,14.22,14.2,14.58],"l":[13.1,13.36,13.64,13.29],"c":[13.2,14.04,14.13,13.35]} - } diff --git a/indices_quotes.go b/indices_quotes.go index b307cd6..c874599 100644 --- a/indices_quotes.go +++ b/indices_quotes.go @@ -12,6 +12,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -112,21 +113,25 @@ func (iqr *IndexQuoteRequest) getParams() ([]parameters.MarketDataParam, error) return params, nil } -// Packed sends the IndexQuoteRequest and returns the IndexQuotesResponse. +// Packed sends the IndexQuoteRequest with the provided context and returns the IndexQuotesResponse. // This method checks if the IndexQuoteRequest receiver is nil, returning an error if true. // It proceeds to send the request using the default client and returns the IndexQuotesResponse along with any error encountered during the request. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *models.IndexQuotesResponse: A pointer to the IndexQuotesResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (iqr *IndexQuoteRequest) Packed() (*models.IndexQuotesResponse, error) { +func (iqr *IndexQuoteRequest) Packed(ctx context.Context) (*models.IndexQuotesResponse, error) { if iqr == nil { return nil, fmt.Errorf("IndexQuoteRequest is nil") } var iqrResp models.IndexQuotesResponse - _, err := iqr.baseRequest.client.getFromRequest(iqr.baseRequest, &iqrResp) + _, err := iqr.baseRequest.client.getFromRequest(ctx, iqr.baseRequest, &iqrResp) if err != nil { return nil, err } @@ -134,33 +139,41 @@ func (iqr *IndexQuoteRequest) Packed() (*models.IndexQuotesResponse, error) { return &iqrResp, nil } -// Raw executes the IndexQuoteRequest and returns the raw *resty.Response. +// Raw executes the IndexQuoteRequest with the provided context and returns the raw *resty.Response. // The *resty.Response can be directly used to access the raw JSON or *http.Response for further processing. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed IndexQuoteRequest. // - error: An error object if the IndexQuoteRequest is nil or if an error occurs during the request execution. -func (iqr *IndexQuoteRequest) Raw() (*resty.Response, error) { - return iqr.baseRequest.Raw() +func (iqr *IndexQuoteRequest) Raw(ctx context.Context) (*resty.Response, error) { + return iqr.baseRequest.Raw(ctx) } -// Get sends the IndexQuoteRequest, unpacks the IndexQuotesResponse, and returns a slice of IndexQuote. +// Get sends the IndexQuoteRequest with the provided context, unpacks the IndexQuotesResponse, and returns a slice of IndexQuote. // It returns an error if the request or unpacking fails. This method is crucial for obtaining the actual quote data // from the index quote request. The method first checks if the IndexQuoteRequest receiver is nil, which would // result in an error as the request cannot be sent. It then proceeds to send the request using the default client with the Packed method. // Upon receiving the response, it unpacks the data into a slice of IndexQuote using the Unpack method from the response. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.IndexQuote: A slice of IndexQuote containing the unpacked quote data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (iqr *IndexQuoteRequest) Get() ([]models.IndexQuote, error) { +func (iqr *IndexQuoteRequest) Get(ctx context.Context) ([]models.IndexQuote, error) { if iqr == nil { return nil, fmt.Errorf("IndexQuoteRequest is nil") } - iqrResp, err := iqr.Packed() + iqrResp, err := iqr.Packed(ctx) if err != nil { return nil, err } diff --git a/indices_quotes_test.go b/indices_quotes_test.go index e905bd9..31b648f 100644 --- a/indices_quotes_test.go +++ b/indices_quotes_test.go @@ -1,11 +1,13 @@ package client import ( + "context" "testing" ) func TestIndexQuoteRequest_Packed(t *testing.T) { - iqPacked, err := IndexQuotes().Symbol("VIX").FiftyTwoWeek(true).Packed() + ctx := context.TODO() + iqPacked, err := IndexQuotes().Symbol("VIX").FiftyTwoWeek(true).Packed(ctx) if err != nil { t.Errorf("Failed to get index quotes: %v", err) return @@ -33,7 +35,8 @@ func TestIndexQuoteRequest_Packed(t *testing.T) { } func TestIndexQuoteRequest_Get(t *testing.T) { - iq, err := IndexQuotes().Symbol("VIX").FiftyTwoWeek(false).Get() + ctx := context.TODO() + iq, err := IndexQuotes().Symbol("VIX").FiftyTwoWeek(false).Get(ctx) if err != nil { t.Errorf("Failed to get index quotes: %v", err) return diff --git a/logging_test.go b/logging_test.go index 6f2b33c..6acba73 100644 --- a/logging_test.go +++ b/logging_test.go @@ -1,6 +1,7 @@ package client import ( + "context" "fmt" "log" "net/http" @@ -17,7 +18,8 @@ func TestLogging(t *testing.T) { } client.Debug(false) - sc, err := StockCandles().Resolution("D").Symbol("AAPL").Date("2023-01-03").Raw() + ctx := context.TODO() + sc, err := StockCandles().Resolution("D").Symbol("AAPL").Date("2023-01-03").Raw(ctx) if err != nil { fmt.Print(err) fmt.Print(client) diff --git a/markets_status.go b/markets_status.go index 2b63acd..1f903f7 100644 --- a/markets_status.go +++ b/markets_status.go @@ -12,6 +12,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -43,6 +44,7 @@ import ( // - Get() ([]MarketStatusReport, error): Sends the request, unpacks the response, and returns the data in a user-friendly format. // - Packed() (*MarketStatusResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response. // - Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response. +// // [/v1/markets/status/]: https://www.marketdata.app/docs/api/markets/status type MarketStatusRequest struct { *baseRequest @@ -166,32 +168,40 @@ func (msr *MarketStatusRequest) Countback(q int) *MarketStatusRequest { return msr } -// Raw executes the MarketStatusRequest and returns the raw *resty.Response. +// Raw executes the MarketStatusRequest with the provided context and returns the raw *resty.Response. // The *resty.Response can be directly used to access the raw JSON or *http.Response for further processing. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed MarketStatusRequest. // - error: An error object if the MarketStatusRequest is nil or if an error occurs during the request execution. -func (msr *MarketStatusRequest) Raw() (*resty.Response, error) { - return msr.baseRequest.Raw() +func (msr *MarketStatusRequest) Raw(ctx context.Context) (*resty.Response, error) { + return msr.baseRequest.Raw(ctx) } -// Packed sends the MarketStatusRequest and returns the MarketStatusResponse. +// Packed sends the MarketStatusRequest with the provided context and returns the MarketStatusResponse. // This method checks if the MarketStatusRequest receiver is nil, returning an error if true. // It proceeds to send the request and returns the MarketStatusResponse along with any error encountered during the request. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *models.MarketStatusResponse: A pointer to the *MarketStatusResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (msr *MarketStatusRequest) Packed() (*models.MarketStatusResponse, error) { +func (msr *MarketStatusRequest) Packed(ctx context.Context) (*models.MarketStatusResponse, error) { if msr == nil { return nil, fmt.Errorf("MarketStatusRequest is nil") } var msrResp models.MarketStatusResponse - _, err := msr.baseRequest.client.getFromRequest(msr.baseRequest, &msrResp) + _, err := msr.baseRequest.client.getFromRequest(ctx, msr.baseRequest, &msrResp) if err != nil { return nil, err } @@ -199,23 +209,27 @@ func (msr *MarketStatusRequest) Packed() (*models.MarketStatusResponse, error) { return &msrResp, nil } -// Get sends the MarketStatusRequest, unpacks the MarketStatusResponse, and returns a slice of MarketStatusReport. +// Get sends the MarketStatusRequest with the provided context, unpacks the MarketStatusResponse, and returns a slice of MarketStatusReport. // It returns an error if the request or unpacking fails. This method is crucial for obtaining the actual market status data // from the market status request. The method first checks if the MarketStatusRequest receiver is nil, which would // result in an error as the request cannot be sent. It then proceeds to send the request using the Packed method. // Upon receiving the response, it unpacks the data into a slice of MarketStatusReport using the Unpack method from the response. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.MarketStatusReport: A slice of MarketStatusReport containing the unpacked market status data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (msr *MarketStatusRequest) Get() ([]models.MarketStatusReport, error) { +func (msr *MarketStatusRequest) Get(ctx context.Context) ([]models.MarketStatusReport, error) { if msr == nil { return nil, fmt.Errorf("MarketStatusRequest is nil") } // Use the Packed method to make the request - msrResp, err := msr.Packed() + msrResp, err := msr.Packed(ctx) if err != nil { return nil, err } diff --git a/markets_status_test.go b/markets_status_test.go index a607310..c07c43d 100644 --- a/markets_status_test.go +++ b/markets_status_test.go @@ -1,6 +1,7 @@ package client import ( + "context" "fmt" "testing" ) @@ -47,8 +48,8 @@ func TestMarketStatusRequestSetters(t *testing.T) { } func ExampleMarketStatus_packed() { - - msr, err := MarketStatus().From("2022-01-01").To("2022-01-10").Packed() + ctx := context.TODO() + msr, err := MarketStatus().From("2022-01-01").To("2022-01-10").Packed(ctx) if err != nil { fmt.Print(err) return @@ -59,8 +60,8 @@ func ExampleMarketStatus_packed() { } func ExampleMarketStatus_get() { - - msr, err := MarketStatus().From("2022-01-01").To("2022-01-10").Get() + ctx := context.TODO() + msr, err := MarketStatus().From("2022-01-01").To("2022-01-10").Get(ctx) if err != nil { fmt.Print(err) return diff --git a/options_chain.go b/options_chain.go index e3f040e..2c8a4d5 100644 --- a/options_chain.go +++ b/options_chain.go @@ -13,6 +13,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -61,6 +62,7 @@ import ( // - Get() ([]OptionQuote, error): Sends the request, unpacks the response, and returns the data in a user-friendly format. // - Packed() (*OptionQuotesResponse, error): Packs the request parameters and sends the request, returning a *OptionQuotesResponse response. // - Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response. +// // [/v1/options/chain/]: https://www.marketdata.app/docs/api/options/chain type OptionChainRequest struct { *baseRequest @@ -574,7 +576,6 @@ func (ocr *OptionChainRequest) MaxBid(maxBid float64) *OptionChainRequest { return ocr } - // getParams packs the OptionChainRequest struct into a slice of interface{} and returns it. // This method is used to gather all the parameters set in the OptionChainRequest into a single slice // for easier manipulation and usage in subsequent requests. @@ -591,32 +592,40 @@ func (ocr *OptionChainRequest) getParams() ([]parameters.MarketDataParam, error) return params, nil } -// Raw executes the OptionChainRequest and returns the raw *resty.Response. +// Raw executes the OptionChainRequest with the provided context and returns the raw *resty.Response. // This method uses the default client for this request. The *resty.Response can be directly used to access the raw JSON or *http.Response. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed OptionChainRequest. // - error: An error object if the OptionChainRequest is nil or if an error occurs during the request execution. -func (ocr *OptionChainRequest) Raw() (*resty.Response, error) { - return ocr.baseRequest.Raw() +func (ocr *OptionChainRequest) Raw(ctx context.Context) (*resty.Response, error) { + return ocr.baseRequest.Raw(ctx) } -// Packed sends the OptionChainRequest and returns the OptionChainResponse. +// Packed sends the OptionChainRequest with the provided context and returns the OptionChainResponse. // This method checks if the OptionChainRequest receiver is nil, returning an error if true. // It proceeds to send the request using the default client and returns the OptionChainResponse along with any error encountered during the request. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *models.OptionQuotesResponse: A pointer to the OptionQuotesResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (ocr *OptionChainRequest) Packed() (*models.OptionQuotesResponse, error) { +func (ocr *OptionChainRequest) Packed(ctx context.Context) (*models.OptionQuotesResponse, error) { if ocr == nil { return nil, fmt.Errorf("OptionChainRequest is nil") } var ocrResp models.OptionQuotesResponse - _, err := ocr.baseRequest.client.getFromRequest(ocr.baseRequest, &ocrResp) + _, err := ocr.baseRequest.client.getFromRequest(ctx, ocr.baseRequest, &ocrResp) if err != nil { return nil, err } @@ -624,23 +633,27 @@ func (ocr *OptionChainRequest) Packed() (*models.OptionQuotesResponse, error) { return &ocrResp, nil } -// Get sends the OptionChainRequest, unpacks the OptionChainResponse, and returns a slice of OptionQuote. +// Get sends the OptionChainRequest with the provided context, unpacks the OptionChainResponse, and returns a slice of OptionQuote. // It returns an error if the request or unpacking fails. This method is crucial for obtaining the actual option chain data // from the option chain request. The method first checks if the OptionChainRequest receiver is nil, which would // result in an error as the request cannot be sent. It then proceeds to send the request using the default client. // Upon receiving the response, it unpacks the data into a slice of OptionQuote using the Unpack method from the response. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.OptionQuote: A slice of OptionQuote containing the unpacked option chain data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (ocr *OptionChainRequest) Get() ([]models.OptionQuote, error) { +func (ocr *OptionChainRequest) Get(ctx context.Context) ([]models.OptionQuote, error) { if ocr == nil { return nil, fmt.Errorf("OptionChainRequest is nil") } // Use the Packed method to make the request - ocrResp, err := ocr.Packed() + ocrResp, err := ocr.Packed(ctx) if err != nil { return nil, err } diff --git a/options_chain_test.go b/options_chain_test.go index 2828e1c..5587c37 100644 --- a/options_chain_test.go +++ b/options_chain_test.go @@ -1,12 +1,14 @@ package client import ( + "context" "fmt" "testing" ) func TestOptionChainRequest(t *testing.T) { - resp, err := OptionChain().UnderlyingSymbol("AAPL").Side("call").DTE(60).StrikeLimit(2).Range("itm").Get() + ctx := context.TODO() + resp, err := OptionChain().UnderlyingSymbol("AAPL").Side("call").DTE(60).StrikeLimit(2).Range("itm").Get(ctx) if err != nil { t.Fatalf("Failed to get option chain: %v", err) } @@ -26,8 +28,9 @@ func TestOptionChainRequest(t *testing.T) { } func ExampleOptionChainRequest_packed() { + ctx := context.TODO() resp, err := OptionChain().UnderlyingSymbol("AAPL").Side("call").Date("2022-01-03"). - Month(2).Year(2022).Range("itm").Strike(150).Weekly(false).Monthly(true).Quarterly(false).Nonstandard(false).Packed() + Month(2).Year(2022).Range("itm").Strike(150).Weekly(false).Monthly(true).Nonstandard(false).Packed(ctx) if err != nil { fmt.Println("Error fetching packed option chain:", err) return @@ -36,9 +39,9 @@ func ExampleOptionChainRequest_packed() { // Output: OptionQuotesResponse{OptionSymbol: ["AAPL220121C00150000"], Underlying: ["AAPL"], Expiration: [1642798800], Side: ["call"], Strike: [150], FirstTraded: [1568640600], DTE: [18], Ask: [32.15], AskSize: [2], Bid: [31.8], BidSize: [359], Mid: [31.98], Last: [32], Volume: [3763], OpenInterest: [98804], UnderlyingPrice: [182.01], InTheMoney: [true], Updated: [1641243600], IV: [nil], Delta: [nil], Gamma: [nil], Theta: [nil], Vega: [nil], Rho: [nil], IntrinsicValue: [32.01], ExtrinsicValue: [0.03]} } - func ExampleOptionChainRequest_get() { - resp, err := OptionChain().UnderlyingSymbol("AAPL").Side("call").Date("2022-01-03").DTE(60).StrikeLimit(2).Range("itm").Get() + ctx := context.TODO() + resp, err := OptionChain().UnderlyingSymbol("AAPL").Side("call").Date("2022-01-03").DTE(60).StrikeLimit(2).Range("itm").Get(ctx) if err != nil { fmt.Println("Error fetching option chain:", err) return diff --git a/options_expirations.go b/options_expirations.go index d468f75..5a88e9d 100644 --- a/options_expirations.go +++ b/options_expirations.go @@ -13,6 +13,7 @@ package client import ( + "context" "fmt" "time" @@ -42,6 +43,7 @@ import ( // - Get() ([]time.Time, error): Sends the request, unpacks the response, and returns []time.Time allowing direct-access to the data. // - Packed() (*OptionsExpirationsResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response. // - Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response. +// // [/v1/options/expirations/]: https://www.marketdata.app/docs/api/options/expirations type OptionsExpirationsRequest struct { *baseRequest @@ -124,31 +126,39 @@ func (o *OptionsExpirationsRequest) getParams() ([]parameters.MarketDataParam, e return params, nil } -// Raw executes the OptionsExpirationsRequest and returns the raw *resty.Response. +// Raw executes the OptionsExpirationsRequest with the provided context and returns the raw *resty.Response. // This method uses the default client for the request. The *resty.Response can be used to directly access the raw JSON or *http.Response. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed OptionsExpirationsRequest. // - error: An error object if the OptionsExpirationsRequest is nil or if an error occurs during the request execution. -func (oer *OptionsExpirationsRequest) Raw() (*resty.Response, error) { - return oer.baseRequest.Raw() +func (oer *OptionsExpirationsRequest) Raw(ctx context.Context) (*resty.Response, error) { + return oer.baseRequest.Raw(ctx) } -// Packed sends the OptionsExpirationsRequest and returns the OptionsExpirationsResponse. +// Packed sends the OptionsExpirationsRequest with the provided context and returns the OptionsExpirationsResponse. // This method uses the default client for the request. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *models.OptionsExpirationsResponse: A pointer to the OptionsExpirationsResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (o *OptionsExpirationsRequest) Packed() (*models.OptionsExpirationsResponse, error) { +func (o *OptionsExpirationsRequest) Packed(ctx context.Context) (*models.OptionsExpirationsResponse, error) { if o == nil { return nil, fmt.Errorf("OptionsExpirationsRequest is nil") } var oResp models.OptionsExpirationsResponse - _, err := o.baseRequest.client.getFromRequest(o.baseRequest, &oResp) + _, err := o.baseRequest.client.getFromRequest(ctx, o.baseRequest, &oResp) if err != nil { return nil, err } @@ -156,20 +166,23 @@ func (o *OptionsExpirationsRequest) Packed() (*models.OptionsExpirationsResponse return &oResp, nil } -// Get sends the OptionsExpirationsRequest, unpacks the OptionsExpirationsResponse, and returns a slice of time.Time. -// It returns an error if the request or unpacking fails. -// This method uses the default client for the request. +// Get sends the OptionsExpirationsRequest with the provided context, unpacks the OptionsExpirationsResponse, and returns a slice of time.Time. +// It returns an error if the request or unpacking fails. This method uses the default client for the request. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. // // # Returns // // - []time.Time: A slice of time.Time containing the unpacked options expirations data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (o *OptionsExpirationsRequest) Get() ([]time.Time, error) { +func (o *OptionsExpirationsRequest) Get(ctx context.Context) ([]time.Time, error) { if o == nil { return nil, fmt.Errorf("OptionsExpirationsRequest is nil") } - oResp, err := o.Packed() + oResp, err := o.Packed(ctx) if err != nil { return nil, err } diff --git a/options_expirations_test.go b/options_expirations_test.go index da747c4..8b66e41 100644 --- a/options_expirations_test.go +++ b/options_expirations_test.go @@ -1,9 +1,13 @@ package client -import "fmt" +import ( + "context" + "fmt" +) func ExampleOptionsExpirationsResponse_get() { - resp, err := OptionsExpirations().UnderlyingSymbol("AAPL").Date("2009-02-04").Get() + ctx := context.TODO() + resp, err := OptionsExpirations().UnderlyingSymbol("AAPL").Date("2009-02-04").Get(ctx) if err != nil { fmt.Print(err) return @@ -21,7 +25,8 @@ func ExampleOptionsExpirationsResponse_get() { } func ExampleOptionsExpirationsResponse_packed() { - resp, err := OptionsExpirations().UnderlyingSymbol("AAPL").Date("2009-02-04").Packed() + ctx := context.TODO() + resp, err := OptionsExpirations().UnderlyingSymbol("AAPL").Date("2009-02-04").Packed(ctx) if err != nil { fmt.Print(err) return diff --git a/options_lookup.go b/options_lookup.go index 2529b39..35c4371 100644 --- a/options_lookup.go +++ b/options_lookup.go @@ -13,6 +13,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -39,6 +40,7 @@ import ( // - Get() (string, error): Sends the request, unpacks the response, and returns the data in a user-friendly format. // - Packed() (*OptionLookupResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response. // - Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response. +// // [/v1/options/lookup/]: https://www.marketdata.app/docs/api/options/lookup type OptionLookupRequest struct { *baseRequest @@ -80,30 +82,38 @@ func (o *OptionLookupRequest) getParams() ([]parameters.MarketDataParam, error) return params, nil } -// Raw executes the OptionLookupRequest and returns the raw *resty.Response. +// Raw executes the OptionLookupRequest with the provided context and returns the raw *resty.Response. // The *resty.Response allows access to the raw JSON or *http.Response for further processing. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed OptionLookupRequest. // - error: An error object if the request fails due to being nil, or other execution errors. -func (olr *OptionLookupRequest) Raw() (*resty.Response, error) { - return olr.baseRequest.Raw() +func (olr *OptionLookupRequest) Raw(ctx context.Context) (*resty.Response, error) { + return olr.baseRequest.Raw(ctx) } -// Packed sends the OptionLookupRequest and returns the OptionsLookupResponse. +// Packed sends the OptionLookupRequest with the provided context and returns the OptionsLookupResponse. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. // // # Returns // // - *models.OptionsLookupResponse: A pointer to the OptionsLookupResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (o *OptionLookupRequest) Packed() (*models.OptionLookupResponse, error) { +func (o *OptionLookupRequest) Packed(ctx context.Context) (*models.OptionLookupResponse, error) { if o == nil { return nil, fmt.Errorf("OptionsLookupRequest is nil") } var oResp models.OptionLookupResponse - _, err := o.baseRequest.client.getFromRequest(o.baseRequest, &oResp) + _, err := o.baseRequest.client.getFromRequest(ctx, o.baseRequest, &oResp) if err != nil { return nil, err } @@ -111,20 +121,24 @@ func (o *OptionLookupRequest) Packed() (*models.OptionLookupResponse, error) { return &oResp, nil } -// Get sends the OptionLookupRequest, unpacks the OptionsLookupResponse, and returns the unpacked data as a string. +// Get sends the OptionLookupRequest with the provided context, unpacks the OptionsLookupResponse, and returns the unpacked data as a string. // It returns an error if the request or unpacking fails. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - string: A string containing the unpacked options data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (o *OptionLookupRequest) Get() (string, error) { +func (o *OptionLookupRequest) Get(ctx context.Context) (string, error) { if o == nil { return "", fmt.Errorf("OptionsLookupRequest is nil") } // Use the Packed method to make the request - oResp, err := o.Packed() + oResp, err := o.Packed(ctx) if err != nil { return "", err } diff --git a/options_lookup_test.go b/options_lookup_test.go index 9925983..c367fa0 100644 --- a/options_lookup_test.go +++ b/options_lookup_test.go @@ -1,9 +1,13 @@ package client -import "fmt" +import ( + "context" + "fmt" +) func ExampleOptionLookupRequest_get() { - resp, err := OptionLookup().UserInput("AAPL 7/28/2023 200 Call").Get() + ctx := context.TODO() + resp, err := OptionLookup().UserInput("AAPL 7/28/2023 200 Call").Get(ctx) if err != nil { fmt.Print(err) return @@ -14,7 +18,8 @@ func ExampleOptionLookupRequest_get() { } func ExampleOptionLookupRequest_packed() { - resp, err := OptionLookup().UserInput("AAPL 7/28/2023 200 Call").Packed() + ctx := context.TODO() + resp, err := OptionLookup().UserInput("AAPL 7/28/2023 200 Call").Packed(ctx) if err != nil { fmt.Print(err) return diff --git a/options_quotes.go b/options_quotes.go index eb3a952..a1ea737 100644 --- a/options_quotes.go +++ b/options_quotes.go @@ -13,6 +13,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -42,6 +43,7 @@ import ( // - Get() ([]OptionQuote, error): Sends the request, unpacks the response, and returns the data in a user-friendly format. // - Packed() (*OptionQuotesResponse, error): Returns a struct that contains equal-length slices of primitives. This packed response mirrors Market Data's JSON response. // - Raw() (*resty.Response, error): Sends the request as is and returns the raw HTTP response. +// // [/v1/options/quotes/]: https://www.marketdata.app/docs/api/options/quotes type OptionQuoteRequest struct { *baseRequest @@ -151,31 +153,39 @@ func (oqr *OptionQuoteRequest) getParams() ([]parameters.MarketDataParam, error) return params, nil } -// Raw executes the OptionQuoteRequest and returns the raw *resty.Response. +// Raw executes the OptionQuoteRequest with the provided context and returns the raw *resty.Response. // This method uses the default client for the request. The *resty.Response can be used to access the raw JSON or *http.Response directly. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed request. // - error: An error object if the OptionQuoteRequest is nil or if an error occurs during the request execution. -func (oqr *OptionQuoteRequest) Raw() (*resty.Response, error) { - return oqr.baseRequest.Raw() +func (oqr *OptionQuoteRequest) Raw(ctx context.Context) (*resty.Response, error) { + return oqr.baseRequest.Raw(ctx) } -// Packed sends the OptionQuoteRequest and returns the OptionQuotesResponse. +// Packed sends the OptionQuoteRequest with the provided context and returns the OptionQuotesResponse. // This method uses the default client for the request. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *models.OptionQuotesResponse: A pointer to the OptionQuotesResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (oqr *OptionQuoteRequest) Packed() (*models.OptionQuotesResponse, error) { +func (oqr *OptionQuoteRequest) Packed(ctx context.Context) (*models.OptionQuotesResponse, error) { if oqr == nil { return nil, fmt.Errorf("OptionQuoteRequest is nil") } var oqrResp models.OptionQuotesResponse - _, err := oqr.baseRequest.client.getFromRequest(oqr.baseRequest, &oqrResp) + _, err := oqr.baseRequest.client.getFromRequest(ctx, oqr.baseRequest, &oqrResp) if err != nil { return nil, err } @@ -183,21 +193,24 @@ func (oqr *OptionQuoteRequest) Packed() (*models.OptionQuotesResponse, error) { return &oqrResp, nil } -// Get sends the OptionQuoteRequest, unpacks the OptionQuotesResponse, and returns a slice of OptionQuote. -// It returns an error if the request or unpacking fails. -// This method uses the default client for the request. +// Get sends the OptionQuoteRequest with the provided context, unpacks the OptionQuotesResponse, and returns a slice of OptionQuote. +// It returns an error if the request or unpacking fails. This method uses the default client for the request. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. // // # Returns // // - []models.OptionQuote: A slice of OptionQuote containing the unpacked options quotes data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (oqr *OptionQuoteRequest) Get() ([]models.OptionQuote, error) { +func (oqr *OptionQuoteRequest) Get(ctx context.Context) ([]models.OptionQuote, error) { if oqr == nil { return nil, fmt.Errorf("OptionQuoteRequest is nil") } // Use the Packed method to make the request - oqrResp, err := oqr.Packed() + oqrResp, err := oqr.Packed(ctx) if err != nil { return nil, err } diff --git a/options_quotes_test.go b/options_quotes_test.go index 9ef322b..7e69096 100644 --- a/options_quotes_test.go +++ b/options_quotes_test.go @@ -1,9 +1,13 @@ package client -import "fmt" +import ( + "context" + "fmt" +) func ExampleOptionQuoteRequest_get() { - resp, err := OptionQuote().OptionSymbol("AAPL250117C00150000").Date("2024-02-05").Get() + ctx := context.TODO() + resp, err := OptionQuote().OptionSymbol("AAPL250117C00150000").Date("2024-02-05").Get(ctx) if err != nil { fmt.Print(err) return @@ -16,7 +20,8 @@ func ExampleOptionQuoteRequest_get() { } func ExampleOptionQuoteRequest_packed() { - resp, err := OptionQuote().OptionSymbol("AAPL250117P00150000").Date("2024-02-05").Packed() + ctx := context.TODO() + resp, err := OptionQuote().OptionSymbol("AAPL250117P00150000").Date("2024-02-05").Packed(ctx) if err != nil { fmt.Print(err) return @@ -27,7 +32,8 @@ func ExampleOptionQuoteRequest_packed() { } func ExampleOptionQuoteRequest_raw() { - resp, err := OptionQuote().OptionSymbol("AAPL250117P00150000").Date("2024-02-05").Raw() + ctx := context.TODO() + resp, err := OptionQuote().OptionSymbol("AAPL250117P00150000").Date("2024-02-05").Raw(ctx) if err != nil { fmt.Print(err) return diff --git a/options_strikes.go b/options_strikes.go index 320d75d..2da0a91 100644 --- a/options_strikes.go +++ b/options_strikes.go @@ -13,6 +13,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -115,30 +116,38 @@ func (o *OptionStrikesRequest) getParams() ([]parameters.MarketDataParam, error) return params, nil } -// Raw executes the OptionStrikesRequest and returns the raw *resty.Response. +// Raw executes the OptionStrikesRequest with the provided context and returns the raw *resty.Response. // This method returns the *resty.Response which can be used to directly access the raw JSON or *http.Response. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed OptionStrikesRequest. // - error: An error object if the OptionStrikesRequest is nil or if an error occurs during the request execution. -func (osr *OptionStrikesRequest) Raw() (*resty.Response, error) { - return osr.baseRequest.Raw() +func (osr *OptionStrikesRequest) Raw(ctx context.Context) (*resty.Response, error) { + return osr.baseRequest.Raw(ctx) } -// Packed sends the OptionStrikesRequest and returns the OptionStrikesResponse. +// Packed sends the OptionStrikesRequest with the provided context and returns the OptionStrikesResponse. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. // // # Returns // // - *models.OptionStrikesResponse: A pointer to the OptionStrikesResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (osr *OptionStrikesRequest) Packed() (*models.OptionStrikesResponse, error) { +func (osr *OptionStrikesRequest) Packed(ctx context.Context) (*models.OptionStrikesResponse, error) { if osr == nil { return nil, fmt.Errorf("OptionStrikesRequest is nil") } var osrResp models.OptionStrikesResponse - _, err := osr.baseRequest.client.getFromRequest(osr.baseRequest, &osrResp) + _, err := osr.baseRequest.client.getFromRequest(ctx, osr.baseRequest, &osrResp) if err != nil { return nil, err } @@ -146,20 +155,24 @@ func (osr *OptionStrikesRequest) Packed() (*models.OptionStrikesResponse, error) return &osrResp, nil } -// Get sends the OptionStrikesRequest, unpacks the OptionStrikesResponse, and returns a slice of OptionStrikes. +// Get sends the OptionStrikesRequest with the provided context, unpacks the OptionStrikesResponse, and returns a slice of OptionStrikes. // It returns an error if the request or unpacking fails. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.OptionStrikes: A slice of OptionStrikes containing the unpacked options strikes data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (osr *OptionStrikesRequest) Get() ([]models.OptionStrikes, error) { +func (osr *OptionStrikesRequest) Get(ctx context.Context) ([]models.OptionStrikes, error) { if osr == nil { return nil, fmt.Errorf("OptionStrikesRequest is nil") } // Use the Packed method to make the request - osrResp, err := osr.Packed() + osrResp, err := osr.Packed(ctx) if err != nil { return nil, err } diff --git a/options_strikes_test.go b/options_strikes_test.go index 593084c..92b8de0 100644 --- a/options_strikes_test.go +++ b/options_strikes_test.go @@ -1,9 +1,13 @@ package client -import "fmt" +import ( + "context" + "fmt" +) func ExampleOptionStrikesRequest_get() { - resp, err := OptionStrikes().UnderlyingSymbol("AAPL").Date("2009-02-09").Get() + ctx := context.TODO() + resp, err := OptionStrikes().UnderlyingSymbol("AAPL").Date("2009-02-09").Get(ctx) if err != nil { fmt.Print(err) return @@ -21,7 +25,8 @@ func ExampleOptionStrikesRequest_get() { } func ExampleOptionStrikesRequest_packed() { - resp, err := OptionStrikes().UnderlyingSymbol("AAPL").Date("2009-02-09").Packed() + ctx := context.TODO() + resp, err := OptionStrikes().UnderlyingSymbol("AAPL").Date("2009-02-09").Packed(ctx) if err != nil { fmt.Print(err) return diff --git a/stocks_bulkcandles.go b/stocks_bulkcandles.go index fb4bc6b..f9819fe 100644 --- a/stocks_bulkcandles.go +++ b/stocks_bulkcandles.go @@ -13,6 +13,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -160,30 +161,38 @@ func (bscr *BulkStockCandlesRequest) getParams() ([]parameters.MarketDataParam, return params, nil } -// Raw executes the request and returns the raw *resty.Response. +// Raw executes the request with the provided context and returns the raw *resty.Response. // This method allows for obtaining the raw JSON or *http.Response directly from the executed request. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw response from the executed request. // - error: An error object if the request is nil or if an error occurs during the request execution. -func (bscr *BulkStockCandlesRequest) Raw() (*resty.Response, error) { - return bscr.baseRequest.Raw() +func (bscr *BulkStockCandlesRequest) Raw(ctx context.Context) (*resty.Response, error) { + return bscr.baseRequest.Raw(ctx) } -// Packed sends the BulkStockCandlesRequest and returns the StockCandlesResponse. +// Packed sends the BulkStockCandlesRequest with the provided context and returns the StockCandlesResponse. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. // // # Returns // // - *models.BulkStockCandlesResponse: A pointer to the BulkStockCandlesResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (bscr *BulkStockCandlesRequest) Packed() (*models.BulkStockCandlesResponse, error) { +func (bscr *BulkStockCandlesRequest) Packed(ctx context.Context) (*models.BulkStockCandlesResponse, error) { if bscr == nil { return nil, fmt.Errorf("BulkStockCandlesRequest is nil") } var scrResp models.BulkStockCandlesResponse - _, err := bscr.baseRequest.client.getFromRequest(bscr.baseRequest, &scrResp) + _, err := bscr.baseRequest.client.getFromRequest(ctx, bscr.baseRequest, &scrResp) if err != nil { return nil, err } @@ -191,20 +200,24 @@ func (bscr *BulkStockCandlesRequest) Packed() (*models.BulkStockCandlesResponse, return &scrResp, nil } -// Get sends the BulkStockCandlesRequest, unpacks the StockCandlesResponse, and returns a slice of []Candle. +// Get sends the BulkStockCandlesRequest with the provided context, unpacks the StockCandlesResponse, and returns a slice of []Candle. // It returns an error if the request or unpacking fails. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.Candle: A slice of []Candle containing the unpacked candle data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (bscr *BulkStockCandlesRequest) Get() ([]models.Candle, error) { +func (bscr *BulkStockCandlesRequest) Get(ctx context.Context) ([]models.Candle, error) { if bscr == nil { return nil, fmt.Errorf("BulkStockCandlesRequest is nil") } // Use the Packed method to make the request - scrResp, err := bscr.Packed() + scrResp, err := bscr.Packed(ctx) if err != nil { return nil, err } @@ -217,6 +230,7 @@ func (bscr *BulkStockCandlesRequest) Get() ([]models.Candle, error) { return data, nil } + // BulkStockCandles initializes a new BulkStockCandlesRequest with default parameters. // This function prepares a request to fetch bulk stock candles data. It sets up all necessary parameters // and configurations to make the request ready to be sent. The function accepts a variadic parameter @@ -249,4 +263,3 @@ func BulkStockCandles(client ...*MarketDataClient) *BulkStockCandlesRequest { return bscr } - diff --git a/stocks_bulkcandles_test.go b/stocks_bulkcandles_test.go index 178344f..6e3e1a3 100644 --- a/stocks_bulkcandles_test.go +++ b/stocks_bulkcandles_test.go @@ -1,10 +1,14 @@ package client -import "fmt" +import ( + "context" + "fmt" +) func ExampleBulkStockCandlesRequest_packed() { + ctx := context.TODO() symbols := []string{"AAPL", "META", "MSFT"} - bscr, err := BulkStockCandles().Resolution("D").Symbols(symbols).Date("2024-02-06").Packed() + bscr, err := BulkStockCandles().Resolution("D").Symbols(symbols).Date("2024-02-06").Packed(ctx) if err != nil { fmt.Print(err) return @@ -14,8 +18,9 @@ func ExampleBulkStockCandlesRequest_packed() { } func ExampleBulkStockCandlesRequest_get() { + ctx := context.TODO() symbols := []string{"AAPL", "META", "MSFT"} - bscr, err := BulkStockCandles().Resolution("D").Symbols(symbols).Date("2024-02-06").Get() + bscr, err := BulkStockCandles().Resolution("D").Symbols(symbols).Date("2024-02-06").Get(ctx) if err != nil { fmt.Print(err) return @@ -30,8 +35,9 @@ func ExampleBulkStockCandlesRequest_get() { } func ExampleBulkStockCandlesRequest_raw() { + ctx := context.TODO() symbols := []string{"AAPL", "META", "MSFT"} - bscr, err := BulkStockCandles().Resolution("D").Symbols(symbols).Date("2024-02-06").Raw() + bscr, err := BulkStockCandles().Resolution("D").Symbols(symbols).Date("2024-02-06").Raw(ctx) if err != nil { fmt.Print(err) return diff --git a/stocks_bulkquotes.go b/stocks_bulkquotes.go index 8714b5e..b70d9de 100644 --- a/stocks_bulkquotes.go +++ b/stocks_bulkquotes.go @@ -13,6 +13,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -96,30 +97,38 @@ func (bs *BulkStockQuotesRequest) getParams() ([]parameters.MarketDataParam, err return params, nil } -// Raw executes the request for BulkStockQuotesRequest and returns the raw *resty.Response. +// Raw executes the request for BulkStockQuotesRequest with the provided context and returns the raw *resty.Response. // This method does not allow for an optional MarketDataClient to be passed. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw response from the executed BulkStockQuotesRequest. // - error: An error object if the BulkStockQuotesRequest is nil or if an error occurs during the request execution. -func (bsqr *BulkStockQuotesRequest) Raw() (*resty.Response, error) { - return bsqr.baseRequest.Raw() +func (bsqr *BulkStockQuotesRequest) Raw(ctx context.Context) (*resty.Response, error) { + return bsqr.baseRequest.Raw(ctx) } -// Packed sends the BulkStockQuotesRequest and returns the StockQuotesResponse. +// Packed sends the BulkStockQuotesRequest with the provided context and returns the StockQuotesResponse. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. // // # Returns // // - *models.StockQuotesResponse: A pointer to the StockQuotesResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (bs *BulkStockQuotesRequest) Packed() (*models.StockQuotesResponse, error) { +func (bs *BulkStockQuotesRequest) Packed(ctx context.Context) (*models.StockQuotesResponse, error) { if bs == nil { return nil, fmt.Errorf("BulkStockQuotesRequest is nil") } var bsResp models.StockQuotesResponse - _, err := bs.baseRequest.client.getFromRequest(bs.baseRequest, &bsResp) + _, err := bs.baseRequest.client.getFromRequest(ctx, bs.baseRequest, &bsResp) if err != nil { return nil, err } @@ -127,19 +136,23 @@ func (bs *BulkStockQuotesRequest) Packed() (*models.StockQuotesResponse, error) return &bsResp, nil } -// Get sends the BulkStockQuotesRequest, unpacks the StockQuotesResponse, and returns a slice of StockQuote. +// Get sends the BulkStockQuotesRequest with the provided context, unpacks the StockQuotesResponse, and returns a slice of StockQuote. // It returns an error if the request or unpacking fails. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.StockQuote: A slice of StockQuote containing the unpacked quote data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (bs *BulkStockQuotesRequest) Get() ([]models.StockQuote, error) { +func (bs *BulkStockQuotesRequest) Get(ctx context.Context) ([]models.StockQuote, error) { if bs == nil { return nil, fmt.Errorf("BulkStockQuotesRequest is nil") } - bsResp, err := bs.Packed() + bsResp, err := bs.Packed(ctx) if err != nil { return nil, err } diff --git a/stocks_bulkquotes_test.go b/stocks_bulkquotes_test.go index 4c27c87..64ed3a5 100644 --- a/stocks_bulkquotes_test.go +++ b/stocks_bulkquotes_test.go @@ -1,6 +1,7 @@ package client import ( + "context" "encoding/json" "fmt" "log" @@ -13,8 +14,9 @@ func ExampleBulkStockQuotesRequest_get() { // and perform an actual request to fetch stock quotes for multiple symbols. // Initialize a new BulkStockQuotesRequest and fetch stock quotes for "AAPL", "META", and "MSFT". + ctx := context.TODO() symbols := []string{"AAPL", "META", "MSFT"} - bsqr, err := BulkStockQuotes().Symbols(symbols).Get() + bsqr, err := BulkStockQuotes().Symbols(symbols).Get(ctx) if err != nil { log.Fatalf("Failed to get bulk stock quotes: %v", err) } @@ -33,8 +35,9 @@ func ExampleBulkStockQuotesRequest_packed() { // and perform an actual request to fetch stock quotes for multiple symbols: "AAPL", "META", and "MSFT". // Initialize a new BulkStockQuotesRequest and fetch stock quotes for the specified symbols. + ctx := context.TODO() symbols := []string{"AAPL", "META", "MSFT"} - bsqr, err := BulkStockQuotes().Symbols(symbols).Packed() + bsqr, err := BulkStockQuotes().Symbols(symbols).Packed(ctx) if err != nil { log.Fatalf("Failed to get bulk stock quotes: %v", err) } @@ -54,8 +57,9 @@ func ExampleBulkStockQuotesRequest_raw() { // The response is converted to a raw string and we print out the string at the end of the test. // Initialize a new BulkStockQuotesRequest and fetch stock quotes for "AAPL", "META", and "MSFT". + ctx := context.TODO() symbols := []string{"AAPL", "META", "MSFT"} - bsqr, err := BulkStockQuotes().Symbols(symbols).Raw() + bsqr, err := BulkStockQuotes().Symbols(symbols).Raw(ctx) if err != nil { log.Fatalf("Failed to get bulk stock quotes: %v", err) } @@ -87,9 +91,9 @@ func ExampleBulkStockQuotesRequest_raw() { func TestBulkStockQuotesRequest_packed(t *testing.T) { //client, _ := GetClient() //client.Debug(true) - + ctx := context.TODO() symbols := []string{"AAPL", "META", "MSFT"} - bsqr, err := BulkStockQuotes().Symbols(symbols).Get() + bsqr, err := BulkStockQuotes().Symbols(symbols).Get(ctx) if err != nil { fmt.Print(err) return diff --git a/stocks_candles.go b/stocks_candles.go index 4ea37e2..c77c0c9 100644 --- a/stocks_candles.go +++ b/stocks_candles.go @@ -12,6 +12,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -256,30 +257,38 @@ func (scr *StockCandlesRequest) getParams() ([]parameters.MarketDataParam, error return params, nil } -// Raw executes the StockCandlesRequest and returns the raw *resty.Response. +// Raw executes the StockCandlesRequest with the provided context and returns the raw *resty.Response. // This method returns the raw JSON or *http.Response for further processing without accepting an alternative MarketDataClient. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed request. // - error: An error object if the request fails due to execution errors. -func (scr *StockCandlesRequest) Raw() (*resty.Response, error) { - return scr.baseRequest.Raw() +func (scr *StockCandlesRequest) Raw(ctx context.Context) (*resty.Response, error) { + return scr.baseRequest.Raw(ctx) } -// Packed sends the StockCandlesRequest and returns the StockCandlesResponse. -//// +// Packed sends the StockCandlesRequest with the provided context and returns the StockCandlesResponse. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *StockCandlesResponse: A pointer to the StockCandlesResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (scr *StockCandlesRequest) Packed() (*models.StockCandlesResponse, error) { +func (scr *StockCandlesRequest) Packed(ctx context.Context) (*models.StockCandlesResponse, error) { if scr == nil { return nil, fmt.Errorf("StockCandlesRequest is nil") } var scrResp models.StockCandlesResponse - _, err := scr.baseRequest.client.getFromRequest(scr.baseRequest, &scrResp) + _, err := scr.baseRequest.client.getFromRequest(ctx, scr.baseRequest, &scrResp) if err != nil { return nil, err } @@ -287,20 +296,24 @@ func (scr *StockCandlesRequest) Packed() (*models.StockCandlesResponse, error) { return &scrResp, nil } -// Get sends the StockCandlesRequest, unpacks the StockCandlesResponse, and returns a slice of StockCandle. +// Get sends the StockCandlesRequest with the provided context, unpacks the StockCandlesResponse, and returns a slice of StockCandle. // It returns an error if the request or unpacking fails. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # 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 (scr *StockCandlesRequest) Get() ([]models.Candle, error) { +func (scr *StockCandlesRequest) Get(ctx context.Context) ([]models.Candle, error) { if scr == nil { return nil, fmt.Errorf("StockCandlesRequest is nil") } // Use the Packed method to make the request - scrResp, err := scr.Packed() + scrResp, err := scr.Packed(ctx) if err != nil { return nil, err } @@ -316,7 +329,7 @@ func (scr *StockCandlesRequest) Get() ([]models.Candle, error) { // StockCandles initializes a new StockCandlesRequest with default parameters. // This function prepares a request to fetch stock candle data. It sets up all necessary parameters -// and configurations to make the request ready to be sent. +// and configurations to make the request ready to be sent. // // # Returns // diff --git a/stocks_candles_test.go b/stocks_candles_test.go index 31b6610..068bf18 100644 --- a/stocks_candles_test.go +++ b/stocks_candles_test.go @@ -1,9 +1,13 @@ package client -import "fmt" +import ( + "context" + "fmt" +) func ExampleStockCandlesRequest_raw() { - scr, err := StockCandles().Resolution("4H").Symbol("AAPL").From("2023-01-01").To("2023-01-04").Raw() + ctx := context.TODO() + scr, err := StockCandles().Resolution("4H").Symbol("AAPL").From("2023-01-01").To("2023-01-04").Raw(ctx) if err != nil { fmt.Print(err) return @@ -14,7 +18,8 @@ func ExampleStockCandlesRequest_raw() { } func ExampleStockCandlesRequest_packed() { - scr, err := StockCandles().Resolution("4H").Symbol("AAPL").From("2023-01-01").To("2023-01-04").Packed() + ctx := context.TODO() + scr, err := StockCandles().Resolution("4H").Symbol("AAPL").From("2023-01-01").To("2023-01-04").Packed(ctx) if err != nil { fmt.Print(err) return @@ -25,7 +30,8 @@ func ExampleStockCandlesRequest_packed() { } func ExampleStockCandlesRequest_get() { - scr, err := StockCandles().Resolution("4H").Symbol("AAPL").From("2023-01-01").To("2023-01-04").Get() + ctx := context.TODO() + scr, err := StockCandles().Resolution("4H").Symbol("AAPL").From("2023-01-01").To("2023-01-04").Get(ctx) if err != nil { fmt.Print(err) return @@ -38,4 +44,4 @@ func ExampleStockCandlesRequest_get() { // Candle{Time: 2023-01-03 13:30:00 -05:00, Open: 124.67, High: 125.42, Low: 124.17, Close: 125.05, Volume: 30727802} // Candle{Time: 2023-01-04 09:30:00 -05:00, Open: 126.89, High: 128.66, Low: 125.08, Close: 127.26, Volume: 49096197} // Candle{Time: 2023-01-04 13:30:00 -05:00, Open: 127.26, High: 127.87, Low: 125.28, Close: 126.38, Volume: 28870578} -} \ No newline at end of file +} diff --git a/stocks_candles_v2.go b/stocks_candles_v2.go index 517039e..496058c 100644 --- a/stocks_candles_v2.go +++ b/stocks_candles_v2.go @@ -1,6 +1,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -60,19 +61,23 @@ func (cr *StockCandlesRequestV2) getParams() ([]parameters.MarketDataParam, erro return params, nil } -// Packed sends the StockCandlesRequestV2 and returns the StockCandlesResponse. +// Packed sends the StockCandlesRequestV2 with the provided context and returns the StockCandlesResponse. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. // // # Returns // // - *models.StockCandlesResponse: A pointer to the StockCandlesResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (scrV2 *StockCandlesRequestV2) Packed() (*models.StockCandlesResponse, error) { +func (scrV2 *StockCandlesRequestV2) Packed(ctx context.Context) (*models.StockCandlesResponse, error) { if scrV2 == nil { return nil, fmt.Errorf("StockCandlesRequestV2 is nil") } var scrResp models.StockCandlesResponse - _, err := scrV2.baseRequest.client.getFromRequest(scrV2.baseRequest, &scrResp) + _, err := scrV2.baseRequest.client.getFromRequest(ctx, scrV2.baseRequest, &scrResp) if err != nil { return nil, err } @@ -80,20 +85,24 @@ func (scrV2 *StockCandlesRequestV2) Packed() (*models.StockCandlesResponse, erro return &scrResp, nil } -// Get sends the StockCandlesRequestV2, unpacks the StockCandlesResponse, and returns a slice of StockCandle. +// Get sends the StockCandlesRequestV2 with the provided context, unpacks the StockCandlesResponse, and returns a slice of StockCandle. // It returns an error if the request or unpacking fails. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.StockCandle: A slice of []Candle containing the unpacked candle data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (scrV2 *StockCandlesRequestV2) Get() ([]models.Candle, error) { +func (scrV2 *StockCandlesRequestV2) Get(ctx context.Context) ([]models.Candle, error) { if scrV2 == nil { return nil, fmt.Errorf("StockCandlesRequestV2 is nil") } // Use the Packed method to make the request - scrResp, err := scrV2.Packed() + scrResp, err := scrV2.Packed(ctx) if err != nil { return nil, err } diff --git a/stocks_candles_v2_test.go b/stocks_candles_v2_test.go index 48e09c8..feb95b0 100644 --- a/stocks_candles_v2_test.go +++ b/stocks_candles_v2_test.go @@ -1,10 +1,13 @@ package client -import "fmt" +import ( + "context" + "fmt" +) func ExampleStockCandlesRequestV2_get() { - - scr2, err := StockCandlesV2().Resolution("D").Symbol("AAPL").DateKey("2023-01").Get() + ctx := context.TODO() + scr2, err := StockCandlesV2().Resolution("D").Symbol("AAPL").DateKey("2023-01").Get(ctx) if err != nil { fmt.Print(err) return @@ -36,8 +39,8 @@ func ExampleStockCandlesRequestV2_get() { } func ExampleStockCandlesRequestV2_packed() { - - scr2, err := StockCandlesV2().Resolution("D").Symbol("AAPL").DateKey("2023-01").Packed() + ctx := context.TODO() + scr2, err := StockCandlesV2().Resolution("D").Symbol("AAPL").DateKey("2023-01").Packed(ctx) if err != nil { fmt.Print(err) return diff --git a/stocks_earnings.go b/stocks_earnings.go index 8e5dbfe..a2cdb35 100644 --- a/stocks_earnings.go +++ b/stocks_earnings.go @@ -13,6 +13,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -177,30 +178,38 @@ func (ser *StockEarningsRequest) getParams() ([]parameters.MarketDataParam, erro return params, nil } -// Raw executes the StockEarningsRequest and returns the raw *resty.Response. +// Raw executes the StockEarningsRequest with the provided context and returns the raw *resty.Response. // The *resty.Response can be used to access the raw JSON or *http.Response directly. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw response from the executed StockEarningsRequest. // - error: An error object if the StockEarningsRequest is nil, the MarketDataClient is nil, or if an error occurs during the request execution. -func (ser *StockEarningsRequest) Raw() (*resty.Response, error) { - return ser.baseRequest.Raw() +func (ser *StockEarningsRequest) Raw(ctx context.Context) (*resty.Response, error) { + return ser.baseRequest.Raw(ctx) } -// Packed sends the StockEarningsRequest and returns the StockEarningsResponse. +// Packed sends the StockEarningsRequest with the provided context and returns the StockEarningsResponse. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. // // # Returns // // - *models.StockEarningsResponse: A pointer to the StockEarningsResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (ser *StockEarningsRequest) Packed() (*models.StockEarningsResponse, error) { +func (ser *StockEarningsRequest) Packed(ctx context.Context) (*models.StockEarningsResponse, error) { if ser == nil { return nil, fmt.Errorf("StockEarningsRequest is nil") } var serResp models.StockEarningsResponse - _, err := ser.baseRequest.client.getFromRequest(ser.baseRequest, &serResp) + _, err := ser.baseRequest.client.getFromRequest(ctx, ser.baseRequest, &serResp) if err != nil { return nil, err } @@ -208,19 +217,23 @@ func (ser *StockEarningsRequest) Packed() (*models.StockEarningsResponse, error) return &serResp, nil } -// Get sends the StockEarningsRequest, unpacks the StockEarningsResponse, and returns a slice of StockEarningsReport. +// Get sends the StockEarningsRequest with the provided context, unpacks the StockEarningsResponse, and returns a slice of StockEarningsReport. // It returns an error if the request or unpacking fails. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.StockEarningsReport: A slice of StockEarningsReport containing the unpacked earnings data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (ser *StockEarningsRequest) Get() ([]models.StockEarningsReport, error) { +func (ser *StockEarningsRequest) Get(ctx context.Context) ([]models.StockEarningsReport, error) { if ser == nil { return nil, fmt.Errorf("StockEarningsRequest is nil") } - serResp, err := ser.Packed() + serResp, err := ser.Packed(ctx) if err != nil { return nil, err } diff --git a/stocks_earnings_test.go b/stocks_earnings_test.go index 2caf52c..d606176 100644 --- a/stocks_earnings_test.go +++ b/stocks_earnings_test.go @@ -1,13 +1,15 @@ package client import ( + "context" "fmt" "regexp" "time" ) func ExampleStockEarningsRequest_raw() { - ser, err := StockEarnings().Symbol("AAPL").From("2022-01-01").To("2022-01-31").Raw() + ctx := context.TODO() + ser, err := StockEarnings().Symbol("AAPL").From("2022-01-01").To("2022-01-31").Raw(ctx) if err != nil { fmt.Print(err) return @@ -25,7 +27,8 @@ func ExampleStockEarningsRequest_raw() { } func ExampleStockEarningsRequest_packed() { - ser, err := StockEarnings().Symbol("AAPL").From("2022-01-01").To("2022-01-31").Packed() + ctx := context.TODO() + ser, err := StockEarnings().Symbol("AAPL").From("2022-01-01").To("2022-01-31").Packed(ctx) if err != nil { fmt.Print(err) return @@ -38,7 +41,8 @@ func ExampleStockEarningsRequest_packed() { } func ExampleStockEarningsRequest_get() { - ser, err := StockEarnings().Symbol("AAPL").From("2022-01-01").To("2022-01-31").Get() + ctx := context.TODO() + ser, err := StockEarnings().Symbol("AAPL").From("2022-01-01").To("2022-01-31").Get(ctx) if err != nil { fmt.Print(err) return diff --git a/stocks_news.go b/stocks_news.go index 0979618..eccadd3 100644 --- a/stocks_news.go +++ b/stocks_news.go @@ -13,6 +13,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -162,30 +163,38 @@ func (snr *StockNewsRequest) getParams() ([]parameters.MarketDataParam, error) { return params, nil } -// Raw executes the StockNewsRequest and returns the raw *resty.Response. +// Raw executes the StockNewsRequest with the provided context and returns the raw *resty.Response. // This method retrieves the raw HTTP response for further processing. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed request. // - error: An error object if the request fails due to being nil or other execution errors. -func (snr *StockNewsRequest) Raw() (*resty.Response, error) { - return snr.baseRequest.Raw() +func (snr *StockNewsRequest) Raw(ctx context.Context) (*resty.Response, error) { + return snr.baseRequest.Raw(ctx) } -// Packed sends the StockNewsRequest and returns the StockNewsResponse. +// Packed sends the StockNewsRequest with the provided context and returns the StockNewsResponse. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. // // # Returns // // - *models.StockNewsResponse: A pointer to the StockNewsResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (snr *StockNewsRequest) Packed() (*models.StockNewsResponse, error) { +func (snr *StockNewsRequest) Packed(ctx context.Context) (*models.StockNewsResponse, error) { if snr == nil { return nil, fmt.Errorf("StockNewsRequest is nil") } var snrResp models.StockNewsResponse - _, err := snr.baseRequest.client.getFromRequest(snr.baseRequest, &snrResp) + _, err := snr.baseRequest.client.getFromRequest(ctx, snr.baseRequest, &snrResp) if err != nil { return nil, err } @@ -193,20 +202,24 @@ func (snr *StockNewsRequest) Packed() (*models.StockNewsResponse, error) { return &snrResp, nil } -// Get sends the StockNewsRequest, unpacks the StockNewsResponse, and returns a slice of StockNews. +// Get sends the StockNewsRequest with the provided context, unpacks the StockNewsResponse, and returns a slice of StockNews. // It returns an error if the request or unpacking fails. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.StockNews: A slice of StockNews containing the unpacked news data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (snr *StockNewsRequest) Get() ([]models.StockNews, error) { +func (snr *StockNewsRequest) Get(ctx context.Context) ([]models.StockNews, error) { if snr == nil { return nil, fmt.Errorf("StockNewsRequest is nil") } // Use the Packed method to make the request - snrResp, err := snr.Packed() + snrResp, err := snr.Packed(ctx) if err != nil { return nil, err } diff --git a/stocks_news_test.go b/stocks_news_test.go index 329a4b4..6fa2e57 100644 --- a/stocks_news_test.go +++ b/stocks_news_test.go @@ -1,9 +1,13 @@ package client -import "fmt" +import ( + "context" + "fmt" +) func ExampleStockNewsRequest_get() { - resp, err := StockNews().Symbol("AAPL").Date("2023-01-01").Get() + ctx := context.TODO() + resp, err := StockNews().Symbol("AAPL").Date("2023-01-01").Get(ctx) if err != nil { fmt.Print(err) return @@ -22,7 +26,8 @@ func ExampleStockNewsRequest_get() { } func ExampleStockNewsRequest_packed() { - resp, err := StockNews().Symbol("AAPL").Date("2023-01-01").Packed() + ctx := context.TODO() + resp, err := StockNews().Symbol("AAPL").Date("2023-01-01").Packed(ctx) if err != nil { fmt.Print(err) return @@ -33,7 +38,8 @@ func ExampleStockNewsRequest_packed() { } func ExampleStockNewsRequest_raw() { - resp, err := StockNews().Symbol("AAPL").Date("2023-01-01").Raw() + ctx := context.TODO() + resp, err := StockNews().Symbol("AAPL").Date("2023-01-01").Raw(ctx) if err != nil { fmt.Print(err) return @@ -41,4 +47,4 @@ func ExampleStockNewsRequest_raw() { fmt.Println(resp) // Output: {"s":"ok","symbol":["AAPL","AAPL","AAPL","AAPL","AAPL","AAPL"],"headline":["Lessons Learned From Visa and Mastercard in a Year of Crypto News","Down 28% in 2022, Is Apple Stock a Buy for 2023?","80% of Warren Buffett's Portfolio Is Invested in These 7 Stocks as 2023 Begins","2 Beaten-Down Warren Buffett Stocks to Buy in 2023","2023 Dividend Growth Portfolio Review And Look Ahead","The Fall Of Tesla And The Rise of Exxon Amid The Energy Crisis"],"content":["How Visa and Mastercard fared in a year dominated by crypto news. Why fortress-like balance sheets will be an even bigger asset in the new year. To catch full episodes of all The Motley Fool's free podcasts, check out our podcast center.

Continue reading","Apple (NASDAQ: AAPL) has benefited from robust consumer demand and hopes that easing supply chain constraints will boost the tech giant's prospects. *Stock prices used were the afternoon prices of Dec.

Continue reading","Two of these stocks were especially big winners for Buffett in 2022.","These are high-conviction stocks for the Oracle of Omaha but they're trading at knocked-down prices.

Continue reading","I review my current holdings and sectors in the portfolio and how it has changed over the years. See my income projections for 2023 and potential pitfalls.","Growth stocks have been thoroughly hammered this year, with high inflation and rising interest rates pinching growth equities of all stripes. But few stocks exemplify the dramatic shake-up at the top, like leading EV maker Tesla Inc. (NASDAQ: TSLA). TSLA stock has tanked 69.5% in the year-to-date, wiping off a staggering $877 billion from its market cap. In comparison, the S&P 500 has declined a more modest 19.7% over the timeframe. Tesla has gone from being the fifth most valuable public company and now ranks just thirteenth with a market cap of $385 billion.

Tesla’s woes are well documented, including Musk's Twitter takeover and related distractions; worries that high inflation and rising interest rates will dampen consumers' enthusiasm for EVs, as well as investor jitters about growth assets. TSLA shareholders are furious at CEO Elon Musk, The Wall Street Journal reports, for his Twitter antics and tomfoolery, which has led to several downgrades for the stock. Meanwhile, hordes of customers are canceling their Tesla orders, \"His personality is absolutely tanking the Tesla brand. I'm looking forward to having an Elon-free existence,’’ a biotech exec with a Model S lease has told CNET. \"There is no Tesla CEO today,\" tweeted Gary Black, a hedge fund manager with ~$50 million worth of TSLA stock told Futurism.

Related: U.S. Oil, Gas Rigs Up 193 This Year

But Tesla is hardly alone here: most EV stocks have had a year to forget with rising costs, supply chain issues, increasing competition, and the threat of a potential recession causing many to sell off heavily.

Surprisingly, some Wall Street pundits have not given up on TSLA stock and are urging investors to use the selloff as a buying opportunity. To wit, Citi has tapped TSLA as a bullish contrarian stock for 2023, while Baird analyst Ben Kallo still sees Tesla as a “Best Idea” stock in 2023. Meanwhile, Morgan Stanley says Tesla could extend its lead over its EV rivals in the coming year, and has cited “valuation, cash flow, innovation and cost leadership” as key reasons to maintain a Buy-equivalent rating. Meanwhile, famed contrarian investor Cathie Wood, known for betting big on former growth stocks as they fall, recently loaded up on more than 25K shares of the EV giant.

Story continues

In sharp contrast, things could not have gone differently for Tesla’s biggest fossil fuel rival, Exxon Mobil Corp. (NYSE: XOM). Exxon Mobil has enjoyed the biggest rise in the S&P 500 this year, with the energy giant jumping almost like technology stocks did in the tech boom thanks to high oil and gas prices triggered by the energy crisis. XOM shares have soared 72% this year, adding $190 billion to the company’s market value. Exxon’s increase in market value surpasses any company in the S&P 500, making Exxon Mobil the eighth most valuable stock in the S&P 500. That’s a remarkable jump considering that it only ranked 27th most valuable in the S&P 500 a year ago. Exxon was the most valuable S&P 500 company in 2011 until Apple Inc. (NASDAQ: AAPL) surpassed it in 2012.

Whereas Citi has picked XOM as one of its bearish contrarian stocks for 2023, the stock is viewed favorably by most Wall Street analysts, as evidenced by its $118.89 average price target, good for a 10% upside. The energy sector in general is expected to outperform the market again in 2023, and XOM should be just fine, considering it’s still cheap with a PE (Fwd) of 7.9. Back in October, Exxon raised its quarterly dividend by $0.03 per share to $0.91 per share marking the company's 40th straight year of increasing its dividend, keeping it in the elite group of Dividend Aristocrats. XOM shares now yield 3.3%.

The outlook for the energy sector remains bright. According to a recent Moody's research report, industry earnings will stabilize overall in 2023, though they will come in slightly below levels reached by recent peaks.

The analysts note that commodity prices have declined from very high levels earlier in 2022, but have predicted that prices are likely to remain cyclically strong through 2023. This, combined with modest growth in volumes, will support strong cash flow generation for oil and gas producers. Moody’s estimates that the U.S. energy sector’s EBITDA for 2022 will clock in at $623B but fall slightly to $585B in 2023.

The analysts say that low capex, rising uncertainty about the expansion of future supplies, and high geopolitical risk premium will, however, continue to support cyclically high oil prices. Meanwhile, strong export demand for U.S. LNG will continue supporting high natural gas prices.

The combined dividend and buyback yield for the energy sector is now approaching 8%, which is high by historical standards. Similarly elevated levels occurred in 2020 and 2009, which preceded periods of strength. In comparison, the combined dividend and buyback yield for the S&P 500 is closer to five percent, which makes for one of the largest gaps in favor of the energy sector on record.

In other words, there simply aren’t better places for people investing in the U.S. stock market to park their money if they are looking for serious earnings growth.

By Alex Kimani for Oilprice.com

More Top Reads from Oilprice.com:

A New Type Of Oil And Gas Funding Is Booming What is Crude Oil? A Detailed Explanation on this Essential Fossil Fuel Chevron Sending Tanker To Venezuela To Load Oil

Read this article on OilPrice.com"],"source":["https://finance.yahoo.com/m/4b9f894a-9854-3caf-8775-c7e9f9d4ce90/lessons-learned-from-visa-and.html","https://finance.yahoo.com/m/457b8480-3b01-3a94-9273-54aaf80906a8/down-28%25-in-2022%2C-is-apple.html","https://www.fool.com/investing/2023/01/01/80-of-warren-buffetts-portfolio-is-invested-in-the/","https://finance.yahoo.com/m/cc37d40a-9068-3de1-9dd3-a6a71da3aa75/2-beaten-down-warren-buffett.html","https://seekingalpha.com/article/4567219-2023-dividend-growth-portfolio-review-and-look-ahead","https://finance.yahoo.com/news/fall-tesla-rise-exxon-amid-000000565.html"],"publicationDate":[1672549200,1672549200,1672549200,1672549200,1672549200,1672549200]} -} \ No newline at end of file +} diff --git a/stocks_quotes.go b/stocks_quotes.go index 13c9c46..a646b8b 100644 --- a/stocks_quotes.go +++ b/stocks_quotes.go @@ -13,6 +13,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -93,30 +94,38 @@ func (sqr *StockQuoteRequest) getParams() ([]parameters.MarketDataParam, error) return params, nil } -// Raw executes the StockQuoteRequest and returns the raw *resty.Response. +// Raw executes the StockQuoteRequest with the provided context and returns the raw *resty.Response. // This method returns the raw HTTP response from the executed request. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *resty.Response: The raw HTTP response from the executed request. // - error: An error object if the request fails due to being nil, or other execution errors. -func (sqr *StockQuoteRequest) Raw() (*resty.Response, error) { - return sqr.baseRequest.Raw() +func (sqr *StockQuoteRequest) Raw(ctx context.Context) (*resty.Response, error) { + return sqr.baseRequest.Raw(ctx) } -// Packed sends the StockQuoteRequest and returns the StockQuotesResponse. +// Packed sends the StockQuoteRequest with the provided context and returns the StockQuotesResponse. +// +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. // // # Returns // // - *models.StockQuotesResponse: A pointer to the StockQuotesResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (sqr *StockQuoteRequest) Packed() (*models.StockQuotesResponse, error) { +func (sqr *StockQuoteRequest) Packed(ctx context.Context) (*models.StockQuotesResponse, error) { if sqr == nil { return nil, fmt.Errorf("StockQuoteRequest is nil") } var sqrResp models.StockQuotesResponse - _, err := sqr.baseRequest.client.getFromRequest(sqr.baseRequest, &sqrResp) + _, err := sqr.baseRequest.client.getFromRequest(ctx, sqr.baseRequest, &sqrResp) if err != nil { return nil, err } @@ -124,20 +133,24 @@ func (sqr *StockQuoteRequest) Packed() (*models.StockQuotesResponse, error) { return &sqrResp, nil } -// Get sends the StockQuoteRequest, unpacks the StockQuotesResponse, and returns a slice of StockQuote. +// Get sends the StockQuoteRequest with the provided context, unpacks the StockQuotesResponse, and returns a slice of StockQuote. // It returns an error if the request or unpacking fails. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.StockQuote: A slice of StockQuote containing the unpacked quote data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (sqr *StockQuoteRequest) Get() ([]models.StockQuote, error) { +func (sqr *StockQuoteRequest) Get(ctx context.Context) ([]models.StockQuote, error) { if sqr == nil { return nil, fmt.Errorf("StockQuoteRequest is nil") } // Use the Packed method to make the request - sqrResp, err := sqr.Packed() + sqrResp, err := sqr.Packed(ctx) if err != nil { return nil, err } diff --git a/stocks_quotes_test.go b/stocks_quotes_test.go index cbabafb..8c84a5e 100644 --- a/stocks_quotes_test.go +++ b/stocks_quotes_test.go @@ -1,6 +1,7 @@ package client import ( + "context" "fmt" "log" "regexp" @@ -13,7 +14,8 @@ func ExampleStockQuoteRequest_get() { // and perform an actual request to fetch stock quotes for the "AAPL" symbol. // Initialize a new StockQuoteRequest and fetch a stock quote. - sqr, err := StockQuote().Symbol("AAPL").Get() + ctx := context.TODO() + sqr, err := StockQuote().Symbol("AAPL").Get(ctx) if err != nil { log.Fatalf("Failed to get stock quotes: %v", err) } @@ -30,7 +32,8 @@ func ExampleStockQuoteRequest_packed() { // and perform an actual request to fetch stock quotes for the "AAPL" symbol. // Initialize a new StockQuoteRequest and fetch a stock quote. - sqr, err := StockQuote().Symbol("AAPL").Packed() + ctx := context.TODO() + sqr, err := StockQuote().Symbol("AAPL").Packed(ctx) if err != nil { log.Fatalf("Failed to get stock quotes: %v", err) } @@ -48,7 +51,8 @@ func ExampleStockQuoteRequest_raw() { // The response is converted to a raw string and we print out the string at the end of the test. // Initialize a new StockQuoteRequest and fetch a stock quote. - sqr, err := StockQuote().Symbol("AAPL").Raw() + ctx := context.TODO() + sqr, err := StockQuote().Symbol("AAPL").Raw(ctx) if err != nil { log.Fatalf("Failed to get stock quotes: %v", err) } @@ -70,7 +74,8 @@ func ExampleStockQuoteRequest_raw() { } func TestStockQuoteRequest(t *testing.T) { - sqr, err := StockQuote().Symbol("AAPL").FiftyTwoWeek(true).Get() + ctx := context.TODO() + sqr, err := StockQuote().Symbol("AAPL").FiftyTwoWeek(true).Get(ctx) if err != nil { fmt.Print(err) return diff --git a/stocks_tickers_v2.go b/stocks_tickers_v2.go index 2c95679..0908717 100644 --- a/stocks_tickers_v2.go +++ b/stocks_tickers_v2.go @@ -2,6 +2,7 @@ package client import ( + "context" "fmt" "github.com/MarketDataApp/sdk-go/helpers/parameters" @@ -50,20 +51,24 @@ func (str *StockTickersRequestV2) getParams() ([]parameters.MarketDataParam, err return params, nil } -// Packed sends the StockTickersRequestV2 and returns the TickersResponse. +// Packed sends the StockTickersRequestV2 with the provided context and returns the TickersResponse. // This method checks if the StockTickersRequestV2 receiver is nil, returning an error if true. // Otherwise, it proceeds to send the request and returns the TickersResponse along with any error encountered during the request. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - *models.TickersResponse: A pointer to the TickersResponse obtained from the request. // - error: An error object that indicates a failure in sending the request. -func (str *StockTickersRequestV2) Packed() (*models.TickersResponse, error) { +func (str *StockTickersRequestV2) Packed(ctx context.Context) (*models.TickersResponse, error) { if str == nil { return nil, fmt.Errorf("StockTickersRequestV2 is nil") } var trResp models.TickersResponse - _, err := str.baseRequest.client.getFromRequest(str.baseRequest, &trResp) + _, err := str.baseRequest.client.getFromRequest(ctx, str.baseRequest, &trResp) if err != nil { return nil, err } @@ -71,23 +76,27 @@ func (str *StockTickersRequestV2) Packed() (*models.TickersResponse, error) { return &trResp, nil } -// Get sends the StockTickersRequestV2, unpacks the TickersResponse, and returns a slice of Ticker. +// Get sends the StockTickersRequestV2 with the provided context, unpacks the TickersResponse, and returns a slice of Ticker. // It returns an error if the request or unpacking fails. This method is crucial for obtaining the actual stock tickers data // from the stock tickers request. The method first checks if the StockTickersRequestV2 receiver is nil, which would // result in an error as the request cannot be sent. It then proceeds to send the request using the Packed method. // Upon receiving the response, it unpacks the data into a slice of Ticker using the Unpack method from the response. // +// # Parameters +// +// - ctx context.Context: The context to use for the request execution. +// // # Returns // // - []models.Ticker: A slice of Ticker containing the unpacked tickers data from the response. // - error: An error object that indicates a failure in sending the request or unpacking the response. -func (str *StockTickersRequestV2) Get() ([]models.Ticker, error) { +func (str *StockTickersRequestV2) Get(ctx context.Context) ([]models.Ticker, error) { if str == nil { return nil, fmt.Errorf("StockTickersRequestV2 is nil") } // Use the Packed method to make the request - trResp, err := str.Packed() + trResp, err := str.Packed(ctx) if err != nil { return nil, err } diff --git a/stocks_tickers_v2_test.go b/stocks_tickers_v2_test.go index 9e1d13d..35d5bef 100644 --- a/stocks_tickers_v2_test.go +++ b/stocks_tickers_v2_test.go @@ -1,9 +1,13 @@ package client -import "fmt" +import ( + "context" + "fmt" +) func ExampleStockTickersRequestV2_get() { - tickers, err := StockTickers().DateKey("2023-01-05").Get() + ctx := context.TODO() + tickers, err := StockTickers().DateKey("2023-01-05").Get(ctx) if err != nil { fmt.Print(err) return @@ -14,5 +18,5 @@ func ExampleStockTickersRequestV2_get() { break } } - // Output: Ticker{Symbol: AAPL, Name: Apple Inc., Type: CS, Currency: USD, Exchange: XNAS, FigiShares: BBG001S5N8V8, FigiComposite: BBG000B9XRY4, Cik: 0000320193, Updated: 2023-01-11 19:00:00 -05:00} + // Output: Ticker{Symbol: AAPL, Name: Apple Inc., Type: CS, Currency: USD, Exchange: XNAS, FigiShares: BBG001S5N8V8, FigiComposite: BBG000B9XRY4, Cik: 0000320193, Updated: 2023-01-05}} }