From 7844441e630cbc882c1273410bb6ce51af2918a1 Mon Sep 17 00:00:00 2001 From: utahta Date: Sat, 18 Jul 2026 22:01:18 +0900 Subject: [PATCH 1/5] Add context.Context support to all API methods - Add ctx as the first parameter to all service methods and client.HTTPClient.DoRequest, propagated via http.NewRequestWithContext - Detach shared singleflight requests from the caller's cancellation (DoChan + context.WithoutCancel) so that one caller canceling does not fail the flight for other waiters; the completed flight still populates the cache while the canceled caller returns immediately - MockClient honors a canceled context --- announcement.go | 13 ++-- announcement_test.go | 11 +-- breakdown.go | 13 ++-- breakdown_test.go | 9 ++- client/client.go | 73 +++++++++-------- client/client_test.go | 99 ++++++++++++++++++++---- client/interface.go | 4 +- client/mock.go | 7 +- daily_margin_interest.go | 17 ++-- daily_margin_interest_test.go | 13 ++-- dividend.go | 17 ++-- fs_details.go | 17 ++-- fs_details_test.go | 13 ++-- futures.go | 17 ++-- futures_test.go | 13 ++-- index_option.go | 21 ++--- index_option_test.go | 15 ++-- indices.go | 41 +++++----- indices_test.go | 19 ++--- listed.go | 37 ++++----- listed_test.go | 19 ++--- options.go | 21 ++--- options_test.go | 13 ++-- prices_am.go | 13 ++-- prices_am_test.go | 9 ++- quotes.go | 21 ++--- quotes_test.go | 13 ++-- short_selling.go | 21 ++--- short_selling_positions.go | 29 +++---- short_selling_positions_test.go | 19 ++--- short_selling_test.go | 15 ++-- statements.go | 21 ++--- statements_test.go | 13 ++-- test/e2e/announcement_test.go | 13 ++-- test/e2e/breakdown_test.go | 13 ++-- test/e2e/daily_margin_interest_test.go | 19 ++--- test/e2e/daily_quotes_test.go | 15 ++-- test/e2e/fs_details_test.go | 15 ++-- test/e2e/futures_test.go | 25 +++--- test/e2e/index_option_test.go | 23 +++--- test/e2e/indices_test.go | 15 ++-- test/e2e/listed_test.go | 13 ++-- test/e2e/options_test.go | 23 +++--- test/e2e/prices_am_test.go | 15 ++-- test/e2e/short_selling_positions_test.go | 15 ++-- test/e2e/short_selling_test.go | 13 ++-- test/e2e/statements_test.go | 7 +- test/e2e/topix_test.go | 15 ++-- test/e2e/trades_spec_test.go | 17 ++-- test/e2e/trading_calendar_test.go | 15 ++-- test/e2e/weekly_margin_interest_test.go | 17 ++-- topix.go | 17 ++-- topix_test.go | 11 +-- trades_spec.go | 21 ++--- trades_spec_test.go | 11 +-- trading_calendar.go | 33 ++++---- trading_calendar_test.go | 15 ++-- weekly_margin_interest.go | 21 ++--- weekly_margin_interest_test.go | 15 ++-- 59 files changed, 634 insertions(+), 494 deletions(-) diff --git a/announcement.go b/announcement.go index 21400cd..b1ee2d9 100644 --- a/announcement.go +++ b/announcement.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "github.com/utahta/jquants/client" @@ -48,7 +49,7 @@ type AnnouncementParams struct { // 3月期・9月期決算会社のみ対応しています。 // パラメータ: // - params: ページネーション用のパラメータ(オプション) -func (s *AnnouncementService) GetAnnouncement(params AnnouncementParams) (*AnnouncementResponse, error) { +func (s *AnnouncementService) GetAnnouncement(ctx context.Context, params AnnouncementParams) (*AnnouncementResponse, error) { path := "/equities/earnings-calendar" if params.PaginationKey != "" { @@ -56,7 +57,7 @@ func (s *AnnouncementService) GetAnnouncement(params AnnouncementParams) (*Annou } var resp AnnouncementResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get announcement: %w", err) } @@ -65,7 +66,7 @@ func (s *AnnouncementService) GetAnnouncement(params AnnouncementParams) (*Annou // GetAllAnnouncements は翌営業日の全決算発表予定を取得します。 // ページネーションを使用して全データを取得します。 -func (s *AnnouncementService) GetAllAnnouncements() ([]Announcement, error) { +func (s *AnnouncementService) GetAllAnnouncements(ctx context.Context) ([]Announcement, error) { var allAnnouncements []Announcement paginationKey := "" @@ -74,7 +75,7 @@ func (s *AnnouncementService) GetAllAnnouncements() ([]Announcement, error) { PaginationKey: paginationKey, } - resp, err := s.GetAnnouncement(params) + resp, err := s.GetAnnouncement(ctx, params) if err != nil { return nil, err } @@ -93,8 +94,8 @@ func (s *AnnouncementService) GetAllAnnouncements() ([]Announcement, error) { // GetAnnouncementByCode は指定銘柄の決算発表予定を取得します。 // 翌営業日に決算発表予定がある場合のみ取得できます。 -func (s *AnnouncementService) GetAnnouncementByCode(code string) (*Announcement, error) { - announcements, err := s.GetAllAnnouncements() +func (s *AnnouncementService) GetAnnouncementByCode(ctx context.Context, code string) (*Announcement, error) { + announcements, err := s.GetAllAnnouncements(ctx) if err != nil { return nil, err } diff --git a/announcement_test.go b/announcement_test.go index 3b67f9b..ec42600 100644 --- a/announcement_test.go +++ b/announcement_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -60,7 +61,7 @@ func TestAnnouncementService_GetAnnouncement(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Test - resp, err := service.GetAnnouncement(tt.params) + resp, err := service.GetAnnouncement(context.Background(), tt.params) if err != nil { t.Errorf("GetAnnouncement failed: %v", err) } @@ -135,7 +136,7 @@ func TestAnnouncementService_GetAllAnnouncements(t *testing.T) { mockClient.SetResponse("GET", "/equities/earnings-calendar?pagination_key=next_key", mockResponse2) // Test - announcements, err := service.GetAllAnnouncements() + announcements, err := service.GetAllAnnouncements(context.Background()) if err != nil { t.Errorf("GetAllAnnouncements failed: %v", err) } @@ -188,7 +189,7 @@ func TestAnnouncementService_GetAnnouncementByCode(t *testing.T) { mockClient.SetResponse("GET", "/equities/earnings-calendar", mockResponse) // Test - announcement, err := service.GetAnnouncementByCode("7203") + announcement, err := service.GetAnnouncementByCode(context.Background(), "7203") if err != nil { t.Errorf("GetAnnouncementByCode failed: %v", err) } @@ -230,7 +231,7 @@ func TestAnnouncementService_GetAnnouncementByCode_NotFound(t *testing.T) { mockClient.SetResponse("GET", "/equities/earnings-calendar", mockResponse) // Test - _, err := service.GetAnnouncementByCode("7203") + _, err := service.GetAnnouncementByCode(context.Background(), "7203") if err == nil { t.Errorf("Expected error for non-existent code, got nil") } @@ -245,7 +246,7 @@ func TestAnnouncementService_GetAnnouncement_Error(t *testing.T) { mockClient.SetError("GET", "/equities/earnings-calendar", fmt.Errorf("API error")) // Test - _, err := service.GetAnnouncement(AnnouncementParams{}) + _, err := service.GetAnnouncement(context.Background(), AnnouncementParams{}) if err == nil { t.Errorf("Expected error, got nil") } diff --git a/breakdown.go b/breakdown.go index 48f0400..929451f 100644 --- a/breakdown.go +++ b/breakdown.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" "time" @@ -143,7 +144,7 @@ func (r *BreakdownResponse) UnmarshalJSON(data []byte) error { // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *BreakdownService) GetBreakdown(params BreakdownParams) (*BreakdownResponse, error) { +func (s *BreakdownService) GetBreakdown(ctx context.Context, params BreakdownParams) (*BreakdownResponse, error) { path := "/markets/breakdown" query := "?" @@ -168,7 +169,7 @@ func (s *BreakdownService) GetBreakdown(params BreakdownParams) (*BreakdownRespo } var resp BreakdownResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get breakdown: %w", err) } @@ -180,7 +181,7 @@ func (s *BreakdownService) GetBreakdown(params BreakdownParams) (*BreakdownRespo // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *BreakdownService) GetBreakdownByCode(code string, days int) ([]Breakdown, error) { +func (s *BreakdownService) GetBreakdownByCode(ctx context.Context, code string, days int) ([]Breakdown, error) { to := time.Now() from := to.AddDate(0, 0, -days) @@ -195,7 +196,7 @@ func (s *BreakdownService) GetBreakdownByCode(code string, days int) ([]Breakdow PaginationKey: paginationKey, } - resp, err := s.GetBreakdown(params) + resp, err := s.GetBreakdown(ctx, params) if err != nil { return nil, err } @@ -214,7 +215,7 @@ func (s *BreakdownService) GetBreakdownByCode(code string, days int) ([]Breakdow // GetBreakdownByDate は指定日の全銘柄の売買内訳データを取得します。 // ページネーションを使用して大量データを分割取得します。 -func (s *BreakdownService) GetBreakdownByDate(date string) ([]Breakdown, error) { +func (s *BreakdownService) GetBreakdownByDate(ctx context.Context, date string) ([]Breakdown, error) { var allBreakdown []Breakdown paginationKey := "" @@ -224,7 +225,7 @@ func (s *BreakdownService) GetBreakdownByDate(date string) ([]Breakdown, error) PaginationKey: paginationKey, } - resp, err := s.GetBreakdown(params) + resp, err := s.GetBreakdown(ctx, params) if err != nil { return nil, err } diff --git a/breakdown_test.go b/breakdown_test.go index ddac867..2a91b1f 100644 --- a/breakdown_test.go +++ b/breakdown_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" "time" @@ -88,7 +89,7 @@ func TestBreakdownService_GetBreakdown(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Execute - resp, err := service.GetBreakdown(tt.params) + resp, err := service.GetBreakdown(context.Background(), tt.params) // Verify if err != nil { @@ -136,7 +137,7 @@ func TestBreakdownService_GetBreakdownByCode(t *testing.T) { mockClient.SetResponse("GET", expectedPath, mockResponse) // Execute - breakdown, err := service.GetBreakdownByCode("7203", 30) + breakdown, err := service.GetBreakdownByCode(context.Background(), "7203", 30) // Verify if err != nil { @@ -188,7 +189,7 @@ func TestBreakdownService_GetBreakdownByDate(t *testing.T) { mockClient.SetResponse("GET", "/markets/breakdown?date=20240101&pagination_key=next_page_key", mockResponse2) // Execute - breakdown, err := service.GetBreakdownByDate("20240101") + breakdown, err := service.GetBreakdownByDate(context.Background(), "20240101") // Verify if err != nil { @@ -208,7 +209,7 @@ func TestBreakdownService_GetBreakdown_Error(t *testing.T) { mockClient.SetError("GET", "/markets/breakdown?code=7203", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetBreakdown(BreakdownParams{Code: "7203"}) + _, err := service.GetBreakdown(context.Background(), BreakdownParams{Code: "7203"}) // Verify if err == nil { diff --git a/client/client.go b/client/client.go index 465f27d..45f63ad 100644 --- a/client/client.go +++ b/client/client.go @@ -2,6 +2,7 @@ package client import ( "bytes" + "context" "encoding/json" "fmt" "io" @@ -67,35 +68,32 @@ func NewClientFromEnv(opts ...ClientOption) (*Client, error) { return NewClient(apiKey, opts...), nil } -func (c *Client) DoRequest(method, path string, body interface{}, result interface{}) error { +func (c *Client) DoRequest(ctx context.Context, method, path string, body interface{}, result interface{}) error { cacheKey := method + ":" + path if method == http.MethodGet && c.cacheEnabled { // Check cache first c.mu.RLock() - if cached, ok := c.cache[cacheKey]; ok { - c.mu.RUnlock() - if result != nil { - if err := json.Unmarshal(cached, result); err != nil { - return fmt.Errorf("failed to decode cached response: %w", err) - } - } - return nil - } + cached, ok := c.cache[cacheKey] c.mu.RUnlock() + if ok { + return decodeResponse(cached, result) + } // Use singleflight to deduplicate concurrent requests for the same key - respBody, err, _ := c.sf.Do(cacheKey, func() (interface{}, error) { + ch := c.sf.DoChan(cacheKey, func() (interface{}, error) { // Check cache again (another goroutine may have cached it) c.mu.RLock() - if cached, ok := c.cache[cacheKey]; ok { - c.mu.RUnlock() + cached, ok := c.cache[cacheKey] + c.mu.RUnlock() + if ok { return cached, nil } - c.mu.RUnlock() - // Perform HTTP request - data, err := c.doHTTPRequest(method, path, body) + // Detach the shared request from the caller's cancellation so that + // one caller canceling does not fail the flight for other waiters. + // The http.Client timeout still bounds the request duration. + data, err := c.doHTTPRequest(context.WithoutCancel(ctx), method, path, body) if err != nil { return nil, err } @@ -108,35 +106,31 @@ func (c *Client) DoRequest(method, path string, body interface{}, result interfa return data, nil }) - if err != nil { - return err - } - - if result != nil { - if err := json.Unmarshal(respBody.([]byte), result); err != nil { - return fmt.Errorf("failed to decode response: %w", err) + // Wait for the shared flight, but let each caller honor its own context. + // A canceled caller returns immediately; the flight keeps running and + // populates the cache for other callers. + select { + case <-ctx.Done(): + return ctx.Err() + case res := <-ch: + if res.Err != nil { + return res.Err } + return decodeResponse(res.Val.([]byte), result) } - return nil } // Non-cached request (cache disabled or non-GET method) - respBody, err := c.doHTTPRequest(method, path, body) + respBody, err := c.doHTTPRequest(ctx, method, path, body) if err != nil { return err } - if result != nil { - if err := json.Unmarshal(respBody, result); err != nil { - return fmt.Errorf("failed to decode response: %w", err) - } - } - - return nil + return decodeResponse(respBody, result) } // doHTTPRequest performs the actual HTTP request. -func (c *Client) doHTTPRequest(method, path string, body interface{}) ([]byte, error) { +func (c *Client) doHTTPRequest(ctx context.Context, method, path string, body interface{}) ([]byte, error) { url := c.baseURL + path var reqBody io.Reader @@ -148,7 +142,7 @@ func (c *Client) doHTTPRequest(method, path string, body interface{}) ([]byte, e reqBody = bytes.NewBuffer(jsonBody) } - req, err := http.NewRequest(method, url, reqBody) + req, err := http.NewRequestWithContext(ctx, method, url, reqBody) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } @@ -176,6 +170,17 @@ func (c *Client) doHTTPRequest(method, path string, body interface{}) ([]byte, e return respBody, nil } +// decodeResponse unmarshals data into result. A nil result skips decoding. +func decodeResponse(data []byte, result interface{}) error { + if result == nil { + return nil + } + if err := json.Unmarshal(data, result); err != nil { + return fmt.Errorf("failed to decode response: %w", err) + } + return nil +} + // ClearCache clears the cache. func (c *Client) ClearCache() { if !c.cacheEnabled { diff --git a/client/client_test.go b/client/client_test.go index 9d693e4..9dd8daa 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -1,12 +1,15 @@ package client import ( + "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "sync" "sync/atomic" "testing" + "time" ) func TestNewClient(t *testing.T) { @@ -68,7 +71,7 @@ func TestClient_DoRequest_CacheHitMiss(t *testing.T) { // First request (cache miss) var resp1 response - err := c.DoRequest(http.MethodGet, "/test", nil, &resp1) + err := c.DoRequest(context.Background(), http.MethodGet, "/test", nil, &resp1) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -81,7 +84,7 @@ func TestClient_DoRequest_CacheHitMiss(t *testing.T) { // Second request (cache hit) var resp2 response - err = c.DoRequest(http.MethodGet, "/test", nil, &resp2) + err = c.DoRequest(context.Background(), http.MethodGet, "/test", nil, &resp2) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -94,7 +97,7 @@ func TestClient_DoRequest_CacheHitMiss(t *testing.T) { // Different path is a separate cache entry var resp3 response - err = c.DoRequest(http.MethodGet, "/test2", nil, &resp3) + err = c.DoRequest(context.Background(), http.MethodGet, "/test2", nil, &resp3) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -121,7 +124,7 @@ func TestClient_DoRequest_CacheDisabled(t *testing.T) { // First request var resp1 response - err := c.DoRequest(http.MethodGet, "/test", nil, &resp1) + err := c.DoRequest(context.Background(), http.MethodGet, "/test", nil, &resp1) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -131,7 +134,7 @@ func TestClient_DoRequest_CacheDisabled(t *testing.T) { // Second request (called again since no cache) var resp2 response - err = c.DoRequest(http.MethodGet, "/test", nil, &resp2) + err = c.DoRequest(context.Background(), http.MethodGet, "/test", nil, &resp2) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -158,7 +161,7 @@ func TestClient_DoRequest_POSTNotCached(t *testing.T) { // First POST request var resp1 response - err := c.DoRequest(http.MethodPost, "/test", nil, &resp1) + err := c.DoRequest(context.Background(), http.MethodPost, "/test", nil, &resp1) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -168,7 +171,7 @@ func TestClient_DoRequest_POSTNotCached(t *testing.T) { // Second POST request (POST is not cached) var resp2 response - err = c.DoRequest(http.MethodPost, "/test", nil, &resp2) + err = c.DoRequest(context.Background(), http.MethodPost, "/test", nil, &resp2) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -195,7 +198,7 @@ func TestClient_DoRequest_CacheWithQueryParams(t *testing.T) { // Different query parameters are separate cache entries var resp1 response - err := c.DoRequest(http.MethodGet, "/test?code=7203", nil, &resp1) + err := c.DoRequest(context.Background(), http.MethodGet, "/test?code=7203", nil, &resp1) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -204,7 +207,7 @@ func TestClient_DoRequest_CacheWithQueryParams(t *testing.T) { } var resp2 response - err = c.DoRequest(http.MethodGet, "/test?code=9984", nil, &resp2) + err = c.DoRequest(context.Background(), http.MethodGet, "/test?code=9984", nil, &resp2) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -214,7 +217,7 @@ func TestClient_DoRequest_CacheWithQueryParams(t *testing.T) { // Same query parameters result in cache hit var resp3 response - err = c.DoRequest(http.MethodGet, "/test?code=7203", nil, &resp3) + err = c.DoRequest(context.Background(), http.MethodGet, "/test?code=7203", nil, &resp3) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -235,8 +238,8 @@ func TestClient_ClearCache(t *testing.T) { // Populate cache var resp struct{ Message string } - _ = c.DoRequest(http.MethodGet, "/test1", nil, &resp) - _ = c.DoRequest(http.MethodGet, "/test2", nil, &resp) + _ = c.DoRequest(context.Background(), http.MethodGet, "/test1", nil, &resp) + _ = c.DoRequest(context.Background(), http.MethodGet, "/test2", nil, &resp) if c.CacheSize() != 2 { t.Errorf("expected cache size 2, got %d", c.CacheSize()) @@ -286,7 +289,7 @@ func TestClient_DoRequest_ConcurrentAccess(t *testing.T) { go func() { defer wg.Done() var resp response - err := c.DoRequest(http.MethodGet, "/test", nil, &resp) + err := c.DoRequest(context.Background(), http.MethodGet, "/test", nil, &resp) if err != nil { t.Errorf("unexpected error: %v", err) } @@ -302,3 +305,73 @@ func TestClient_DoRequest_ConcurrentAccess(t *testing.T) { t.Errorf("expected cache size 1, got %d", c.CacheSize()) } } + +func TestClient_DoRequest_ContextCancellation(t *testing.T) { + var callCount int64 + release := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt64(&callCount, 1) + <-release + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{"message": "hello"}) + })) + defer server.Close() + + c := NewClient("test-api-key", WithCache()) + c.baseURL = server.URL + + type response struct { + Message string `json:"message"` + } + + // Start a request and cancel its context while the request is in flight + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + errCh := make(chan error, 1) + go func() { + var resp response + errCh <- c.DoRequest(ctx, http.MethodGet, "/test", nil, &resp) + }() + + // Wait until the request reaches the server + deadline := time.Now().Add(5 * time.Second) + for atomic.LoadInt64(&callCount) == 0 { + if time.Now().After(deadline) { + t.Fatal("request did not reach the server") + } + time.Sleep(time.Millisecond) + } + cancel() + + // The canceled caller returns immediately with the context error + select { + case err := <-errCh: + if !errors.Is(err, context.Canceled) { + t.Errorf("expected context.Canceled, got %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("canceled caller did not return") + } + + // The detached flight keeps running and populates the cache + close(release) + deadline = time.Now().Add(5 * time.Second) + for c.CacheSize() == 0 { + if time.Now().After(deadline) { + t.Fatal("flight did not populate the cache after cancellation") + } + time.Sleep(time.Millisecond) + } + + // A subsequent request is served from the cache without a new API call + var resp response + if err := c.DoRequest(context.Background(), http.MethodGet, "/test", nil, &resp); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if resp.Message != "hello" { + t.Errorf("expected message 'hello', got '%s'", resp.Message) + } + if got := atomic.LoadInt64(&callCount); got != 1 { + t.Errorf("expected 1 call, got %d", got) + } +} diff --git a/client/interface.go b/client/interface.go index c5bb6ea..6816873 100644 --- a/client/interface.go +++ b/client/interface.go @@ -1,6 +1,8 @@ package client +import "context" + // HTTPClient defines the interface for making HTTP requests type HTTPClient interface { - DoRequest(method, path string, body interface{}, result interface{}) error + DoRequest(ctx context.Context, method, path string, body interface{}, result interface{}) error } diff --git a/client/mock.go b/client/mock.go index 839b3bb..ea1678c 100644 --- a/client/mock.go +++ b/client/mock.go @@ -1,6 +1,7 @@ package client import ( + "context" "encoding/json" "fmt" "strings" @@ -25,7 +26,11 @@ func NewMockClient() *MockClient { } // DoRequest implements HTTPClient interface -func (m *MockClient) DoRequest(method, path string, body interface{}, result interface{}) error { +func (m *MockClient) DoRequest(ctx context.Context, method, path string, body interface{}, result interface{}) error { + if err := ctx.Err(); err != nil { + return err + } + m.RequestCount++ m.LastMethod = method m.LastPath = path diff --git a/daily_margin_interest.go b/daily_margin_interest.go index a646b91..21d7f5c 100644 --- a/daily_margin_interest.go +++ b/daily_margin_interest.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "github.com/utahta/jquants/client" @@ -92,7 +93,7 @@ const ( ) // GetDailyMarginInterest は日々公表信用取引残高を取得します。 -func (s *DailyMarginInterestService) GetDailyMarginInterest(params DailyMarginInterestParams) (*DailyMarginInterestResponse, error) { +func (s *DailyMarginInterestService) GetDailyMarginInterest(ctx context.Context, params DailyMarginInterestParams) (*DailyMarginInterestResponse, error) { // codeまたはdateのいずれかが必須 if params.Code == "" && params.Date == "" { return nil, fmt.Errorf("either code or date parameter is required") @@ -122,7 +123,7 @@ func (s *DailyMarginInterestService) GetDailyMarginInterest(params DailyMarginIn } var resp DailyMarginInterestResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get daily margin interest: %w", err) } @@ -131,7 +132,7 @@ func (s *DailyMarginInterestService) GetDailyMarginInterest(params DailyMarginIn // GetDailyMarginInterestByCode は指定銘柄の日々公表信用取引残高を取得します。 // ページネーションを使用して全データを取得します。 -func (s *DailyMarginInterestService) GetDailyMarginInterestByCode(code string) ([]DailyMarginInterest, error) { +func (s *DailyMarginInterestService) GetDailyMarginInterestByCode(ctx context.Context, code string) ([]DailyMarginInterest, error) { var allData []DailyMarginInterest paginationKey := "" @@ -141,7 +142,7 @@ func (s *DailyMarginInterestService) GetDailyMarginInterestByCode(code string) ( PaginationKey: paginationKey, } - resp, err := s.GetDailyMarginInterest(params) + resp, err := s.GetDailyMarginInterest(ctx, params) if err != nil { return nil, err } @@ -159,7 +160,7 @@ func (s *DailyMarginInterestService) GetDailyMarginInterestByCode(code string) ( // GetDailyMarginInterestByDate は指定日の全銘柄の日々公表信用取引残高を取得します。 // ページネーションを使用して全データを取得します。 -func (s *DailyMarginInterestService) GetDailyMarginInterestByDate(date string) ([]DailyMarginInterest, error) { +func (s *DailyMarginInterestService) GetDailyMarginInterestByDate(ctx context.Context, date string) ([]DailyMarginInterest, error) { var allData []DailyMarginInterest paginationKey := "" @@ -169,7 +170,7 @@ func (s *DailyMarginInterestService) GetDailyMarginInterestByDate(date string) ( PaginationKey: paginationKey, } - resp, err := s.GetDailyMarginInterest(params) + resp, err := s.GetDailyMarginInterest(ctx, params) if err != nil { return nil, err } @@ -186,7 +187,7 @@ func (s *DailyMarginInterestService) GetDailyMarginInterestByDate(date string) ( } // GetDailyMarginInterestByCodeAndDateRange は指定銘柄・期間の日々公表信用取引残高を取得します。 -func (s *DailyMarginInterestService) GetDailyMarginInterestByCodeAndDateRange(code, from, to string) ([]DailyMarginInterest, error) { +func (s *DailyMarginInterestService) GetDailyMarginInterestByCodeAndDateRange(ctx context.Context, code, from, to string) ([]DailyMarginInterest, error) { var allData []DailyMarginInterest paginationKey := "" @@ -198,7 +199,7 @@ func (s *DailyMarginInterestService) GetDailyMarginInterestByCodeAndDateRange(co PaginationKey: paginationKey, } - resp, err := s.GetDailyMarginInterest(params) + resp, err := s.GetDailyMarginInterest(ctx, params) if err != nil { return nil, err } diff --git a/daily_margin_interest_test.go b/daily_margin_interest_test.go index 59387f0..df95921 100644 --- a/daily_margin_interest_test.go +++ b/daily_margin_interest_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -98,7 +99,7 @@ func TestDailyMarginInterestService_GetDailyMarginInterest(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Execute - resp, err := service.GetDailyMarginInterest(tt.params) + resp, err := service.GetDailyMarginInterest(context.Background(), tt.params) // Verify if err != nil { @@ -124,7 +125,7 @@ func TestDailyMarginInterestService_GetDailyMarginInterest_RequiresCodeOrDate(t service := NewDailyMarginInterestService(mockClient) // Execute with empty code and date - _, err := service.GetDailyMarginInterest(DailyMarginInterestParams{}) + _, err := service.GetDailyMarginInterest(context.Background(), DailyMarginInterestParams{}) // Verify if err == nil { @@ -188,7 +189,7 @@ func TestDailyMarginInterestService_GetDailyMarginInterestByCode(t *testing.T) { mockClient.SetResponse("GET", "/markets/margin-alert?code=13260&pagination_key=next_page_key", mockResponse2) // Execute - data, err := service.GetDailyMarginInterestByCode("13260") + data, err := service.GetDailyMarginInterestByCode(context.Background(), "13260") // Verify if err != nil { @@ -232,7 +233,7 @@ func TestDailyMarginInterestService_GetDailyMarginInterestByDate(t *testing.T) { mockClient.SetResponse("GET", "/markets/margin-alert?date=20240208", mockResponse) // Execute - data, err := service.GetDailyMarginInterestByDate("20240208") + data, err := service.GetDailyMarginInterestByDate(context.Background(), "20240208") // Verify if err != nil { @@ -276,7 +277,7 @@ func TestDailyMarginInterestService_GetDailyMarginInterestByCodeAndDateRange(t * mockClient.SetResponse("GET", "/markets/margin-alert?code=13260&from=20240201&to=20240208", mockResponse) // Execute - data, err := service.GetDailyMarginInterestByCodeAndDateRange("13260", "20240201", "20240208") + data, err := service.GetDailyMarginInterestByCodeAndDateRange(context.Background(), "13260", "20240201", "20240208") // Verify if err != nil { @@ -473,7 +474,7 @@ func TestDailyMarginInterestService_GetDailyMarginInterest_Error(t *testing.T) { mockClient.SetError("GET", "/markets/margin-alert?code=13260", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetDailyMarginInterest(DailyMarginInterestParams{Code: "13260"}) + _, err := service.GetDailyMarginInterest(context.Background(), DailyMarginInterestParams{Code: "13260"}) // Verify if err == nil { diff --git a/dividend.go b/dividend.go index 47221da..2b2daf8 100644 --- a/dividend.go +++ b/dividend.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" @@ -175,7 +176,7 @@ func (r *DividendResponse) UnmarshalJSON(data []byte) error { // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *DividendService) GetDividend(params DividendParams) (*DividendResponse, error) { +func (s *DividendService) GetDividend(ctx context.Context, params DividendParams) (*DividendResponse, error) { // codeまたはdateのいずれかが必須 if params.Code == "" && params.Date == "" { return nil, fmt.Errorf("either code or date parameter is required") @@ -205,7 +206,7 @@ func (s *DividendService) GetDividend(params DividendParams) (*DividendResponse, } var resp DividendResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get dividend: %w", err) } @@ -217,7 +218,7 @@ func (s *DividendService) GetDividend(params DividendParams) (*DividendResponse, // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *DividendService) GetDividendByCode(code string) ([]Dividend, error) { +func (s *DividendService) GetDividendByCode(ctx context.Context, code string) ([]Dividend, error) { var allData []Dividend paginationKey := "" @@ -227,7 +228,7 @@ func (s *DividendService) GetDividendByCode(code string) ([]Dividend, error) { PaginationKey: paginationKey, } - resp, err := s.GetDividend(params) + resp, err := s.GetDividend(ctx, params) if err != nil { return nil, err } @@ -249,7 +250,7 @@ func (s *DividendService) GetDividendByCode(code string) ([]Dividend, error) { // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *DividendService) GetDividendByDate(date string) ([]Dividend, error) { +func (s *DividendService) GetDividendByDate(ctx context.Context, date string) ([]Dividend, error) { var allData []Dividend paginationKey := "" @@ -259,7 +260,7 @@ func (s *DividendService) GetDividendByDate(date string) ([]Dividend, error) { PaginationKey: paginationKey, } - resp, err := s.GetDividend(params) + resp, err := s.GetDividend(ctx, params) if err != nil { return nil, err } @@ -277,7 +278,7 @@ func (s *DividendService) GetDividendByDate(date string) ([]Dividend, error) { } // GetDividendByCodeAndDateRange は指定銘柄・期間の配当情報を取得します。 -func (s *DividendService) GetDividendByCodeAndDateRange(code, from, to string) ([]Dividend, error) { +func (s *DividendService) GetDividendByCodeAndDateRange(ctx context.Context, code, from, to string) ([]Dividend, error) { var allData []Dividend paginationKey := "" @@ -289,7 +290,7 @@ func (s *DividendService) GetDividendByCodeAndDateRange(code, from, to string) ( PaginationKey: paginationKey, } - resp, err := s.GetDividend(params) + resp, err := s.GetDividend(ctx, params) if err != nil { return nil, err } diff --git a/fs_details.go b/fs_details.go index 8a03afb..ba5a378 100644 --- a/fs_details.go +++ b/fs_details.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "github.com/utahta/jquants/client" @@ -54,7 +55,7 @@ type FSDetail struct { // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *FSDetailsService) GetFSDetails(params FSDetailsParams) (*FSDetailsResponse, error) { +func (s *FSDetailsService) GetFSDetails(ctx context.Context, params FSDetailsParams) (*FSDetailsResponse, error) { // codeまたはdateのいずれかが必須 if params.Code == "" && params.Date == "" { return nil, fmt.Errorf("either code or date parameter is required") @@ -78,7 +79,7 @@ func (s *FSDetailsService) GetFSDetails(params FSDetailsParams) (*FSDetailsRespo } var resp FSDetailsResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get fs details: %w", err) } @@ -90,7 +91,7 @@ func (s *FSDetailsService) GetFSDetails(params FSDetailsParams) (*FSDetailsRespo // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *FSDetailsService) GetFSDetailsByCode(code string) ([]FSDetail, error) { +func (s *FSDetailsService) GetFSDetailsByCode(ctx context.Context, code string) ([]FSDetail, error) { var allData []FSDetail paginationKey := "" @@ -100,7 +101,7 @@ func (s *FSDetailsService) GetFSDetailsByCode(code string) ([]FSDetail, error) { PaginationKey: paginationKey, } - resp, err := s.GetFSDetails(params) + resp, err := s.GetFSDetails(ctx, params) if err != nil { return nil, err } @@ -119,7 +120,7 @@ func (s *FSDetailsService) GetFSDetailsByCode(code string) ([]FSDetail, error) { // GetFSDetailsByDate は指定日の全銘柄財務諸表詳細情報を取得します。 // ページネーションを使用して全データを取得します。 -func (s *FSDetailsService) GetFSDetailsByDate(date string) ([]FSDetail, error) { +func (s *FSDetailsService) GetFSDetailsByDate(ctx context.Context, date string) ([]FSDetail, error) { var allData []FSDetail paginationKey := "" @@ -129,7 +130,7 @@ func (s *FSDetailsService) GetFSDetailsByDate(date string) ([]FSDetail, error) { PaginationKey: paginationKey, } - resp, err := s.GetFSDetails(params) + resp, err := s.GetFSDetails(ctx, params) if err != nil { return nil, err } @@ -147,8 +148,8 @@ func (s *FSDetailsService) GetFSDetailsByDate(date string) ([]FSDetail, error) { } // GetFSDetailsByCodeAndDate は指定銘柄の指定開示日の財務諸表詳細情報を取得します。 -func (s *FSDetailsService) GetFSDetailsByCodeAndDate(code, date string) ([]FSDetail, error) { - resp, err := s.GetFSDetails(FSDetailsParams{ +func (s *FSDetailsService) GetFSDetailsByCodeAndDate(ctx context.Context, code, date string) ([]FSDetail, error) { + resp, err := s.GetFSDetails(ctx, FSDetailsParams{ Code: code, Date: date, }) diff --git a/fs_details_test.go b/fs_details_test.go index 0f03cc4..e590b36 100644 --- a/fs_details_test.go +++ b/fs_details_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -98,7 +99,7 @@ func TestFSDetailsService_GetFSDetails(t *testing.T) { } // Execute - resp, err := service.GetFSDetails(tt.params) + resp, err := service.GetFSDetails(context.Background(), tt.params) // Verify if tt.wantErr { @@ -131,7 +132,7 @@ func TestFSDetailsService_GetFSDetails_RequiresParameter(t *testing.T) { service := NewFSDetailsService(mockClient) // Execute with empty parameters - _, err := service.GetFSDetails(FSDetailsParams{}) + _, err := service.GetFSDetails(context.Background(), FSDetailsParams{}) // Verify if err == nil { @@ -189,7 +190,7 @@ func TestFSDetailsService_GetFSDetailsByCode(t *testing.T) { mockClient.SetResponse("GET", "/fins/details?code=86970&pagination_key=next_page_key", mockResponse2) // Execute - data, err := service.GetFSDetailsByCode("86970") + data, err := service.GetFSDetailsByCode(context.Background(), "86970") // Verify if err != nil { @@ -227,7 +228,7 @@ func TestFSDetailsService_GetFSDetailsByDate(t *testing.T) { mockClient.SetResponse("GET", "/fins/details?date=20230130", mockResponse) // Execute - data, err := service.GetFSDetailsByDate("20230130") + data, err := service.GetFSDetailsByDate(context.Background(), "20230130") // Verify if err != nil { @@ -265,7 +266,7 @@ func TestFSDetailsService_GetFSDetailsByCodeAndDate(t *testing.T) { mockClient.SetResponse("GET", "/fins/details?code=86970&date=20230130", mockResponse) // Execute - data, err := service.GetFSDetailsByCodeAndDate("86970", "20230130") + data, err := service.GetFSDetailsByCodeAndDate(context.Background(), "86970", "20230130") // Verify if err != nil { @@ -614,7 +615,7 @@ func TestFSDetailsService_GetFSDetails_Error(t *testing.T) { mockClient.SetError("GET", "/fins/details?code=86970", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetFSDetails(FSDetailsParams{Code: "86970"}) + _, err := service.GetFSDetails(context.Background(), FSDetailsParams{Code: "86970"}) // Verify if err == nil { diff --git a/futures.go b/futures.go index a129f11..6ed067c 100644 --- a/futures.go +++ b/futures.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" "strconv" @@ -191,7 +192,7 @@ func (r *FuturesResponse) UnmarshalJSON(data []byte) error { // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *FuturesService) GetFutures(params FuturesParams) (*FuturesResponse, error) { +func (s *FuturesService) GetFutures(ctx context.Context, params FuturesParams) (*FuturesResponse, error) { // dateは必須パラメータ if params.Date == "" { return nil, fmt.Errorf("date parameter is required") @@ -213,7 +214,7 @@ func (s *FuturesService) GetFutures(params FuturesParams) (*FuturesResponse, err path += query var resp FuturesResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get futures: %w", err) } @@ -225,7 +226,7 @@ func (s *FuturesService) GetFutures(params FuturesParams) (*FuturesResponse, err // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *FuturesService) GetFuturesByDate(date string) ([]Futures, error) { +func (s *FuturesService) GetFuturesByDate(ctx context.Context, date string) ([]Futures, error) { var allData []Futures paginationKey := "" @@ -235,7 +236,7 @@ func (s *FuturesService) GetFuturesByDate(date string) ([]Futures, error) { PaginationKey: paginationKey, } - resp, err := s.GetFutures(params) + resp, err := s.GetFutures(ctx, params) if err != nil { return nil, err } @@ -256,7 +257,7 @@ func (s *FuturesService) GetFuturesByDate(date string) ([]Futures, error) { // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *FuturesService) GetFuturesByCategory(date, category string) ([]Futures, error) { +func (s *FuturesService) GetFuturesByCategory(ctx context.Context, date, category string) ([]Futures, error) { var allData []Futures paginationKey := "" @@ -267,7 +268,7 @@ func (s *FuturesService) GetFuturesByCategory(date, category string) ([]Futures, PaginationKey: paginationKey, } - resp, err := s.GetFutures(params) + resp, err := s.GetFutures(ctx, params) if err != nil { return nil, err } @@ -287,7 +288,7 @@ func (s *FuturesService) GetFuturesByCategory(date, category string) ([]Futures, // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *FuturesService) GetCentralContractMonthFutures(date string) ([]Futures, error) { +func (s *FuturesService) GetCentralContractMonthFutures(ctx context.Context, date string) ([]Futures, error) { var allData []Futures paginationKey := "" @@ -298,7 +299,7 @@ func (s *FuturesService) GetCentralContractMonthFutures(date string) ([]Futures, PaginationKey: paginationKey, } - resp, err := s.GetFutures(params) + resp, err := s.GetFutures(ctx, params) if err != nil { return nil, err } diff --git a/futures_test.go b/futures_test.go index b8e1d3c..5f1ab54 100644 --- a/futures_test.go +++ b/futures_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -103,7 +104,7 @@ func TestFuturesService_GetFutures(t *testing.T) { } // Execute - resp, err := service.GetFutures(tt.params) + resp, err := service.GetFutures(context.Background(), tt.params) // Verify if tt.wantErr { @@ -136,7 +137,7 @@ func TestFuturesService_GetFutures_RequiresDate(t *testing.T) { service := NewFuturesService(mockClient) // Execute with empty date - _, err := service.GetFutures(FuturesParams{}) + _, err := service.GetFutures(context.Background(), FuturesParams{}) // Verify if err == nil { @@ -188,7 +189,7 @@ func TestFuturesService_GetFuturesByDate(t *testing.T) { mockClient.SetResponse("GET", "/derivatives/bars/daily/futures?date=20240723&pagination_key=next_page_key", mockResponse2) // Execute - data, err := service.GetFuturesByDate("20240723") + data, err := service.GetFuturesByDate(context.Background(), "20240723") // Verify if err != nil { @@ -230,7 +231,7 @@ func TestFuturesService_GetFuturesByCategory(t *testing.T) { mockClient.SetResponse("GET", "/derivatives/bars/daily/futures?date=20240723&category=NK225F", mockResponse) // Execute - data, err := service.GetFuturesByCategory("20240723", "NK225F") + data, err := service.GetFuturesByCategory(context.Background(), "20240723", "NK225F") // Verify if err != nil { @@ -274,7 +275,7 @@ func TestFuturesService_GetCentralContractMonthFutures(t *testing.T) { mockClient.SetResponse("GET", "/derivatives/bars/daily/futures?date=20240723&contract_flag=1", mockResponse) // Execute - data, err := service.GetCentralContractMonthFutures("20240723") + data, err := service.GetCentralContractMonthFutures(context.Background(), "20240723") // Verify if err != nil { @@ -539,7 +540,7 @@ func TestFuturesService_GetFutures_Error(t *testing.T) { mockClient.SetError("GET", "/derivatives/bars/daily/futures?date=20240723", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetFutures(FuturesParams{Date: "20240723"}) + _, err := service.GetFutures(context.Background(), FuturesParams{Date: "20240723"}) // Verify if err == nil { diff --git a/index_option.go b/index_option.go index 71a762e..42b2583 100644 --- a/index_option.go +++ b/index_option.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" "strconv" @@ -222,7 +223,7 @@ func parseNullableFloat64(v interface{}) *float64 { } // GetIndexOptions は指定日の日経225オプションデータを取得します。 -func (s *IndexOptionService) GetIndexOptions(params IndexOptionParams) (*IndexOptionResponse, error) { +func (s *IndexOptionService) GetIndexOptions(ctx context.Context, params IndexOptionParams) (*IndexOptionResponse, error) { if params.Date == "" { return nil, fmt.Errorf("date parameter is required") } @@ -237,7 +238,7 @@ func (s *IndexOptionService) GetIndexOptions(params IndexOptionParams) (*IndexOp path += query var resp IndexOptionResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get index options: %w", err) } @@ -246,7 +247,7 @@ func (s *IndexOptionService) GetIndexOptions(params IndexOptionParams) (*IndexOp // GetIndexOptionsByDate は指定日の全日経225オプションデータを取得します。 // ページネーションを使用して全データを取得します。 -func (s *IndexOptionService) GetIndexOptionsByDate(date string) ([]IndexOption, error) { +func (s *IndexOptionService) GetIndexOptionsByDate(ctx context.Context, date string) ([]IndexOption, error) { var allOptions []IndexOption paginationKey := "" @@ -256,7 +257,7 @@ func (s *IndexOptionService) GetIndexOptionsByDate(date string) ([]IndexOption, PaginationKey: paginationKey, } - resp, err := s.GetIndexOptions(params) + resp, err := s.GetIndexOptions(ctx, params) if err != nil { return nil, err } @@ -274,8 +275,8 @@ func (s *IndexOptionService) GetIndexOptionsByDate(date string) ([]IndexOption, } // GetCallOptions は指定日のコールオプションを取得します。 -func (s *IndexOptionService) GetCallOptions(date string) ([]IndexOption, error) { - options, err := s.GetIndexOptionsByDate(date) +func (s *IndexOptionService) GetCallOptions(ctx context.Context, date string) ([]IndexOption, error) { + options, err := s.GetIndexOptionsByDate(ctx, date) if err != nil { return nil, err } @@ -291,8 +292,8 @@ func (s *IndexOptionService) GetCallOptions(date string) ([]IndexOption, error) } // GetPutOptions は指定日のプットオプションを取得します。 -func (s *IndexOptionService) GetPutOptions(date string) ([]IndexOption, error) { - options, err := s.GetIndexOptionsByDate(date) +func (s *IndexOptionService) GetPutOptions(ctx context.Context, date string) ([]IndexOption, error) { + options, err := s.GetIndexOptionsByDate(ctx, date) if err != nil { return nil, err } @@ -308,8 +309,8 @@ func (s *IndexOptionService) GetPutOptions(date string) ([]IndexOption, error) { } // GetOptionChain は指定日のオプションチェーン(全ての権利行使価格)を取得します。 -func (s *IndexOptionService) GetOptionChain(date string) ([]IndexOption, error) { - return s.GetIndexOptionsByDate(date) +func (s *IndexOptionService) GetOptionChain(ctx context.Context, date string) ([]IndexOption, error) { + return s.GetIndexOptionsByDate(ctx, date) } // IsCall はコールオプションかどうかを判定します。 diff --git a/index_option_test.go b/index_option_test.go index 287de85..9fe1c62 100644 --- a/index_option_test.go +++ b/index_option_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -77,7 +78,7 @@ func TestIndexOptionService_GetIndexOptions(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Execute - resp, err := service.GetIndexOptions(tt.params) + resp, err := service.GetIndexOptions(context.Background(), tt.params) // Verify if err != nil { @@ -103,7 +104,7 @@ func TestIndexOptionService_GetIndexOptions_RequiresDate(t *testing.T) { service := NewIndexOptionService(mockClient) // Execute with empty date - _, err := service.GetIndexOptions(IndexOptionParams{}) + _, err := service.GetIndexOptions(context.Background(), IndexOptionParams{}) // Verify if err == nil { @@ -158,7 +159,7 @@ func TestIndexOptionService_GetIndexOptionsByDate(t *testing.T) { mockClient.SetResponse("GET", "/derivatives/bars/daily/options/225?date=20230322&pagination_key=next_page_key", mockResponse2) // Execute - options, err := service.GetIndexOptionsByDate("20230322") + options, err := service.GetIndexOptionsByDate(context.Background(), "20230322") // Verify if err != nil { @@ -204,7 +205,7 @@ func TestIndexOptionService_GetCallOptions(t *testing.T) { mockClient.SetResponse("GET", "/derivatives/bars/daily/options/225?date=20230322", mockResponse) // Execute - callOptions, err := service.GetCallOptions("20230322") + callOptions, err := service.GetCallOptions(context.Background(), "20230322") // Verify if err != nil { @@ -256,7 +257,7 @@ func TestIndexOptionService_GetPutOptions(t *testing.T) { mockClient.SetResponse("GET", "/derivatives/bars/daily/options/225?date=20230322", mockResponse) // Execute - putOptions, err := service.GetPutOptions("20230322") + putOptions, err := service.GetPutOptions(context.Background(), "20230322") // Verify if err != nil { @@ -301,7 +302,7 @@ func TestIndexOptionService_GetOptionChain(t *testing.T) { mockClient.SetResponse("GET", "/derivatives/bars/daily/options/225?date=20230322", mockResponse) // Execute - options, err := service.GetOptionChain("20230322") + options, err := service.GetOptionChain(context.Background(), "20230322") // Verify if err != nil { @@ -449,7 +450,7 @@ func TestIndexOptionService_GetIndexOptions_Error(t *testing.T) { mockClient.SetError("GET", "/derivatives/bars/daily/options/225?date=20230322", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetIndexOptions(IndexOptionParams{Date: "20230322"}) + _, err := service.GetIndexOptions(context.Background(), IndexOptionParams{Date: "20230322"}) // Verify if err == nil { diff --git a/indices.go b/indices.go index a2abfd7..2735625 100644 --- a/indices.go +++ b/indices.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" @@ -94,7 +95,7 @@ type IndicesParams struct { // - Date: 基準日付(例: "20240101" または "2024-01-01") // - From/To: 期間指定(例: "20240101" または "2024-01-01") // - PaginationKey: ページネーション用キー -func (s *IndicesService) GetIndices(params IndicesParams) (*IndicesResponse, error) { +func (s *IndicesService) GetIndices(ctx context.Context, params IndicesParams) (*IndicesResponse, error) { path := "/indices/bars/daily" query := "?" @@ -119,7 +120,7 @@ func (s *IndicesService) GetIndices(params IndicesParams) (*IndicesResponse, err } var resp IndicesResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get indices: %w", err) } @@ -128,12 +129,12 @@ func (s *IndicesService) GetIndices(params IndicesParams) (*IndicesResponse, err // GetIndicesByCode は指定指数の全期間のデータを取得します。 // ページネーションを使用して全データを取得します。 -func (s *IndicesService) GetIndicesByCode(code string) ([]Index, error) { +func (s *IndicesService) GetIndicesByCode(ctx context.Context, code string) ([]Index, error) { var allIndices []Index paginationKey := "" for { - resp, err := s.GetIndices(IndicesParams{ + resp, err := s.GetIndices(ctx, IndicesParams{ Code: code, PaginationKey: paginationKey, }) @@ -153,8 +154,8 @@ func (s *IndicesService) GetIndicesByCode(code string) ([]Index, error) { } // GetIndicesByCodeAndDate は指定指数の指定日のデータを取得します。 -func (s *IndicesService) GetIndicesByCodeAndDate(code, date string) ([]Index, error) { - resp, err := s.GetIndices(IndicesParams{ +func (s *IndicesService) GetIndicesByCodeAndDate(ctx context.Context, code, date string) ([]Index, error) { + resp, err := s.GetIndices(ctx, IndicesParams{ Code: code, Date: date, }) @@ -166,12 +167,12 @@ func (s *IndicesService) GetIndicesByCodeAndDate(code, date string) ([]Index, er // GetIndicesByCodeAndDateRange は指定指数の指定期間のデータを取得します。 // ページネーションを使用して全データを取得します。 -func (s *IndicesService) GetIndicesByCodeAndDateRange(code, from, to string) ([]Index, error) { +func (s *IndicesService) GetIndicesByCodeAndDateRange(ctx context.Context, code, from, to string) ([]Index, error) { var allIndices []Index paginationKey := "" for { - resp, err := s.GetIndices(IndicesParams{ + resp, err := s.GetIndices(ctx, IndicesParams{ Code: code, From: from, To: to, @@ -194,7 +195,7 @@ func (s *IndicesService) GetIndicesByCodeAndDateRange(code, from, to string) ([] // GetIndicesByDate は指定日の全指数データを取得します。 // ページネーションを使用して全データを取得します。 -func (s *IndicesService) GetIndicesByDate(date string) ([]Index, error) { +func (s *IndicesService) GetIndicesByDate(ctx context.Context, date string) ([]Index, error) { var allIndices []Index paginationKey := "" @@ -204,7 +205,7 @@ func (s *IndicesService) GetIndicesByDate(date string) ([]Index, error) { PaginationKey: paginationKey, } - resp, err := s.GetIndices(params) + resp, err := s.GetIndices(ctx, params) if err != nil { return nil, err } @@ -246,23 +247,23 @@ const ( ) // GetTOPIX はTOPIXの全期間データを取得します。 -func (s *IndicesService) GetTOPIX() ([]Index, error) { - return s.GetIndicesByCode(IndexTOPIX) +func (s *IndicesService) GetTOPIX(ctx context.Context) ([]Index, error) { + return s.GetIndicesByCode(ctx, IndexTOPIX) } // GetTOPIXCore30 はTOPIX Core30の全期間データを取得します。 -func (s *IndicesService) GetTOPIXCore30() ([]Index, error) { - return s.GetIndicesByCode(IndexTOPIXCore30) +func (s *IndicesService) GetTOPIXCore30(ctx context.Context) ([]Index, error) { + return s.GetIndicesByCode(ctx, IndexTOPIXCore30) } // GetPrimeMarketIndex は東証プライム市場指数の全期間データを取得します。 -func (s *IndicesService) GetPrimeMarketIndex() ([]Index, error) { - return s.GetIndicesByCode(IndexPrime) +func (s *IndicesService) GetPrimeMarketIndex(ctx context.Context) ([]Index, error) { + return s.GetIndicesByCode(ctx, IndexPrime) } // GetREIT はREIT指数の全期間データを取得します。 -func (s *IndicesService) GetREIT() ([]Index, error) { - return s.GetIndicesByCode(IndexREIT) +func (s *IndicesService) GetREIT(ctx context.Context) ([]Index, error) { + return s.GetIndicesByCode(ctx, IndexREIT) } // 業種別指数コード(東証33業種) @@ -303,6 +304,6 @@ const ( ) // GetSectorIndex は指定した業種別指数の全期間データを取得します。 -func (s *IndicesService) GetSectorIndex(sectorCode string) ([]Index, error) { - return s.GetIndicesByCode(sectorCode) +func (s *IndicesService) GetSectorIndex(ctx context.Context, sectorCode string) ([]Index, error) { + return s.GetIndicesByCode(ctx, sectorCode) } diff --git a/indices_test.go b/indices_test.go index 0e2bf39..eea8c60 100644 --- a/indices_test.go +++ b/indices_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -77,7 +78,7 @@ func TestIndicesService_GetIndices(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Execute - resp, err := service.GetIndices(tt.params) + resp, err := service.GetIndices(context.Background(), tt.params) // Verify if err != nil { @@ -123,7 +124,7 @@ func TestIndicesService_GetIndicesByCode(t *testing.T) { mockClient.SetResponse("GET", "/indices/bars/daily?code=0000&pagination_key=next_page_key", mockResponse2) // Execute - indices, err := service.GetIndicesByCode("0000") + indices, err := service.GetIndicesByCode(context.Background(), "0000") // Verify if err != nil { @@ -175,7 +176,7 @@ func TestIndicesService_GetIndicesByDate(t *testing.T) { mockClient.SetResponse("GET", "/indices/bars/daily?date=20240101&pagination_key=next_page_key", mockResponse2) // Execute - indices, err := service.GetIndicesByDate("20240101") + indices, err := service.GetIndicesByDate(context.Background(), "20240101") // Verify if err != nil { @@ -200,7 +201,7 @@ func TestIndicesService_GetTOPIX(t *testing.T) { mockClient.SetResponse("GET", "/indices/bars/daily?code=0000", mockResponse) // Execute - indices, err := service.GetTOPIX() + indices, err := service.GetTOPIX(context.Background()) // Verify if err != nil { @@ -228,7 +229,7 @@ func TestIndicesService_GetSectorIndex(t *testing.T) { mockClient.SetResponse("GET", "/indices/bars/daily?code=0058", mockResponse) // Execute - indices, err := service.GetSectorIndex(IndexSectorInfoComm) + indices, err := service.GetSectorIndex(context.Background(), IndexSectorInfoComm) // Verify if err != nil { @@ -256,7 +257,7 @@ func TestIndicesService_GetPrimeMarketIndex(t *testing.T) { mockClient.SetResponse("GET", "/indices/bars/daily?code=0500", mockResponse) // Execute - indices, err := service.GetPrimeMarketIndex() + indices, err := service.GetPrimeMarketIndex(context.Background()) // Verify if err != nil { @@ -288,7 +289,7 @@ func TestIndicesService_GetIndicesByCodeAndDate(t *testing.T) { mockClient.SetResponse("GET", "/indices/bars/daily?code=0000&date=20240101", mockResponse) // Execute - indices, err := service.GetIndicesByCodeAndDate("0000", "20240101") + indices, err := service.GetIndicesByCodeAndDate(context.Background(), "0000", "20240101") // Verify if err != nil { @@ -333,7 +334,7 @@ func TestIndicesService_GetIndicesByCodeAndDateRange(t *testing.T) { mockClient.SetResponse("GET", basePath+"&pagination_key=next_page_key", mockResponse2) // Execute - indices, err := service.GetIndicesByCodeAndDateRange("0000", "20240101", "20240131") + indices, err := service.GetIndicesByCodeAndDateRange(context.Background(), "0000", "20240101", "20240131") // Verify if err != nil { @@ -359,7 +360,7 @@ func TestIndicesService_GetIndices_Error(t *testing.T) { mockClient.SetError("GET", "/indices/bars/daily?code=0000", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetIndices(IndicesParams{Code: "0000"}) + _, err := service.GetIndices(context.Background(), IndicesParams{Code: "0000"}) // Verify if err == nil { diff --git a/listed.go b/listed.go index 7b878fe..a91cfed 100644 --- a/listed.go +++ b/listed.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "github.com/utahta/jquants/client" @@ -125,7 +126,7 @@ type ListedInfoParams struct { // パラメータ: // - Code: 銘柄コード(例: "7203" または "72030") // - Date: 基準日付(例: "20240101" または "2024-01-01") -func (s *ListedService) GetListedInfo(params ListedInfoParams) (*ListedInfoResponse, error) { +func (s *ListedService) GetListedInfo(ctx context.Context, params ListedInfoParams) (*ListedInfoResponse, error) { path := "/equities/master" query := "?" @@ -141,7 +142,7 @@ func (s *ListedService) GetListedInfo(params ListedInfoParams) (*ListedInfoRespo } var resp ListedInfoResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get listed info: %w", err) } @@ -149,8 +150,8 @@ func (s *ListedService) GetListedInfo(params ListedInfoParams) (*ListedInfoRespo } // GetAllListedInfo は当日時点の全銘柄情報を取得します。 -func (s *ListedService) GetAllListedInfo() ([]ListedInfo, error) { - resp, err := s.GetListedInfo(ListedInfoParams{}) +func (s *ListedService) GetAllListedInfo(ctx context.Context) ([]ListedInfo, error) { + resp, err := s.GetListedInfo(ctx, ListedInfoParams{}) if err != nil { return nil, err } @@ -158,8 +159,8 @@ func (s *ListedService) GetAllListedInfo() ([]ListedInfo, error) { } // GetListedInfoByCode は当日時点の指定銘柄情報を取得します。 -func (s *ListedService) GetListedInfoByCode(code string) ([]ListedInfo, error) { - resp, err := s.GetListedInfo(ListedInfoParams{Code: code}) +func (s *ListedService) GetListedInfoByCode(ctx context.Context, code string) ([]ListedInfo, error) { + resp, err := s.GetListedInfo(ctx, ListedInfoParams{Code: code}) if err != nil { return nil, err } @@ -167,8 +168,8 @@ func (s *ListedService) GetListedInfoByCode(code string) ([]ListedInfo, error) { } // GetListedInfoByDate は指定日時点の全銘柄情報を取得します。 -func (s *ListedService) GetListedInfoByDate(date string) ([]ListedInfo, error) { - resp, err := s.GetListedInfo(ListedInfoParams{Date: date}) +func (s *ListedService) GetListedInfoByDate(ctx context.Context, date string) ([]ListedInfo, error) { + resp, err := s.GetListedInfo(ctx, ListedInfoParams{Date: date}) if err != nil { return nil, err } @@ -176,8 +177,8 @@ func (s *ListedService) GetListedInfoByDate(date string) ([]ListedInfo, error) { } // GetListedInfoByCodeAndDate は指定日時点の指定銘柄情報を取得します。 -func (s *ListedService) GetListedInfoByCodeAndDate(code, date string) ([]ListedInfo, error) { - resp, err := s.GetListedInfo(ListedInfoParams{Code: code, Date: date}) +func (s *ListedService) GetListedInfoByCodeAndDate(ctx context.Context, code, date string) ([]ListedInfo, error) { + resp, err := s.GetListedInfo(ctx, ListedInfoParams{Code: code, Date: date}) if err != nil { return nil, err } @@ -185,9 +186,9 @@ func (s *ListedService) GetListedInfoByCodeAndDate(code, date string) ([]ListedI } // GetListedBySector17 は指定した17業種コードの銘柄一覧を取得します。 -// 例: GetListedBySector17(Sector17IT, "") でIT関連銘柄を取得 -func (s *ListedService) GetListedBySector17(sector17Code string, date string) ([]ListedInfo, error) { - allInfo, err := s.GetListedInfoByDate(date) +// 例: GetListedBySector17(ctx, Sector17IT, "") でIT関連銘柄を取得 +func (s *ListedService) GetListedBySector17(ctx context.Context, sector17Code string, date string) ([]ListedInfo, error) { + allInfo, err := s.GetListedInfoByDate(ctx, date) if err != nil { return nil, err } @@ -203,9 +204,9 @@ func (s *ListedService) GetListedBySector17(sector17Code string, date string) ([ } // GetListedBySector33 は指定した33業種コードの銘柄一覧を取得します。 -// 例: GetListedBySector33(Sector33IT, "") で情報・通信業銘柄を取得 -func (s *ListedService) GetListedBySector33(sector33Code string, date string) ([]ListedInfo, error) { - allInfo, err := s.GetListedInfoByDate(date) +// 例: GetListedBySector33(ctx, Sector33IT, "") で情報・通信業銘柄を取得 +func (s *ListedService) GetListedBySector33(ctx context.Context, sector33Code string, date string) ([]ListedInfo, error) { + allInfo, err := s.GetListedInfoByDate(ctx, date) if err != nil { return nil, err } @@ -222,8 +223,8 @@ func (s *ListedService) GetListedBySector33(sector33Code string, date string) ([ // GetListedByMarket は指定した市場区分の銘柄一覧を取得します。 // marketCode: MarketPrime, MarketStandard, MarketGrowth など -func (s *ListedService) GetListedByMarket(marketCode string, date string) ([]ListedInfo, error) { - allInfo, err := s.GetListedInfoByDate(date) +func (s *ListedService) GetListedByMarket(ctx context.Context, marketCode string, date string) ([]ListedInfo, error) { + allInfo, err := s.GetListedInfoByDate(ctx, date) if err != nil { return nil, err } diff --git a/listed_test.go b/listed_test.go index 67d1a30..ebfe0f8 100644 --- a/listed_test.go +++ b/listed_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -69,7 +70,7 @@ func TestListedService_GetListedInfo(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Test - resp, err := service.GetListedInfo(tt.params) + resp, err := service.GetListedInfo(context.Background(), tt.params) if err != nil { t.Fatalf("GetListedInfo() error = %v", err) } @@ -108,7 +109,7 @@ func TestListedService_GetAllListedInfo(t *testing.T) { mockClient.SetResponse("GET", "/equities/master", mockResponse) // Execute - infos, err := service.GetAllListedInfo() + infos, err := service.GetAllListedInfo(context.Background()) if err != nil { t.Fatalf("GetAllListedInfo() error = %v", err) } @@ -145,7 +146,7 @@ func TestListedService_GetListedInfoByCode(t *testing.T) { mockClient.SetResponse("GET", "/equities/master?code=7203", mockResponse) // Execute - infos, err := service.GetListedInfoByCode("7203") + infos, err := service.GetListedInfoByCode(context.Background(), "7203") if err != nil { t.Fatalf("GetListedInfoByCode() error = %v", err) } @@ -180,7 +181,7 @@ func TestListedService_GetListedInfoByDate(t *testing.T) { mockClient.SetResponse("GET", "/equities/master?date=20240101", mockResponse) // Execute - infos, err := service.GetListedInfoByDate("20240101") + infos, err := service.GetListedInfoByDate(context.Background(), "20240101") if err != nil { t.Fatalf("GetListedInfoByDate() error = %v", err) } @@ -209,7 +210,7 @@ func TestListedService_GetListedInfoByCodeAndDate(t *testing.T) { mockClient.SetResponse("GET", "/equities/master?code=7203&date=20240101", mockResponse) // Execute - infos, err := service.GetListedInfoByCodeAndDate("7203", "20240101") + infos, err := service.GetListedInfoByCodeAndDate(context.Background(), "7203", "20240101") if err != nil { t.Fatalf("GetListedInfoByCodeAndDate() error = %v", err) } @@ -235,7 +236,7 @@ func TestListedService_GetListedInfo_Error(t *testing.T) { mockClient.SetError("GET", "/equities/master?code=7203", fmt.Errorf("API error")) // Test - _, err := service.GetListedInfo(ListedInfoParams{Code: "7203"}) + _, err := service.GetListedInfo(context.Background(), ListedInfoParams{Code: "7203"}) if err == nil { t.Error("GetListedInfo() expected error but got nil") } @@ -275,7 +276,7 @@ func TestListedService_GetListedBySector17(t *testing.T) { mockClient.SetResponse("GET", "/equities/master", mockResponse) // Test - 自動車・輸送機セクターの銘柄を取得 - infos, err := service.GetListedBySector17(Sector17Auto, "") + infos, err := service.GetListedBySector17(context.Background(), Sector17Auto, "") if err != nil { t.Errorf("GetListedBySector17 failed: %v", err) } @@ -326,7 +327,7 @@ func TestListedService_GetListedBySector33(t *testing.T) { mockClient.SetResponse("GET", "/equities/master", mockResponse) // Test - 情報・通信業の銘柄を取得 - infos, err := service.GetListedBySector33(Sector33IT, "") + infos, err := service.GetListedBySector33(context.Background(), Sector33IT, "") if err != nil { t.Errorf("GetListedBySector33 failed: %v", err) } @@ -374,7 +375,7 @@ func TestListedService_GetListedByMarket(t *testing.T) { mockClient.SetResponse("GET", "/equities/master", mockResponse) // Test - プライム市場の銘柄を取得 - infos, err := service.GetListedByMarket(MarketPrime, "") + infos, err := service.GetListedByMarket(context.Background(), MarketPrime, "") if err != nil { t.Errorf("GetListedByMarket failed: %v", err) } diff --git a/options.go b/options.go index aa7016c..106c706 100644 --- a/options.go +++ b/options.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" "strconv" @@ -226,7 +227,7 @@ func (r *OptionsResponse) UnmarshalJSON(data []byte) error { // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *OptionsService) GetOptions(params OptionsParams) (*OptionsResponse, error) { +func (s *OptionsService) GetOptions(ctx context.Context, params OptionsParams) (*OptionsResponse, error) { // dateは必須パラメータ if params.Date == "" { return nil, fmt.Errorf("date parameter is required") @@ -251,7 +252,7 @@ func (s *OptionsService) GetOptions(params OptionsParams) (*OptionsResponse, err path += query var resp OptionsResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get options: %w", err) } @@ -263,7 +264,7 @@ func (s *OptionsService) GetOptions(params OptionsParams) (*OptionsResponse, err // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *OptionsService) GetOptionsByDate(date string) ([]Option, error) { +func (s *OptionsService) GetOptionsByDate(ctx context.Context, date string) ([]Option, error) { var allData []Option paginationKey := "" @@ -273,7 +274,7 @@ func (s *OptionsService) GetOptionsByDate(date string) ([]Option, error) { PaginationKey: paginationKey, } - resp, err := s.GetOptions(params) + resp, err := s.GetOptions(ctx, params) if err != nil { return nil, err } @@ -294,7 +295,7 @@ func (s *OptionsService) GetOptionsByDate(date string) ([]Option, error) { // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *OptionsService) GetOptionsByCategory(date, category string) ([]Option, error) { +func (s *OptionsService) GetOptionsByCategory(ctx context.Context, date, category string) ([]Option, error) { var allData []Option paginationKey := "" @@ -305,7 +306,7 @@ func (s *OptionsService) GetOptionsByCategory(date, category string) ([]Option, PaginationKey: paginationKey, } - resp, err := s.GetOptions(params) + resp, err := s.GetOptions(ctx, params) if err != nil { return nil, err } @@ -325,7 +326,7 @@ func (s *OptionsService) GetOptionsByCategory(date, category string) ([]Option, // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *OptionsService) GetSecurityOptionsByCode(date, code string) ([]Option, error) { +func (s *OptionsService) GetSecurityOptionsByCode(ctx context.Context, date, code string) ([]Option, error) { var allData []Option paginationKey := "" @@ -337,7 +338,7 @@ func (s *OptionsService) GetSecurityOptionsByCode(date, code string) ([]Option, PaginationKey: paginationKey, } - resp, err := s.GetOptions(params) + resp, err := s.GetOptions(ctx, params) if err != nil { return nil, err } @@ -357,7 +358,7 @@ func (s *OptionsService) GetSecurityOptionsByCode(date, code string) ([]Option, // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *OptionsService) GetCentralContractMonthOptions(date string) ([]Option, error) { +func (s *OptionsService) GetCentralContractMonthOptions(ctx context.Context, date string) ([]Option, error) { var allData []Option paginationKey := "" @@ -368,7 +369,7 @@ func (s *OptionsService) GetCentralContractMonthOptions(date string) ([]Option, PaginationKey: paginationKey, } - resp, err := s.GetOptions(params) + resp, err := s.GetOptions(ctx, params) if err != nil { return nil, err } diff --git a/options_test.go b/options_test.go index 4c41933..b1478bd 100644 --- a/options_test.go +++ b/options_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" "testing" @@ -113,7 +114,7 @@ func TestOptionsService_GetOptions(t *testing.T) { } // Execute - resp, err := service.GetOptions(tt.params) + resp, err := service.GetOptions(context.Background(), tt.params) // Verify if tt.wantErr { @@ -185,7 +186,7 @@ func TestOptionsService_GetOptionsByDate(t *testing.T) { mockClient.SetResponse("GET", "/derivatives/bars/daily/options?date=20240723&pagination_key=next_page", mockResponse2) // Execute - options, err := service.GetOptionsByDate("20240723") + options, err := service.GetOptionsByDate(context.Background(), "20240723") // Verify if err != nil { @@ -225,7 +226,7 @@ func TestOptionsService_GetOptionsByCategory(t *testing.T) { mockClient.SetResponse("GET", "/derivatives/bars/daily/options?date=20240723&category=NK225E", mockResponse) // Execute - options, err := service.GetOptionsByCategory("20240723", "NK225E") + options, err := service.GetOptionsByCategory(context.Background(), "20240723", "NK225E") // Verify if err != nil { @@ -262,7 +263,7 @@ func TestOptionsService_GetSecurityOptionsByCode(t *testing.T) { mockClient.SetResponse("GET", "/derivatives/bars/daily/options?date=20240723&category=EQOP&code=7203", mockResponse) // Execute - options, err := service.GetSecurityOptionsByCode("20240723", "7203") + options, err := service.GetSecurityOptionsByCode(context.Background(), "20240723", "7203") // Verify if err != nil { @@ -303,7 +304,7 @@ func TestOptionsService_GetCentralContractMonthOptions(t *testing.T) { mockClient.SetResponse("GET", "/derivatives/bars/daily/options?date=20240723&contract_flag=1", mockResponse) // Execute - options, err := service.GetCentralContractMonthOptions("20240723") + options, err := service.GetCentralContractMonthOptions(context.Background(), "20240723") // Verify if err != nil { @@ -326,7 +327,7 @@ func TestOptionsService_GetOptions_Error(t *testing.T) { mockClient.SetError("GET", "/derivatives/bars/daily/options?date=20240723", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetOptions(OptionsParams{Date: "20240723"}) + _, err := service.GetOptions(context.Background(), OptionsParams{Date: "20240723"}) // Verify if err == nil { diff --git a/prices_am.go b/prices_am.go index d911025..6450c2d 100644 --- a/prices_am.go +++ b/prices_am.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" @@ -115,7 +116,7 @@ func (r *PricesAMResponse) UnmarshalJSON(data []byte) error { // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *PricesAMService) GetPricesAM(params PricesAMParams) (*PricesAMResponse, error) { +func (s *PricesAMService) GetPricesAM(ctx context.Context, params PricesAMParams) (*PricesAMResponse, error) { path := "/equities/bars/daily/am" query := "?" @@ -131,7 +132,7 @@ func (s *PricesAMService) GetPricesAM(params PricesAMParams) (*PricesAMResponse, } var resp PricesAMResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get prices AM: %w", err) } @@ -142,8 +143,8 @@ func (s *PricesAMService) GetPricesAM(params PricesAMParams) (*PricesAMResponse, // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *PricesAMService) GetPricesAMByCode(code string) (*PricesAMResponse, error) { - return s.GetPricesAM(PricesAMParams{Code: code}) +func (s *PricesAMService) GetPricesAMByCode(ctx context.Context, code string) (*PricesAMResponse, error) { + return s.GetPricesAM(ctx, PricesAMParams{Code: code}) } // GetAllPricesAM は全銘柄の前場四本値データを取得します。 @@ -151,7 +152,7 @@ func (s *PricesAMService) GetPricesAMByCode(code string) (*PricesAMResponse, err // // 注意: このAPIはプレミアムプラン専用です。 // スタンダードプラン以下では "This API is not available on your subscription" エラーが返されます。 -func (s *PricesAMService) GetAllPricesAM() ([]PriceAM, error) { +func (s *PricesAMService) GetAllPricesAM(ctx context.Context) ([]PriceAM, error) { var allData []PriceAM paginationKey := "" @@ -160,7 +161,7 @@ func (s *PricesAMService) GetAllPricesAM() ([]PriceAM, error) { PaginationKey: paginationKey, } - resp, err := s.GetPricesAM(params) + resp, err := s.GetPricesAM(ctx, params) if err != nil { return nil, err } diff --git a/prices_am_test.go b/prices_am_test.go index 517d2df..cc2360e 100644 --- a/prices_am_test.go +++ b/prices_am_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -67,7 +68,7 @@ func TestPricesAMService_GetPricesAM(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Execute - resp, err := service.GetPricesAM(tt.params) + resp, err := service.GetPricesAM(context.Background(), tt.params) // Verify if err != nil { @@ -111,7 +112,7 @@ func TestPricesAMService_GetPricesAMByCode(t *testing.T) { mockClient.SetResponse("GET", "/equities/bars/daily/am?code=39400", mockResponse) // Execute - resp, err := service.GetPricesAMByCode("39400") + resp, err := service.GetPricesAMByCode(context.Background(), "39400") // Verify if err != nil { @@ -163,7 +164,7 @@ func TestPricesAMService_GetAllPricesAM(t *testing.T) { mockClient.SetResponse("GET", "/equities/bars/daily/am?pagination_key=next_page_key", mockResponse2) // Execute - data, err := service.GetAllPricesAM() + data, err := service.GetAllPricesAM(context.Background()) // Verify if err != nil { @@ -478,7 +479,7 @@ func TestPricesAMService_GetPricesAM_Error(t *testing.T) { mockClient.SetError("GET", "/equities/bars/daily/am", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetPricesAM(PricesAMParams{}) + _, err := service.GetPricesAM(context.Background(), PricesAMParams{}) // Verify if err == nil { diff --git a/quotes.go b/quotes.go index 336b25c..025f83b 100644 --- a/quotes.go +++ b/quotes.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" @@ -217,7 +218,7 @@ type DailyQuotesParams struct { // - Date: 基準日付(例: "20240101" または "2024-01-01") // - From/To: 期間指定(例: "20240101" または "2024-01-01") // - PaginationKey: ページネーション用キー -func (s *QuotesService) GetDailyQuotes(params DailyQuotesParams) (*DailyQuotesResponse, error) { +func (s *QuotesService) GetDailyQuotes(ctx context.Context, params DailyQuotesParams) (*DailyQuotesResponse, error) { path := "/equities/bars/daily" query := "?" @@ -242,7 +243,7 @@ func (s *QuotesService) GetDailyQuotes(params DailyQuotesParams) (*DailyQuotesRe } var resp DailyQuotesResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get daily quotes: %w", err) } @@ -251,7 +252,7 @@ func (s *QuotesService) GetDailyQuotes(params DailyQuotesParams) (*DailyQuotesRe // GetDailyQuotesByCode は指定銘柄の全期間の株価データを取得します。 // ページネーションを使用して全データを取得します。 -func (s *QuotesService) GetDailyQuotesByCode(code string) ([]DailyQuote, error) { +func (s *QuotesService) GetDailyQuotesByCode(ctx context.Context, code string) ([]DailyQuote, error) { var allQuotes []DailyQuote paginationKey := "" @@ -261,7 +262,7 @@ func (s *QuotesService) GetDailyQuotesByCode(code string) ([]DailyQuote, error) PaginationKey: paginationKey, } - resp, err := s.GetDailyQuotes(params) + resp, err := s.GetDailyQuotes(ctx, params) if err != nil { return nil, err } @@ -278,8 +279,8 @@ func (s *QuotesService) GetDailyQuotesByCode(code string) ([]DailyQuote, error) } // GetDailyQuotesByCodeAndDate は指定銘柄の指定日の株価データを取得します。 -func (s *QuotesService) GetDailyQuotesByCodeAndDate(code, date string) ([]DailyQuote, error) { - resp, err := s.GetDailyQuotes(DailyQuotesParams{ +func (s *QuotesService) GetDailyQuotesByCodeAndDate(ctx context.Context, code, date string) ([]DailyQuote, error) { + resp, err := s.GetDailyQuotes(ctx, DailyQuotesParams{ Code: code, Date: date, }) @@ -291,7 +292,7 @@ func (s *QuotesService) GetDailyQuotesByCodeAndDate(code, date string) ([]DailyQ // GetDailyQuotesByCodeAndDateRange は指定銘柄の指定期間の株価データを取得します。 // ページネーションを使用して全データを取得します。 -func (s *QuotesService) GetDailyQuotesByCodeAndDateRange(code, from, to string) ([]DailyQuote, error) { +func (s *QuotesService) GetDailyQuotesByCodeAndDateRange(ctx context.Context, code, from, to string) ([]DailyQuote, error) { var allQuotes []DailyQuote paginationKey := "" @@ -303,7 +304,7 @@ func (s *QuotesService) GetDailyQuotesByCodeAndDateRange(code, from, to string) PaginationKey: paginationKey, } - resp, err := s.GetDailyQuotes(params) + resp, err := s.GetDailyQuotes(ctx, params) if err != nil { return nil, err } @@ -321,7 +322,7 @@ func (s *QuotesService) GetDailyQuotesByCodeAndDateRange(code, from, to string) // GetDailyQuotesByDate は指定日の全銘柄の株価データを取得します。 // ページネーションを使用して大量データを分割取得します。 -func (s *QuotesService) GetDailyQuotesByDate(date string) ([]DailyQuote, error) { +func (s *QuotesService) GetDailyQuotesByDate(ctx context.Context, date string) ([]DailyQuote, error) { var allQuotes []DailyQuote paginationKey := "" @@ -331,7 +332,7 @@ func (s *QuotesService) GetDailyQuotesByDate(date string) ([]DailyQuote, error) PaginationKey: paginationKey, } - resp, err := s.GetDailyQuotes(params) + resp, err := s.GetDailyQuotes(ctx, params) if err != nil { return nil, err } diff --git a/quotes_test.go b/quotes_test.go index e279dde..dd6dbda 100644 --- a/quotes_test.go +++ b/quotes_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" "time" @@ -76,7 +77,7 @@ func TestQuotesService_GetDailyQuotes(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Test - resp, err := service.GetDailyQuotes(tt.params) + resp, err := service.GetDailyQuotes(context.Background(), tt.params) if err != nil { t.Errorf("GetDailyQuotes failed: %v", err) } @@ -135,7 +136,7 @@ func TestQuotesService_GetDailyQuotesByCode(t *testing.T) { mockClient.SetResponse("GET", "/equities/bars/daily?code=7203&pagination_key=next_page_key", mockResponse2) // Test - quotes, err := service.GetDailyQuotesByCode("7203") + quotes, err := service.GetDailyQuotesByCode(context.Background(), "7203") if err != nil { t.Errorf("GetDailyQuotesByCode failed: %v", err) } @@ -159,7 +160,7 @@ func TestQuotesService_GetDailyQuotes_Error(t *testing.T) { mockClient.SetError("GET", "/equities/bars/daily?code=7203", fmt.Errorf("API error")) // Test - _, err := service.GetDailyQuotes(DailyQuotesParams{Code: "7203"}) + _, err := service.GetDailyQuotes(context.Background(), DailyQuotesParams{Code: "7203"}) if err == nil { t.Errorf("Expected error, got nil") } @@ -203,7 +204,7 @@ func TestQuotesService_GetDailyQuotesByDate(t *testing.T) { mockClient.SetResponse("GET", "/equities/bars/daily?date=20240101&pagination_key=next_page_key", mockResponse2) // Test - quotes, err := service.GetDailyQuotesByDate("20240101") + quotes, err := service.GetDailyQuotesByDate(context.Background(), "20240101") if err != nil { t.Errorf("GetDailyQuotesByDate failed: %v", err) } @@ -347,7 +348,7 @@ func TestQuotesService_GetDailyQuotesByCodeAndDate(t *testing.T) { mockClient.SetResponse("GET", "/equities/bars/daily?code=7203&date=20240101", mockResponse) // Test - quotes, err := service.GetDailyQuotesByCodeAndDate("7203", "20240101") + quotes, err := service.GetDailyQuotesByCodeAndDate(context.Background(), "7203", "20240101") if err != nil { t.Errorf("GetDailyQuotesByCodeAndDate failed: %v", err) } @@ -394,7 +395,7 @@ func TestQuotesService_GetDailyQuotesByCodeAndDateRange(t *testing.T) { mockClient.SetResponse("GET", basePath+"&pagination_key=next_page_key", mockResponse2) // Test - quotes, err := service.GetDailyQuotesByCodeAndDateRange("7203", "20240101", "20240131") + quotes, err := service.GetDailyQuotesByCodeAndDateRange(context.Background(), "7203", "20240101", "20240131") if err != nil { t.Errorf("GetDailyQuotesByCodeAndDateRange failed: %v", err) } diff --git a/short_selling.go b/short_selling.go index f2e74a9..815bb7f 100644 --- a/short_selling.go +++ b/short_selling.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" @@ -93,7 +94,7 @@ func (r *ShortSellingResponse) UnmarshalJSON(data []byte) error { } // GetShortSelling は業種別空売り比率を取得します。 -func (s *ShortSellingService) GetShortSelling(params ShortSellingParams) (*ShortSellingResponse, error) { +func (s *ShortSellingService) GetShortSelling(ctx context.Context, params ShortSellingParams) (*ShortSellingResponse, error) { // s33またはdateのいずれかが必須 if params.Sector33Code == "" && params.Date == "" { return nil, fmt.Errorf("either s33 or date parameter is required") @@ -123,7 +124,7 @@ func (s *ShortSellingService) GetShortSelling(params ShortSellingParams) (*Short } var resp ShortSellingResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get short selling: %w", err) } @@ -132,7 +133,7 @@ func (s *ShortSellingService) GetShortSelling(params ShortSellingParams) (*Short // GetShortSellingBySector は指定業種の空売り比率を取得します。 // ページネーションを使用して全データを取得します。 -func (s *ShortSellingService) GetShortSellingBySector(sector33Code string) ([]ShortSelling, error) { +func (s *ShortSellingService) GetShortSellingBySector(ctx context.Context, sector33Code string) ([]ShortSelling, error) { var allData []ShortSelling paginationKey := "" @@ -142,7 +143,7 @@ func (s *ShortSellingService) GetShortSellingBySector(sector33Code string) ([]Sh PaginationKey: paginationKey, } - resp, err := s.GetShortSelling(params) + resp, err := s.GetShortSelling(ctx, params) if err != nil { return nil, err } @@ -161,7 +162,7 @@ func (s *ShortSellingService) GetShortSellingBySector(sector33Code string) ([]Sh // GetShortSellingByDate は指定日の全業種空売り比率を取得します。 // ページネーションを使用して全データを取得します。 -func (s *ShortSellingService) GetShortSellingByDate(date string) ([]ShortSelling, error) { +func (s *ShortSellingService) GetShortSellingByDate(ctx context.Context, date string) ([]ShortSelling, error) { var allData []ShortSelling paginationKey := "" @@ -171,7 +172,7 @@ func (s *ShortSellingService) GetShortSellingByDate(date string) ([]ShortSelling PaginationKey: paginationKey, } - resp, err := s.GetShortSelling(params) + resp, err := s.GetShortSelling(ctx, params) if err != nil { return nil, err } @@ -189,7 +190,7 @@ func (s *ShortSellingService) GetShortSellingByDate(date string) ([]ShortSelling } // GetShortSellingBySectorAndDateRange は指定業種・期間の空売り比率を取得します。 -func (s *ShortSellingService) GetShortSellingBySectorAndDateRange(sector33Code, from, to string) ([]ShortSelling, error) { +func (s *ShortSellingService) GetShortSellingBySectorAndDateRange(ctx context.Context, sector33Code, from, to string) ([]ShortSelling, error) { var allData []ShortSelling paginationKey := "" @@ -201,7 +202,7 @@ func (s *ShortSellingService) GetShortSellingBySectorAndDateRange(sector33Code, PaginationKey: paginationKey, } - resp, err := s.GetShortSelling(params) + resp, err := s.GetShortSelling(ctx, params) if err != nil { return nil, err } @@ -219,8 +220,8 @@ func (s *ShortSellingService) GetShortSellingBySectorAndDateRange(sector33Code, } // GetShortSellingBySectorAndDate は指定業種の指定日の空売り比率を取得します。 -func (s *ShortSellingService) GetShortSellingBySectorAndDate(sector33Code, date string) ([]ShortSelling, error) { - resp, err := s.GetShortSelling(ShortSellingParams{ +func (s *ShortSellingService) GetShortSellingBySectorAndDate(ctx context.Context, sector33Code, date string) ([]ShortSelling, error) { + resp, err := s.GetShortSelling(ctx, ShortSellingParams{ Sector33Code: sector33Code, Date: date, }) diff --git a/short_selling_positions.go b/short_selling_positions.go index 1cd8338..d2ebdfe 100644 --- a/short_selling_positions.go +++ b/short_selling_positions.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" @@ -146,7 +147,7 @@ func (r *ShortSellingPositionsResponse) UnmarshalJSON(data []byte) error { } // GetShortSellingPositions は空売り残高報告を取得します。 -func (s *ShortSellingPositionsService) GetShortSellingPositions(params ShortSellingPositionsParams) (*ShortSellingPositionsResponse, error) { +func (s *ShortSellingPositionsService) GetShortSellingPositions(ctx context.Context, params ShortSellingPositionsParams) (*ShortSellingPositionsResponse, error) { // code、disc_date、calc_dateのいずれかが必須 if params.Code == "" && params.DisclosedDate == "" && params.CalculatedDate == "" { return nil, fmt.Errorf("either code, disc_date, or calc_date parameter is required") @@ -179,7 +180,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositions(params ShortSell } var resp ShortSellingPositionsResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get short selling positions: %w", err) } @@ -188,7 +189,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositions(params ShortSell // GetShortSellingPositionsByCode は指定銘柄の空売り残高報告を取得します。 // ページネーションを使用して全データを取得します。 -func (s *ShortSellingPositionsService) GetShortSellingPositionsByCode(code string) ([]ShortSellingPosition, error) { +func (s *ShortSellingPositionsService) GetShortSellingPositionsByCode(ctx context.Context, code string) ([]ShortSellingPosition, error) { var allData []ShortSellingPosition paginationKey := "" @@ -198,7 +199,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositionsByCode(code strin PaginationKey: paginationKey, } - resp, err := s.GetShortSellingPositions(params) + resp, err := s.GetShortSellingPositions(ctx, params) if err != nil { return nil, err } @@ -217,7 +218,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositionsByCode(code strin // GetShortSellingPositionsByDisclosedDate は指定公表日の全銘柄空売り残高報告を取得します。 // ページネーションを使用して全データを取得します。 -func (s *ShortSellingPositionsService) GetShortSellingPositionsByDisclosedDate(disclosedDate string) ([]ShortSellingPosition, error) { +func (s *ShortSellingPositionsService) GetShortSellingPositionsByDisclosedDate(ctx context.Context, disclosedDate string) ([]ShortSellingPosition, error) { var allData []ShortSellingPosition paginationKey := "" @@ -227,7 +228,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositionsByDisclosedDate(d PaginationKey: paginationKey, } - resp, err := s.GetShortSellingPositions(params) + resp, err := s.GetShortSellingPositions(ctx, params) if err != nil { return nil, err } @@ -246,7 +247,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositionsByDisclosedDate(d // GetShortSellingPositionsByCalculatedDate は指定計算日の全銘柄空売り残高報告を取得します。 // ページネーションを使用して全データを取得します。 -func (s *ShortSellingPositionsService) GetShortSellingPositionsByCalculatedDate(calculatedDate string) ([]ShortSellingPosition, error) { +func (s *ShortSellingPositionsService) GetShortSellingPositionsByCalculatedDate(ctx context.Context, calculatedDate string) ([]ShortSellingPosition, error) { var allData []ShortSellingPosition paginationKey := "" @@ -256,7 +257,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositionsByCalculatedDate( PaginationKey: paginationKey, } - resp, err := s.GetShortSellingPositions(params) + resp, err := s.GetShortSellingPositions(ctx, params) if err != nil { return nil, err } @@ -274,7 +275,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositionsByCalculatedDate( } // GetShortSellingPositionsByCodeAndDateRange は指定銘柄・期間の空売り残高報告を取得します。 -func (s *ShortSellingPositionsService) GetShortSellingPositionsByCodeAndDateRange(code, fromDate, toDate string) ([]ShortSellingPosition, error) { +func (s *ShortSellingPositionsService) GetShortSellingPositionsByCodeAndDateRange(ctx context.Context, code, fromDate, toDate string) ([]ShortSellingPosition, error) { var allData []ShortSellingPosition paginationKey := "" @@ -286,7 +287,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositionsByCodeAndDateRang PaginationKey: paginationKey, } - resp, err := s.GetShortSellingPositions(params) + resp, err := s.GetShortSellingPositions(ctx, params) if err != nil { return nil, err } @@ -304,7 +305,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositionsByCodeAndDateRang } // GetShortSellingPositionsByCodeAndDisclosedDate は指定銘柄の指定公表日の空売り残高報告を取得します。 -func (s *ShortSellingPositionsService) GetShortSellingPositionsByCodeAndDisclosedDate(code, disclosedDate string) ([]ShortSellingPosition, error) { +func (s *ShortSellingPositionsService) GetShortSellingPositionsByCodeAndDisclosedDate(ctx context.Context, code, disclosedDate string) ([]ShortSellingPosition, error) { var allData []ShortSellingPosition paginationKey := "" @@ -315,7 +316,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositionsByCodeAndDisclose PaginationKey: paginationKey, } - resp, err := s.GetShortSellingPositions(params) + resp, err := s.GetShortSellingPositions(ctx, params) if err != nil { return nil, err } @@ -332,7 +333,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositionsByCodeAndDisclose } // GetShortSellingPositionsByCodeAndCalculatedDate は指定銘柄の指定計算日の空売り残高報告を取得します。 -func (s *ShortSellingPositionsService) GetShortSellingPositionsByCodeAndCalculatedDate(code, calculatedDate string) ([]ShortSellingPosition, error) { +func (s *ShortSellingPositionsService) GetShortSellingPositionsByCodeAndCalculatedDate(ctx context.Context, code, calculatedDate string) ([]ShortSellingPosition, error) { var allData []ShortSellingPosition paginationKey := "" @@ -343,7 +344,7 @@ func (s *ShortSellingPositionsService) GetShortSellingPositionsByCodeAndCalculat PaginationKey: paginationKey, } - resp, err := s.GetShortSellingPositions(params) + resp, err := s.GetShortSellingPositions(ctx, params) if err != nil { return nil, err } diff --git a/short_selling_positions_test.go b/short_selling_positions_test.go index 529316b..46046c6 100644 --- a/short_selling_positions_test.go +++ b/short_selling_positions_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -101,7 +102,7 @@ func TestShortSellingPositionsService_GetShortSellingPositions(t *testing.T) { } // Execute - resp, err := service.GetShortSellingPositions(tt.params) + resp, err := service.GetShortSellingPositions(context.Background(), tt.params) // Verify if tt.wantErr { @@ -134,7 +135,7 @@ func TestShortSellingPositionsService_GetShortSellingPositions_RequiresParameter service := NewShortSellingPositionsService(mockClient) // Execute with empty parameters - _, err := service.GetShortSellingPositions(ShortSellingPositionsParams{}) + _, err := service.GetShortSellingPositions(context.Background(), ShortSellingPositionsParams{}) // Verify if err == nil { @@ -193,7 +194,7 @@ func TestShortSellingPositionsService_GetShortSellingPositionsByCode(t *testing. mockClient.SetResponse("GET", "/markets/short-sale-report?code=86970&pagination_key=next_page_key", mockResponse2) // Execute - data, err := service.GetShortSellingPositionsByCode("86970") + data, err := service.GetShortSellingPositionsByCode(context.Background(), "86970") // Verify if err != nil { @@ -237,7 +238,7 @@ func TestShortSellingPositionsService_GetShortSellingPositionsByDisclosedDate(t mockClient.SetResponse("GET", "/markets/short-sale-report?disc_date=20240801", mockResponse) // Execute - data, err := service.GetShortSellingPositionsByDisclosedDate("20240801") + data, err := service.GetShortSellingPositionsByDisclosedDate(context.Background(), "20240801") // Verify if err != nil { @@ -274,7 +275,7 @@ func TestShortSellingPositionsService_GetShortSellingPositionsByCalculatedDate(t mockClient.SetResponse("GET", "/markets/short-sale-report?calc_date=20240731", mockResponse) // Execute - data, err := service.GetShortSellingPositionsByCalculatedDate("20240731") + data, err := service.GetShortSellingPositionsByCalculatedDate(context.Background(), "20240731") // Verify if err != nil { @@ -312,7 +313,7 @@ func TestShortSellingPositionsService_GetShortSellingPositionsByCodeAndDateRange mockClient.SetResponse("GET", "/markets/short-sale-report?code=86970&disc_date_from=20240101&disc_date_to=20240331", mockResponse) // Execute - data, err := service.GetShortSellingPositionsByCodeAndDateRange("86970", "20240101", "20240331") + data, err := service.GetShortSellingPositionsByCodeAndDateRange(context.Background(), "86970", "20240101", "20240331") // Verify if err != nil { @@ -350,7 +351,7 @@ func TestShortSellingPositionsService_GetShortSellingPositionsByCodeAndDisclosed mockClient.SetResponse("GET", "/markets/short-sale-report?code=86970&disc_date=20240801", mockResponse) // Execute - data, err := service.GetShortSellingPositionsByCodeAndDisclosedDate("86970", "20240801") + data, err := service.GetShortSellingPositionsByCodeAndDisclosedDate(context.Background(), "86970", "20240801") // Verify if err != nil { @@ -389,7 +390,7 @@ func TestShortSellingPositionsService_GetShortSellingPositionsByCodeAndCalculate mockClient.SetResponse("GET", "/markets/short-sale-report?code=86970&calc_date=20240731", mockResponse) // Execute - data, err := service.GetShortSellingPositionsByCodeAndCalculatedDate("86970", "20240731") + data, err := service.GetShortSellingPositionsByCodeAndCalculatedDate(context.Background(), "86970", "20240731") // Verify if err != nil { @@ -595,7 +596,7 @@ func TestShortSellingPositionsService_GetShortSellingPositions_Error(t *testing. mockClient.SetError("GET", "/markets/short-sale-report?code=86970", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetShortSellingPositions(ShortSellingPositionsParams{Code: "86970"}) + _, err := service.GetShortSellingPositions(context.Background(), ShortSellingPositionsParams{Code: "86970"}) // Verify if err == nil { diff --git a/short_selling_test.go b/short_selling_test.go index 84c4c64..fb8b6aa 100644 --- a/short_selling_test.go +++ b/short_selling_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -68,7 +69,7 @@ func TestShortSellingService_GetShortSelling(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Execute - resp, err := service.GetShortSelling(tt.params) + resp, err := service.GetShortSelling(context.Background(), tt.params) // Verify if err != nil { @@ -94,7 +95,7 @@ func TestShortSellingService_GetShortSelling_RequiresSectorOrDate(t *testing.T) service := NewShortSellingService(mockClient) // Execute with empty sector and date - _, err := service.GetShortSelling(ShortSellingParams{}) + _, err := service.GetShortSelling(context.Background(), ShortSellingParams{}) // Verify if err == nil { @@ -149,7 +150,7 @@ func TestShortSellingService_GetShortSellingBySector(t *testing.T) { mockClient.SetResponse("GET", "/markets/short-ratio?s33=0050&pagination_key=next_page_key", mockResponse2) // Execute - data, err := service.GetShortSellingBySector("0050") + data, err := service.GetShortSellingBySector(context.Background(), "0050") // Verify if err != nil { @@ -193,7 +194,7 @@ func TestShortSellingService_GetShortSellingByDate(t *testing.T) { mockClient.SetResponse("GET", "/markets/short-ratio?date=20221025", mockResponse) // Execute - data, err := service.GetShortSellingByDate("20221025") + data, err := service.GetShortSellingByDate(context.Background(), "20221025") // Verify if err != nil { @@ -237,7 +238,7 @@ func TestShortSellingService_GetShortSellingBySectorAndDateRange(t *testing.T) { mockClient.SetResponse("GET", "/markets/short-ratio?s33=0050&from=20220101&to=20221231", mockResponse) // Execute - data, err := service.GetShortSellingBySectorAndDateRange("0050", "20220101", "20221231") + data, err := service.GetShortSellingBySectorAndDateRange(context.Background(), "0050", "20220101", "20221231") // Verify if err != nil { @@ -274,7 +275,7 @@ func TestShortSellingService_GetShortSellingBySectorAndDate(t *testing.T) { mockClient.SetResponse("GET", "/markets/short-ratio?s33=0050&date=20221025", mockResponse) // Execute - data, err := service.GetShortSellingBySectorAndDate("0050", "20221025") + data, err := service.GetShortSellingBySectorAndDate(context.Background(), "0050", "20221025") // Verify if err != nil { @@ -419,7 +420,7 @@ func TestShortSellingService_GetShortSelling_Error(t *testing.T) { mockClient.SetError("GET", "/markets/short-ratio?s33=0050", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetShortSelling(ShortSellingParams{Sector33Code: "0050"}) + _, err := service.GetShortSelling(context.Background(), ShortSellingParams{Sector33Code: "0050"}) // Verify if err == nil { diff --git a/statements.go b/statements.go index b293c71..bbaace3 100644 --- a/statements.go +++ b/statements.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" @@ -487,7 +488,7 @@ type StatementsParams struct { // - Code: 銘柄コード(例: "7203" または "72030") // - Date: 開示日付(例: "20240101" または "2024-01-01") // - PaginationKey: ページネーション用キー -func (s *StatementsService) GetStatements(params StatementsParams) (*StatementsResponse, error) { +func (s *StatementsService) GetStatements(ctx context.Context, params StatementsParams) (*StatementsResponse, error) { path := "/fins/summary" query := "?" @@ -506,7 +507,7 @@ func (s *StatementsService) GetStatements(params StatementsParams) (*StatementsR } var resp StatementsResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get statements: %w", err) } @@ -515,12 +516,12 @@ func (s *StatementsService) GetStatements(params StatementsParams) (*StatementsR // GetAllStatementsByCode は指定銘柄の全期間の財務諸表データを取得します。 // ページネーションを使用して全データを取得します。 -func (s *StatementsService) GetAllStatementsByCode(code string) ([]Statement, error) { +func (s *StatementsService) GetAllStatementsByCode(ctx context.Context, code string) ([]Statement, error) { var allStatements []Statement paginationKey := "" for { - resp, err := s.GetStatements(StatementsParams{ + resp, err := s.GetStatements(ctx, StatementsParams{ Code: code, PaginationKey: paginationKey, }) @@ -540,8 +541,8 @@ func (s *StatementsService) GetAllStatementsByCode(code string) ([]Statement, er } // GetStatementsByCodeAndDate は指定銘柄の指定日の財務諸表データを取得します。 -func (s *StatementsService) GetStatementsByCodeAndDate(code, date string) ([]Statement, error) { - resp, err := s.GetStatements(StatementsParams{ +func (s *StatementsService) GetStatementsByCodeAndDate(ctx context.Context, code, date string) ([]Statement, error) { + resp, err := s.GetStatements(ctx, StatementsParams{ Code: code, Date: date, }) @@ -553,12 +554,12 @@ func (s *StatementsService) GetStatementsByCodeAndDate(code, date string) ([]Sta // GetStatementsByDate は指定日の全銘柄の財務諸表データを取得します。 // ページネーションを使用して全データを取得します。 -func (s *StatementsService) GetStatementsByDate(date string) ([]Statement, error) { +func (s *StatementsService) GetStatementsByDate(ctx context.Context, date string) ([]Statement, error) { var allStatements []Statement paginationKey := "" for { - resp, err := s.GetStatements(StatementsParams{ + resp, err := s.GetStatements(ctx, StatementsParams{ Date: date, PaginationKey: paginationKey, }) @@ -579,8 +580,8 @@ func (s *StatementsService) GetStatementsByDate(date string) ([]Statement, error // GetLatestStatements は指定銘柄の最新財務諸表を取得します。 // 例: GetLatestStatements("7203") でトヨタ自動車の最新決算データを取得 -func (s *StatementsService) GetLatestStatements(code string) (*Statement, error) { - statements, err := s.GetAllStatementsByCode(code) +func (s *StatementsService) GetLatestStatements(ctx context.Context, code string) (*Statement, error) { + statements, err := s.GetAllStatementsByCode(ctx, code) if err != nil { return nil, err } diff --git a/statements_test.go b/statements_test.go index 6027be8..38b98fb 100644 --- a/statements_test.go +++ b/statements_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" "testing" @@ -97,7 +98,7 @@ func TestStatementsService_GetStatements(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Test - resp, err := service.GetStatements(tt.params) + resp, err := service.GetStatements(context.Background(), tt.params) if err != nil { t.Errorf("GetStatements failed: %v", err) } @@ -148,7 +149,7 @@ func TestStatementsService_GetLatestStatements(t *testing.T) { mockClient.SetResponse("GET", "/fins/summary?code=7203", mockResponse) // Test - statement, err := service.GetLatestStatements("7203") + statement, err := service.GetLatestStatements(context.Background(), "7203") if err != nil { t.Errorf("GetLatestStatements failed: %v", err) } @@ -180,7 +181,7 @@ func TestStatementsService_GetLatestStatements_NotFound(t *testing.T) { mockClient.SetResponse("GET", "/fins/summary?code=9999", mockResponse) // Test - _, err := service.GetLatestStatements("9999") + _, err := service.GetLatestStatements(context.Background(), "9999") if err == nil { t.Errorf("Expected error for non-existent company, got nil") } @@ -195,7 +196,7 @@ func TestStatementsService_GetStatements_Error(t *testing.T) { mockClient.SetError("GET", "/fins/summary?code=7203", fmt.Errorf("API error")) // Test - _, err := service.GetStatements(StatementsParams{Code: "7203"}) + _, err := service.GetStatements(context.Background(), StatementsParams{Code: "7203"}) if err == nil { t.Errorf("Expected error, got nil") } @@ -220,7 +221,7 @@ func TestStatementsService_GetStatementsByCodeAndDate(t *testing.T) { mockClient.SetResponse("GET", "/fins/summary?code=7203&date=2024-01-15", mockResponse) // Test - statements, err := service.GetStatementsByCodeAndDate("7203", "2024-01-15") + statements, err := service.GetStatementsByCodeAndDate(context.Background(), "7203", "2024-01-15") if err != nil { t.Errorf("GetStatementsByCodeAndDate failed: %v", err) } @@ -280,7 +281,7 @@ func TestStatementsService_GetStatementsByDate(t *testing.T) { mockClient.SetResponse("GET", "/fins/summary?date=2024-01-15&pagination_key=next_page_key", mockResponse2) // Test - statements, err := service.GetStatementsByDate("2024-01-15") + statements, err := service.GetStatementsByDate(context.Background(), "2024-01-15") if err != nil { t.Errorf("GetStatementsByDate failed: %v", err) } diff --git a/test/e2e/announcement_test.go b/test/e2e/announcement_test.go index 4d4868c..4e9ba70 100644 --- a/test/e2e/announcement_test.go +++ b/test/e2e/announcement_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" "github.com/utahta/jquants" @@ -14,7 +15,7 @@ func TestAnnouncementEndpoint(t *testing.T) { t.Run("GetAnnouncement_Default", func(t *testing.T) { // デフォルト(翌営業日)の決算発表予定を取得 params := jquants.AnnouncementParams{} - resp, err := jq.Announcement.GetAnnouncement(params) + resp, err := jq.Announcement.GetAnnouncement(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -127,7 +128,7 @@ func TestAnnouncementEndpoint(t *testing.T) { params := jquants.AnnouncementParams{} - resp, err := jq.Announcement.GetAnnouncement(params) + resp, err := jq.Announcement.GetAnnouncement(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -147,7 +148,7 @@ func TestAnnouncementEndpoint(t *testing.T) { // ページネーションのテスト params := jquants.AnnouncementParams{} - resp, err := jq.Announcement.GetAnnouncement(params) + resp, err := jq.Announcement.GetAnnouncement(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -165,7 +166,7 @@ func TestAnnouncementEndpoint(t *testing.T) { if resp.PaginationKey != "" { // 次のページを取得 params.PaginationKey = resp.PaginationKey - resp2, err := jq.Announcement.GetAnnouncement(params) + resp2, err := jq.Announcement.GetAnnouncement(context.Background(), params) if err != nil { t.Fatalf("Failed to get next page: %v", err) } @@ -185,7 +186,7 @@ func TestAnnouncementEndpoint(t *testing.T) { t.Run("GetAnnouncement_SectorAnalysis", func(t *testing.T) { // 業種別の分析 params := jquants.AnnouncementParams{} - resp, err := jq.Announcement.GetAnnouncement(params) + resp, err := jq.Announcement.GetAnnouncement(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -212,7 +213,7 @@ func TestAnnouncementEndpoint(t *testing.T) { t.Run("GetAnnouncement_QuarterAnalysis", func(t *testing.T) { // 決算四半期別の分析 params := jquants.AnnouncementParams{} - resp, err := jq.Announcement.GetAnnouncement(params) + resp, err := jq.Announcement.GetAnnouncement(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") diff --git a/test/e2e/breakdown_test.go b/test/e2e/breakdown_test.go index 0f2c3a8..ebc6a54 100644 --- a/test/e2e/breakdown_test.go +++ b/test/e2e/breakdown_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" "time" @@ -14,7 +15,7 @@ import ( func TestBreakdownEndpoint(t *testing.T) { t.Run("GetBreakdown_ByCode", func(t *testing.T) { // トヨタ自動車の売買内訳データを取得 - breakdowns, err := jq.Breakdown.GetBreakdownByCode("7203", 30) + breakdowns, err := jq.Breakdown.GetBreakdownByCode(context.Background(), "7203", 30) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -123,7 +124,7 @@ func TestBreakdownEndpoint(t *testing.T) { Date: date, } - resp, err := jq.Breakdown.GetBreakdown(params) + resp, err := jq.Breakdown.GetBreakdown(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -169,7 +170,7 @@ func TestBreakdownEndpoint(t *testing.T) { To: to, } - resp, err := jq.Breakdown.GetBreakdown(params) + resp, err := jq.Breakdown.GetBreakdown(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -200,7 +201,7 @@ func TestBreakdownEndpoint(t *testing.T) { Date: date, } - resp, err := jq.Breakdown.GetBreakdown(params) + resp, err := jq.Breakdown.GetBreakdown(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -218,7 +219,7 @@ func TestBreakdownEndpoint(t *testing.T) { if resp.PaginationKey != "" { // 次のページを取得 params.PaginationKey = resp.PaginationKey - resp2, err := jq.Breakdown.GetBreakdown(params) + resp2, err := jq.Breakdown.GetBreakdown(context.Background(), params) if err != nil { t.Fatalf("Failed to get next page: %v", err) } @@ -231,7 +232,7 @@ func TestBreakdownEndpoint(t *testing.T) { t.Run("GetBreakdown_Analysis", func(t *testing.T) { // 売買内訳データの分析 - breakdowns, err := jq.Breakdown.GetBreakdownByCode("7203", 10) + breakdowns, err := jq.Breakdown.GetBreakdownByCode(context.Background(), "7203", 10) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") diff --git a/test/e2e/daily_margin_interest_test.go b/test/e2e/daily_margin_interest_test.go index 5dad601..5e2b350 100644 --- a/test/e2e/daily_margin_interest_test.go +++ b/test/e2e/daily_margin_interest_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" "github.com/utahta/jquants" @@ -18,7 +19,7 @@ func TestDailyMarginInterestEndpoint(t *testing.T) { Code: "13260", // 日々公表銘柄として一般的な銘柄 } - resp, err := jq.DailyMarginInterest.GetDailyMarginInterest(params) + resp, err := jq.DailyMarginInterest.GetDailyMarginInterest(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -113,7 +114,7 @@ func TestDailyMarginInterestEndpoint(t *testing.T) { Date: date, } - resp, err := jq.DailyMarginInterest.GetDailyMarginInterest(params) + resp, err := jq.DailyMarginInterest.GetDailyMarginInterest(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -167,7 +168,7 @@ func TestDailyMarginInterestEndpoint(t *testing.T) { t.Run("GetDailyMarginInterestByCode_Convenience", func(t *testing.T) { // 便利メソッドのテスト - interests, err := jq.DailyMarginInterest.GetDailyMarginInterestByCode("13260") + interests, err := jq.DailyMarginInterest.GetDailyMarginInterestByCode(context.Background(), "13260") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -194,7 +195,7 @@ func TestDailyMarginInterestEndpoint(t *testing.T) { // 便利メソッドのテスト(日付指定) date := getTestDate() - interests, err := jq.DailyMarginInterest.GetDailyMarginInterestByDate(date) + interests, err := jq.DailyMarginInterest.GetDailyMarginInterestByDate(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -237,7 +238,7 @@ func TestDailyMarginInterestEndpoint(t *testing.T) { to := getTestDate() from := "20250601" // 約2週間分 - interests, err := jq.DailyMarginInterest.GetDailyMarginInterestByCodeAndDateRange("13260", from, to) + interests, err := jq.DailyMarginInterest.GetDailyMarginInterestByCodeAndDateRange(context.Background(), "13260", from, to) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -271,7 +272,7 @@ func TestDailyMarginInterestEndpoint(t *testing.T) { Date: getTestDate(), } - resp, err := jq.DailyMarginInterest.GetDailyMarginInterest(params) + resp, err := jq.DailyMarginInterest.GetDailyMarginInterest(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -305,7 +306,7 @@ func TestDailyMarginInterestEndpoint(t *testing.T) { Date: getTestDate(), } - resp, err := jq.DailyMarginInterest.GetDailyMarginInterest(params) + resp, err := jq.DailyMarginInterest.GetDailyMarginInterest(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -334,7 +335,7 @@ func TestDailyMarginInterestEndpoint(t *testing.T) { // パラメータなしはエラー params := jquants.DailyMarginInterestParams{} - _, err := jq.DailyMarginInterest.GetDailyMarginInterest(params) + _, err := jq.DailyMarginInterest.GetDailyMarginInterest(context.Background(), params) if err == nil { t.Error("Expected error for empty parameters") } @@ -344,7 +345,7 @@ func TestDailyMarginInterestEndpoint(t *testing.T) { Code: "99999", } - resp, err := jq.DailyMarginInterest.GetDailyMarginInterest(params) + resp, err := jq.DailyMarginInterest.GetDailyMarginInterest(context.Background(), params) if err == nil && resp != nil && len(resp.Data) > 0 { t.Error("Expected empty result for invalid code") } diff --git a/test/e2e/daily_quotes_test.go b/test/e2e/daily_quotes_test.go index c22fb84..5ce4bf9 100644 --- a/test/e2e/daily_quotes_test.go +++ b/test/e2e/daily_quotes_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "fmt" "testing" "time" @@ -26,7 +27,7 @@ func TestDailyQuotesEndpoint(t *testing.T) { To: to, } - resp, err := jq.Quotes.GetDailyQuotes(params) + resp, err := jq.Quotes.GetDailyQuotes(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -168,7 +169,7 @@ func TestDailyQuotesEndpoint(t *testing.T) { Date: date, } - resp, err := jq.Quotes.GetDailyQuotes(params) + resp, err := jq.Quotes.GetDailyQuotes(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -213,7 +214,7 @@ func TestDailyQuotesEndpoint(t *testing.T) { Date: date, } - resp, err := jq.Quotes.GetDailyQuotes(params) + resp, err := jq.Quotes.GetDailyQuotes(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -231,7 +232,7 @@ func TestDailyQuotesEndpoint(t *testing.T) { if resp.PaginationKey != "" { // 次のページを取得 params.PaginationKey = resp.PaginationKey - resp2, err := jq.Quotes.GetDailyQuotes(params) + resp2, err := jq.Quotes.GetDailyQuotes(context.Background(), params) if err != nil { t.Fatalf("Failed to get next page: %v", err) } @@ -249,7 +250,7 @@ func TestDailyQuotesEndpoint(t *testing.T) { t.Run("GetDailyQuotesByCode_Convenience", func(t *testing.T) { // 便利メソッドのテスト(全期間) - quotes, err := jq.Quotes.GetDailyQuotesByCode("7203") + quotes, err := jq.Quotes.GetDailyQuotesByCode(context.Background(), "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -298,7 +299,7 @@ func TestDailyQuotesEndpoint(t *testing.T) { Date: getTestDate(), } - resp, err := jq.Quotes.GetDailyQuotes(params) + resp, err := jq.Quotes.GetDailyQuotes(context.Background(), params) if err == nil && len(resp.Data) > 0 { t.Error("Expected no data for invalid code") } @@ -310,7 +311,7 @@ func TestDailyQuotesEndpoint(t *testing.T) { Date: futureDate, } - resp, err = jq.Quotes.GetDailyQuotes(params) + resp, err = jq.Quotes.GetDailyQuotes(context.Background(), params) if err == nil && len(resp.Data) > 0 { t.Error("Expected no data for future date") } diff --git a/test/e2e/fs_details_test.go b/test/e2e/fs_details_test.go index 64d014a..c40670b 100644 --- a/test/e2e/fs_details_test.go +++ b/test/e2e/fs_details_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" "time" @@ -14,7 +15,7 @@ import ( func TestFSDetailsEndpoint(t *testing.T) { t.Run("GetFSDetails_ByCode", func(t *testing.T) { // トヨタ自動車の財務諸表詳細を取得 - details, err := jq.FSDetails.GetFSDetailsByCode("7203") + details, err := jq.FSDetails.GetFSDetailsByCode(context.Background(), "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -200,7 +201,7 @@ func TestFSDetailsEndpoint(t *testing.T) { Date: date, } - details, err := jq.FSDetails.GetFSDetails(params) + details, err := jq.FSDetails.GetFSDetails(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -231,7 +232,7 @@ func TestFSDetailsEndpoint(t *testing.T) { t.Run("GetFSDetails_ProfitabilityAnalysis", func(t *testing.T) { // トヨタ自動車の収益性分析 - details, err := jq.FSDetails.GetFSDetailsByCode("7203") + details, err := jq.FSDetails.GetFSDetailsByCode(context.Background(), "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -288,7 +289,7 @@ func TestFSDetailsEndpoint(t *testing.T) { t.Run("GetFSDetails_GrowthAnalysis", func(t *testing.T) { // 成長性分析 - details, err := jq.FSDetails.GetFSDetailsByCode("7203") + details, err := jq.FSDetails.GetFSDetailsByCode(context.Background(), "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -347,7 +348,7 @@ func TestFSDetailsEndpoint(t *testing.T) { Code: "7203", } - details, err := jq.FSDetails.GetFSDetails(params) + details, err := jq.FSDetails.GetFSDetails(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -376,7 +377,7 @@ func TestFSDetailsEndpoint(t *testing.T) { // エラーケースのテスト // 存在しない銘柄コード - details, err := jq.FSDetails.GetFSDetailsByCode("99999") + details, err := jq.FSDetails.GetFSDetailsByCode(context.Background(), "99999") if err == nil && len(details) > 0 { t.Error("Expected error or empty result for invalid code") } @@ -386,7 +387,7 @@ func TestFSDetailsEndpoint(t *testing.T) { Date: "invalid-date", } - resp, err := jq.FSDetails.GetFSDetails(params) + resp, err := jq.FSDetails.GetFSDetails(context.Background(), params) if err == nil && resp != nil && len(resp.Data) > 0 { t.Error("Expected error or empty result for invalid date") } diff --git a/test/e2e/futures_test.go b/test/e2e/futures_test.go index 1fbc6e4..65fe42f 100644 --- a/test/e2e/futures_test.go +++ b/test/e2e/futures_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" "github.com/utahta/jquants" @@ -15,7 +16,7 @@ func TestFuturesEndpoint(t *testing.T) { // 最近の営業日の先物四本値を取得 date := getTestDate() - futures, err := jq.Futures.GetFuturesByDate(date) + futures, err := jq.Futures.GetFuturesByDate(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -209,7 +210,7 @@ func TestFuturesEndpoint(t *testing.T) { // 特定カテゴリ(日経225先物)のみを取得 date := getTestDate() - futures, err := jq.Futures.GetFuturesByCategory(date, "NK225F") + futures, err := jq.Futures.GetFuturesByCategory(context.Background(), date, "NK225F") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -235,7 +236,7 @@ func TestFuturesEndpoint(t *testing.T) { // 中心限月のみを取得 date := getTestDate() - futures, err := jq.Futures.GetCentralContractMonthFutures(date) + futures, err := jq.Futures.GetCentralContractMonthFutures(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -262,7 +263,7 @@ func TestFuturesEndpoint(t *testing.T) { // 限月別の分析 date := getTestDate() - futures, err := jq.Futures.GetFuturesByDate(date) + futures, err := jq.Futures.GetFuturesByDate(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -309,7 +310,7 @@ func TestFuturesEndpoint(t *testing.T) { // 商品区分別の分析 date := getTestDate() - futures, err := jq.Futures.GetFuturesByDate(date) + futures, err := jq.Futures.GetFuturesByDate(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -349,7 +350,7 @@ func TestFuturesEndpoint(t *testing.T) { // 価格・ボラティリティ分析 date := getTestDate() - futures, err := jq.Futures.GetFuturesByDate(date) + futures, err := jq.Futures.GetFuturesByDate(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -392,7 +393,7 @@ func TestFuturesEndpoint(t *testing.T) { // セッション分析(ナイト・日中・前場) date := getTestDate() - futures, err := jq.Futures.GetFuturesByDate(date) + futures, err := jq.Futures.GetFuturesByDate(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -445,7 +446,7 @@ func TestFuturesEndpoint(t *testing.T) { Date: date, } - resp, err := jq.Futures.GetFutures(params) + resp, err := jq.Futures.GetFutures(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -481,13 +482,13 @@ func TestFuturesEndpoint(t *testing.T) { // エラーケースのテスト // 未来の日付 - futures, err := jq.Futures.GetFuturesByDate("2030-01-01") + futures, err := jq.Futures.GetFuturesByDate(context.Background(), "2030-01-01") if err == nil && len(futures) > 0 { t.Error("Expected error or empty result for future date") } // 無効な日付形式 - futures, err = jq.Futures.GetFuturesByDate("invalid-date") + futures, err = jq.Futures.GetFuturesByDate(context.Background(), "invalid-date") if err == nil && len(futures) > 0 { t.Error("Expected error or empty result for invalid date format") } @@ -497,13 +498,13 @@ func TestFuturesEndpoint(t *testing.T) { Date: "", } - _, err = jq.Futures.GetFutures(params) + _, err = jq.Futures.GetFutures(context.Background(), params) if err == nil { t.Error("Expected error for missing required date parameter") } // 無効なカテゴリ - futures, err = jq.Futures.GetFuturesByCategory(getTestDate(), "INVALID_CATEGORY") + futures, err = jq.Futures.GetFuturesByCategory(context.Background(), getTestDate(), "INVALID_CATEGORY") if err == nil && len(futures) > 0 { t.Error("Expected error or empty result for invalid category") } diff --git a/test/e2e/index_option_test.go b/test/e2e/index_option_test.go index 443b500..d6039f5 100644 --- a/test/e2e/index_option_test.go +++ b/test/e2e/index_option_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" "github.com/utahta/jquants" @@ -19,7 +20,7 @@ func TestIndexOptionEndpoint(t *testing.T) { Date: date, } - resp, err := jq.IndexOption.GetIndexOptions(params) + resp, err := jq.IndexOption.GetIndexOptions(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -203,7 +204,7 @@ func TestIndexOptionEndpoint(t *testing.T) { // コールオプションのみを取得 date := getTestDate() - options, err := jq.IndexOption.GetCallOptions(date) + options, err := jq.IndexOption.GetCallOptions(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -229,7 +230,7 @@ func TestIndexOptionEndpoint(t *testing.T) { // プットオプションのみを取得 date := getTestDate() - options, err := jq.IndexOption.GetPutOptions(date) + options, err := jq.IndexOption.GetPutOptions(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -255,7 +256,7 @@ func TestIndexOptionEndpoint(t *testing.T) { // オプションチェーンの分析 date := getTestDate() - options, err := jq.IndexOption.GetOptionChain(date) + options, err := jq.IndexOption.GetOptionChain(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -325,7 +326,7 @@ func TestIndexOptionEndpoint(t *testing.T) { Date: date, } - resp, err := jq.IndexOption.GetIndexOptions(params) + resp, err := jq.IndexOption.GetIndexOptions(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -376,7 +377,7 @@ func TestIndexOptionEndpoint(t *testing.T) { Date: date, } - resp, err := jq.IndexOption.GetIndexOptions(params) + resp, err := jq.IndexOption.GetIndexOptions(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -416,7 +417,7 @@ func TestIndexOptionEndpoint(t *testing.T) { Date: date, } - resp, err := jq.IndexOption.GetIndexOptions(params) + resp, err := jq.IndexOption.GetIndexOptions(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -434,7 +435,7 @@ func TestIndexOptionEndpoint(t *testing.T) { if resp.PaginationKey != "" { // 次のページを取得 params.PaginationKey = resp.PaginationKey - resp2, err := jq.IndexOption.GetIndexOptions(params) + resp2, err := jq.IndexOption.GetIndexOptions(context.Background(), params) if err != nil { t.Fatalf("Failed to get next page: %v", err) } @@ -453,7 +454,7 @@ func TestIndexOptionEndpoint(t *testing.T) { Date: "2030-01-01", } - resp, err := jq.IndexOption.GetIndexOptions(params) + resp, err := jq.IndexOption.GetIndexOptions(context.Background(), params) if err == nil && resp != nil && len(resp.Data) > 0 { t.Error("Expected error or empty result for future date") } @@ -463,7 +464,7 @@ func TestIndexOptionEndpoint(t *testing.T) { Date: "invalid-date", } - resp, err = jq.IndexOption.GetIndexOptions(params) + resp, err = jq.IndexOption.GetIndexOptions(context.Background(), params) if err == nil && resp != nil && len(resp.Data) > 0 { t.Error("Expected error or empty result for invalid date format") } @@ -473,7 +474,7 @@ func TestIndexOptionEndpoint(t *testing.T) { Date: "", } - _, err = jq.IndexOption.GetIndexOptions(params) + _, err = jq.IndexOption.GetIndexOptions(context.Background(), params) if err == nil { t.Error("Expected error for missing required date parameter") } diff --git a/test/e2e/indices_test.go b/test/e2e/indices_test.go index 591d147..1e50b3b 100644 --- a/test/e2e/indices_test.go +++ b/test/e2e/indices_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" "github.com/utahta/jquants" @@ -19,7 +20,7 @@ func TestIndicesEndpoint(t *testing.T) { Date: date, } - resp, err := jq.Indices.GetIndices(params) + resp, err := jq.Indices.GetIndices(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -112,7 +113,7 @@ func TestIndicesEndpoint(t *testing.T) { Code: "0000", // 特定の指数コード } - resp, err := jq.Indices.GetIndices(params) + resp, err := jq.Indices.GetIndices(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -140,7 +141,7 @@ func TestIndicesEndpoint(t *testing.T) { Date: date, } - resp, err := jq.Indices.GetIndices(params) + resp, err := jq.Indices.GetIndices(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -158,7 +159,7 @@ func TestIndicesEndpoint(t *testing.T) { if resp.PaginationKey != "" { // 次のページを取得 params.PaginationKey = resp.PaginationKey - resp2, err := jq.Indices.GetIndices(params) + resp2, err := jq.Indices.GetIndices(context.Background(), params) if err != nil { t.Fatalf("Failed to get next page: %v", err) } @@ -178,7 +179,7 @@ func TestIndicesEndpoint(t *testing.T) { t.Run("GetTOPIXCore30", func(t *testing.T) { // TOPIX Core30の便利メソッドテスト - indices, err := jq.Indices.GetTOPIXCore30() + indices, err := jq.Indices.GetTOPIXCore30(context.Background()) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -217,7 +218,7 @@ func TestIndicesEndpoint(t *testing.T) { t.Run("GetTOPIX", func(t *testing.T) { // TOPIXの便利メソッドテスト - indices, err := jq.Indices.GetTOPIX() + indices, err := jq.Indices.GetTOPIX(context.Background()) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -252,7 +253,7 @@ func TestIndicesEndpoint(t *testing.T) { To: "2024-01-31", } - resp, err := jq.Indices.GetIndices(params) + resp, err := jq.Indices.GetIndices(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") diff --git a/test/e2e/listed_test.go b/test/e2e/listed_test.go index 67f8000..b6ff5b7 100644 --- a/test/e2e/listed_test.go +++ b/test/e2e/listed_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" ) @@ -11,7 +12,7 @@ import ( func TestListedEndpoint(t *testing.T) { t.Run("GetAllListedInfo", func(t *testing.T) { // 全ての上場企業情報を取得 - companies, err := jq.Listed.GetAllListedInfo() + companies, err := jq.Listed.GetAllListedInfo(context.Background()) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -88,7 +89,7 @@ func TestListedEndpoint(t *testing.T) { t.Run("GetListedInfoByCode", func(t *testing.T) { // 特定の銘柄コードで企業情報を取得(トヨタ自動車) - infos, err := jq.Listed.GetListedInfoByCode("7203") + infos, err := jq.Listed.GetListedInfoByCode(context.Background(), "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -133,7 +134,7 @@ func TestListedEndpoint(t *testing.T) { t.Run("GetListedInfoByCode_InvalidCode", func(t *testing.T) { // 存在しない銘柄コードでのテスト - infos, err := jq.Listed.GetListedInfoByCode("99999") + infos, err := jq.Listed.GetListedInfoByCode(context.Background(), "99999") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -150,7 +151,7 @@ func TestListedEndpoint(t *testing.T) { t.Run("GetAllListedInfo_MarketSegments", func(t *testing.T) { // 全企業の市場セグメント分析 - companies, err := jq.Listed.GetAllListedInfo() + companies, err := jq.Listed.GetAllListedInfo(context.Background()) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -184,7 +185,7 @@ func TestListedEndpoint(t *testing.T) { t.Run("GetAllListedInfo_SectorAnalysis", func(t *testing.T) { // 業種別分析 - companies, err := jq.Listed.GetAllListedInfo() + companies, err := jq.Listed.GetAllListedInfo(context.Background()) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -223,7 +224,7 @@ func TestListedEndpoint(t *testing.T) { t.Run("GetAllListedInfo_CodeValidation", func(t *testing.T) { // 銘柄コードの形式検証 - companies, err := jq.Listed.GetAllListedInfo() + companies, err := jq.Listed.GetAllListedInfo(context.Background()) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") diff --git a/test/e2e/options_test.go b/test/e2e/options_test.go index 389f0cb..e0e9bb1 100644 --- a/test/e2e/options_test.go +++ b/test/e2e/options_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "fmt" "testing" @@ -20,7 +21,7 @@ func TestOptionsEndpoint(t *testing.T) { Date: date, } - resp, err := jq.Options.GetOptions(params) + resp, err := jq.Options.GetOptions(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -227,7 +228,7 @@ func TestOptionsEndpoint(t *testing.T) { t.Run("GetSecurityOptionsByCode", func(t *testing.T) { // トヨタ自動車の有価証券オプションを取得 date := getTestDate() - options, err := jq.Options.GetSecurityOptionsByCode(date, "7203") + options, err := jq.Options.GetSecurityOptionsByCode(context.Background(), date, "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -257,7 +258,7 @@ func TestOptionsEndpoint(t *testing.T) { t.Run("GetCallOptionsByCode", func(t *testing.T) { // トヨタ自動車のコールオプションのみを取得(フィルタリングで実現) date := getTestDate() - allOptions, err := jq.Options.GetSecurityOptionsByCode(date, "7203") + allOptions, err := jq.Options.GetSecurityOptionsByCode(context.Background(), date, "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -298,7 +299,7 @@ func TestOptionsEndpoint(t *testing.T) { t.Run("GetPutOptionsByCode", func(t *testing.T) { // トヨタ自動車のプットオプションのみを取得(フィルタリングで実現) date := getTestDate() - allOptions, err := jq.Options.GetSecurityOptionsByCode(date, "7203") + allOptions, err := jq.Options.GetSecurityOptionsByCode(context.Background(), date, "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -339,7 +340,7 @@ func TestOptionsEndpoint(t *testing.T) { t.Run("GetOptions_OptionChainAnalysis", func(t *testing.T) { // オプションチェーンの分析(有価証券オプション) date := getTestDate() - options, err := jq.Options.GetSecurityOptionsByCode(date, "7203") + options, err := jq.Options.GetSecurityOptionsByCode(context.Background(), date, "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -414,7 +415,7 @@ func TestOptionsEndpoint(t *testing.T) { Date: date, } - resp, err := jq.Options.GetOptions(params) + resp, err := jq.Options.GetOptions(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -482,7 +483,7 @@ func TestOptionsEndpoint(t *testing.T) { Date: date, } - resp, err := jq.Options.GetOptions(params) + resp, err := jq.Options.GetOptions(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -500,7 +501,7 @@ func TestOptionsEndpoint(t *testing.T) { if resp.PaginationKey != "" { // 次のページを取得 params.PaginationKey = resp.PaginationKey - resp2, err := jq.Options.GetOptions(params) + resp2, err := jq.Options.GetOptions(context.Background(), params) if err != nil { t.Fatalf("Failed to get next page: %v", err) } @@ -516,7 +517,7 @@ func TestOptionsEndpoint(t *testing.T) { // 存在しない銘柄コード date := getTestDate() - options, err := jq.Options.GetSecurityOptionsByCode(date, "99999") + options, err := jq.Options.GetSecurityOptionsByCode(context.Background(), date, "99999") if err == nil && len(options) > 0 { t.Error("Expected error or empty result for invalid code") } @@ -526,7 +527,7 @@ func TestOptionsEndpoint(t *testing.T) { Date: "2030-01-01", } - resp, err := jq.Options.GetOptions(params) + resp, err := jq.Options.GetOptions(context.Background(), params) if err == nil && resp != nil && len(resp.Data) > 0 { t.Error("Expected error or empty result for future date") } @@ -536,7 +537,7 @@ func TestOptionsEndpoint(t *testing.T) { Date: "invalid-date", } - resp2, err := jq.Options.GetOptions(params) + resp2, err := jq.Options.GetOptions(context.Background(), params) if err == nil && resp2 != nil && len(resp2.Data) > 0 { t.Error("Expected error or empty result for invalid date format") } diff --git a/test/e2e/prices_am_test.go b/test/e2e/prices_am_test.go index 0ed59f7..624d596 100644 --- a/test/e2e/prices_am_test.go +++ b/test/e2e/prices_am_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "fmt" "testing" @@ -14,7 +15,7 @@ import ( func TestPricesAMEndpoint(t *testing.T) { t.Run("GetPricesAM_ByCode", func(t *testing.T) { // トヨタ自動車の前場四本値を取得 - resp, err := jq.PricesAM.GetPricesAMByCode("7203") + resp, err := jq.PricesAM.GetPricesAMByCode(context.Background(), "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -119,7 +120,7 @@ func TestPricesAMEndpoint(t *testing.T) { // 全銘柄の前場四本値を取得(当日のデータのみ利用可能) params := jquants.PricesAMParams{} - resp, err := jq.PricesAM.GetPricesAM(params) + resp, err := jq.PricesAM.GetPricesAM(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -162,7 +163,7 @@ func TestPricesAMEndpoint(t *testing.T) { // 市場全体の前場四本値分析(当日のデータのみ) params := jquants.PricesAMParams{} - resp, err := jq.PricesAM.GetPricesAM(params) + resp, err := jq.PricesAM.GetPricesAM(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -216,7 +217,7 @@ func TestPricesAMEndpoint(t *testing.T) { // ページネーションのテスト(当日のデータのみ) params := jquants.PricesAMParams{} - resp, err := jq.PricesAM.GetPricesAM(params) + resp, err := jq.PricesAM.GetPricesAM(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") @@ -234,7 +235,7 @@ func TestPricesAMEndpoint(t *testing.T) { if resp.PaginationKey != "" { // 次のページを取得 params.PaginationKey = resp.PaginationKey - resp2, err := jq.PricesAM.GetPricesAM(params) + resp2, err := jq.PricesAM.GetPricesAM(context.Background(), params) if err != nil { t.Fatalf("Failed to get next page: %v", err) } @@ -249,7 +250,7 @@ func TestPricesAMEndpoint(t *testing.T) { // エラーケースのテスト // 存在しない銘柄コード - resp, err := jq.PricesAM.GetPricesAMByCode("99999") + resp, err := jq.PricesAM.GetPricesAMByCode(context.Background(), "99999") if err == nil && resp != nil && len(resp.Data) > 0 { t.Error("Expected error or empty result for invalid code") } @@ -259,7 +260,7 @@ func TestPricesAMEndpoint(t *testing.T) { Code: "invalid-code", } - resp, err = jq.PricesAM.GetPricesAM(params) + resp, err = jq.PricesAM.GetPricesAM(context.Background(), params) if err == nil && resp != nil && len(resp.Data) > 0 { t.Error("Expected error or empty result for invalid code") } diff --git a/test/e2e/short_selling_positions_test.go b/test/e2e/short_selling_positions_test.go index 77c7676..cc75e67 100644 --- a/test/e2e/short_selling_positions_test.go +++ b/test/e2e/short_selling_positions_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" "time" ) @@ -12,7 +13,7 @@ import ( func TestShortSellingPositionsEndpoint(t *testing.T) { t.Run("GetShortSellingPositions_ByCode", func(t *testing.T) { // トヨタ自動車の空売り残高報告を取得 - positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCode("7203") + positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCode(context.Background(), "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -114,7 +115,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { // 最近の金曜日の全銘柄空売り残高報告を取得 disclosedDate := getRecentFriday() - positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByDisclosedDate(disclosedDate) + positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByDisclosedDate(context.Background(), disclosedDate) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -168,7 +169,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { t.Run("GetShortSellingPositions_PositionAnalysis", func(t *testing.T) { // トヨタ自動車の残高変化分析 - positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCode("7203") + positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCode(context.Background(), "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -226,7 +227,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { to := time.Now().Format("2006-01-02") from := time.Now().AddDate(0, -1, 0).Format("2006-01-02") - positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCodeAndDateRange("7203", from, to) + positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCodeAndDateRange(context.Background(), "7203", from, to) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -272,7 +273,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { t.Run("GetShortSellingPositions_ThresholdAnalysis", func(t *testing.T) { // 閾値分析(報告義務の閾値分析) - positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCode("7203") + positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCode(context.Background(), "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -324,13 +325,13 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { // エラーケースのテスト // 存在しない銘柄コード - positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCode("99999") + positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCode(context.Background(), "99999") if err == nil && len(positions) > 0 { t.Error("Expected error or empty result for invalid code") } // 無効な日付 - positions, err = jq.ShortSellingPositions.GetShortSellingPositionsByDisclosedDate("invalid-date") + positions, err = jq.ShortSellingPositions.GetShortSellingPositionsByDisclosedDate(context.Background(), "invalid-date") if err == nil && len(positions) > 0 { t.Error("Expected error or empty result for invalid date") } diff --git a/test/e2e/short_selling_test.go b/test/e2e/short_selling_test.go index 66e5d47..28ac82b 100644 --- a/test/e2e/short_selling_test.go +++ b/test/e2e/short_selling_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" ) @@ -13,7 +14,7 @@ func TestShortSellingEndpoint(t *testing.T) { // 最近の営業日の業種別空売り比率を取得 date := getTestDate() - shorts, err := jq.ShortSelling.GetShortSellingByDate(date) + shorts, err := jq.ShortSelling.GetShortSellingByDate(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -99,7 +100,7 @@ func TestShortSellingEndpoint(t *testing.T) { // 特定業種(輸送用機器:3050)の空売り比率データを取得 sectorCode := "3050" - shorts, err := jq.ShortSelling.GetShortSellingBySector(sectorCode) + shorts, err := jq.ShortSelling.GetShortSellingBySector(context.Background(), sectorCode) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -150,7 +151,7 @@ func TestShortSellingEndpoint(t *testing.T) { // 最新日の全業種の空売り比率分析 date := getTestDate() - shorts, err := jq.ShortSelling.GetShortSellingByDate(date) + shorts, err := jq.ShortSelling.GetShortSellingByDate(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -231,7 +232,7 @@ func TestShortSellingEndpoint(t *testing.T) { sectorData := make(map[string][]float64) // セクター -> 直近の空売り比率リスト for _, sectorCode := range majorSectors { - shorts, err := jq.ShortSelling.GetShortSellingBySector(sectorCode) + shorts, err := jq.ShortSelling.GetShortSellingBySector(context.Background(), sectorCode) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -281,14 +282,14 @@ func TestShortSellingEndpoint(t *testing.T) { // エラーケースのテスト // 存在しない業種コード(0000は無効) - shorts, err := jq.ShortSelling.GetShortSellingBySector("0000") + shorts, err := jq.ShortSelling.GetShortSellingBySector(context.Background(), "0000") if err == nil && len(shorts) > 0 { t.Error("Expected error or empty result for invalid sector code") } // 未来の日付 futureDate := "2030-01-01" - shorts, err = jq.ShortSelling.GetShortSellingByDate(futureDate) + shorts, err = jq.ShortSelling.GetShortSellingByDate(context.Background(), futureDate) if err == nil && len(shorts) > 0 { t.Error("Expected error or empty result for future date") } diff --git a/test/e2e/statements_test.go b/test/e2e/statements_test.go index b3c481f..7a23f31 100644 --- a/test/e2e/statements_test.go +++ b/test/e2e/statements_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" ) @@ -11,7 +12,7 @@ import ( func TestStatementsEndpoint(t *testing.T) { t.Run("GetStatements_ByCode", func(t *testing.T) { // トヨタ自動車(7203)の財務諸表を取得 - statements, err := jq.Statements.GetAllStatementsByCode("7203") + statements, err := jq.Statements.GetAllStatementsByCode(context.Background(), "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -260,7 +261,7 @@ func TestStatementsEndpoint(t *testing.T) { t.Run("GetStatements_Historical", func(t *testing.T) { // 複数の履歴データ取得のテスト - statements, err := jq.Statements.GetAllStatementsByCode("7203") + statements, err := jq.Statements.GetAllStatementsByCode(context.Background(), "7203") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -294,7 +295,7 @@ func TestStatementsEndpoint(t *testing.T) { date := getTestDate() // GetStatementsByDateメソッドを使用 - statements, err := jq.Statements.GetStatementsByDate(date) + statements, err := jq.Statements.GetStatementsByDate(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") diff --git a/test/e2e/topix_test.go b/test/e2e/topix_test.go index 9111eb4..a29ead4 100644 --- a/test/e2e/topix_test.go +++ b/test/e2e/topix_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" "time" @@ -21,7 +22,7 @@ func TestTOPIXEndpoint(t *testing.T) { To: date, } - resp, err := jq.TOPIX.GetTOPIXData(params) + resp, err := jq.TOPIX.GetTOPIXData(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -99,7 +100,7 @@ func TestTOPIXEndpoint(t *testing.T) { To: toDate, } - resp, err := jq.TOPIX.GetTOPIXData(params) + resp, err := jq.TOPIX.GetTOPIXData(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -150,7 +151,7 @@ func TestTOPIXEndpoint(t *testing.T) { To: date, } - resp, err := jq.TOPIX.GetTOPIXData(params) + resp, err := jq.TOPIX.GetTOPIXData(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -178,7 +179,7 @@ func TestTOPIXEndpoint(t *testing.T) { To: "2024-01-31", } - resp, err := jq.TOPIX.GetTOPIXData(params) + resp, err := jq.TOPIX.GetTOPIXData(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -196,7 +197,7 @@ func TestTOPIXEndpoint(t *testing.T) { if resp.PaginationKey != "" { // 次のページを取得 params.PaginationKey = resp.PaginationKey - resp2, err := jq.TOPIX.GetTOPIXData(params) + resp2, err := jq.TOPIX.GetTOPIXData(context.Background(), params) if err != nil { t.Fatalf("Failed to get next page: %v", err) } @@ -209,7 +210,7 @@ func TestTOPIXEndpoint(t *testing.T) { t.Run("GetLatestTOPIX", func(t *testing.T) { // 最新のTOPIXデータを取得する便利メソッド - topix, err := jq.TOPIX.GetLatestTOPIX() + topix, err := jq.TOPIX.GetLatestTOPIX(context.Background()) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -244,7 +245,7 @@ func TestTOPIXEndpoint(t *testing.T) { To: toDate, } - resp, err := jq.TOPIX.GetTOPIXData(params) + resp, err := jq.TOPIX.GetTOPIXData(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") diff --git a/test/e2e/trades_spec_test.go b/test/e2e/trades_spec_test.go index c5b83f4..2e352eb 100644 --- a/test/e2e/trades_spec_test.go +++ b/test/e2e/trades_spec_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" "time" @@ -16,7 +17,7 @@ func TestTradesSpecEndpoint(t *testing.T) { // 最近の営業日の投資部門別売買状況を取得 date := getTestDate() - trades, err := jq.TradesSpec.GetTradesSpecByDateRange(date, date) + trades, err := jq.TradesSpec.GetTradesSpecByDateRange(context.Background(), date, date) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -81,7 +82,7 @@ func TestTradesSpecEndpoint(t *testing.T) { t.Run("GetTradesSpecBySection_TSEPrime", func(t *testing.T) { // プライム市場の投資部門別売買状況を取得 - trades, err := jq.TradesSpec.GetTradesSpecBySection("TSEPrime") + trades, err := jq.TradesSpec.GetTradesSpecBySection(context.Background(), "TSEPrime") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -119,7 +120,7 @@ func TestTradesSpecEndpoint(t *testing.T) { t.Run("GetTradesSpecBySection_All", func(t *testing.T) { // 全市場の投資部門別売買状況を取得 - trades, err := jq.TradesSpec.GetTradesSpecBySection("All") + trades, err := jq.TradesSpec.GetTradesSpecBySection(context.Background(), "All") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -148,7 +149,7 @@ func TestTradesSpecEndpoint(t *testing.T) { marketData := make(map[string][]jquants.TradesSpec) for _, market := range markets { - trades, err := jq.TradesSpec.GetTradesSpecBySection(market) + trades, err := jq.TradesSpec.GetTradesSpecBySection(context.Background(), market) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -184,7 +185,7 @@ func TestTradesSpecEndpoint(t *testing.T) { fromTime = fromTime.AddDate(0, 0, -7) from := fromTime.Format("20060102") - trades, err := jq.TradesSpec.GetTradesSpecByDateRange(from, to) + trades, err := jq.TradesSpec.GetTradesSpecByDateRange(context.Background(), from, to) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -231,7 +232,7 @@ func TestTradesSpecEndpoint(t *testing.T) { t.Run("GetTradesSpec_TrendAnalysis", func(t *testing.T) { // トレンド分析(プライム市場) - trades, err := jq.TradesSpec.GetTradesSpecBySection("TSEPrime") + trades, err := jq.TradesSpec.GetTradesSpecBySection(context.Background(), "TSEPrime") if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -278,13 +279,13 @@ func TestTradesSpecEndpoint(t *testing.T) { // エラーケースのテスト // 無効なセクション - trades, err := jq.TradesSpec.GetTradesSpecBySection("InvalidSection") + trades, err := jq.TradesSpec.GetTradesSpecBySection(context.Background(), "InvalidSection") if err == nil && len(trades) > 0 { t.Error("Expected error or empty result for invalid section") } // 無効な日付範囲 - trades, err = jq.TradesSpec.GetTradesSpecByDateRange("2024-12-31", "2024-01-01") + trades, err = jq.TradesSpec.GetTradesSpecByDateRange(context.Background(), "2024-12-31", "2024-01-01") if err == nil && len(trades) > 0 { t.Error("Expected error or empty result for invalid date range") } diff --git a/test/e2e/trading_calendar_test.go b/test/e2e/trading_calendar_test.go index 1c5085f..d8bf346 100644 --- a/test/e2e/trading_calendar_test.go +++ b/test/e2e/trading_calendar_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "strings" "testing" "time" @@ -16,7 +17,7 @@ func TestTradingCalendarEndpoint(t *testing.T) { from := "2024-06-01" to := "2024-06-30" - calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange(from, to) + calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange(context.Background(), from, to) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -84,7 +85,7 @@ func TestTradingCalendarEndpoint(t *testing.T) { from := "2024-01-01" to := "2024-01-31" - calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange(from, to) + calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange(context.Background(), from, to) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -139,7 +140,7 @@ func TestTradingCalendarEndpoint(t *testing.T) { from := "2024-05-01" to := "2024-05-31" - calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange(from, to) + calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange(context.Background(), from, to) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -189,7 +190,7 @@ func TestTradingCalendarEndpoint(t *testing.T) { from := "2023-01-01" to := "2023-12-31" - calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange(from, to) + calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange(context.Background(), from, to) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -237,7 +238,7 @@ func TestTradingCalendarEndpoint(t *testing.T) { // 単一日付での取得テスト today := time.Now().Format("2006-01-02") - calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange(today, today) + calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange(context.Background(), today, today) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -273,7 +274,7 @@ func TestTradingCalendarEndpoint(t *testing.T) { // エラーケースのテスト // 無効な日付範囲 - calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange("2024-12-31", "2024-01-01") + calendar, err := jq.TradingCalendar.GetTradingCalendarByDateRange(context.Background(), "2024-12-31", "2024-01-01") if err == nil && len(calendar) > 0 { t.Error("Expected error or empty result for invalid date range") } @@ -282,7 +283,7 @@ func TestTradingCalendarEndpoint(t *testing.T) { futureFrom := time.Now().AddDate(10, 0, 0).Format("2006-01-02") futureTo := time.Now().AddDate(10, 0, 30).Format("2006-01-02") - calendar, err = jq.TradingCalendar.GetTradingCalendarByDateRange(futureFrom, futureTo) + calendar, err = jq.TradingCalendar.GetTradingCalendarByDateRange(context.Background(), futureFrom, futureTo) if err == nil && len(calendar) > 0 { t.Logf("Warning: Got calendar data for far future dates") } diff --git a/test/e2e/weekly_margin_interest_test.go b/test/e2e/weekly_margin_interest_test.go index f40b54f..d82eab7 100644 --- a/test/e2e/weekly_margin_interest_test.go +++ b/test/e2e/weekly_margin_interest_test.go @@ -4,6 +4,7 @@ package e2e import ( + "context" "testing" "time" @@ -16,7 +17,7 @@ func TestWeeklyMarginInterestEndpoint(t *testing.T) { // トヨタ自動車の信用取引週末残高を取得 friday := getRecentFriday() - interests, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterestByCodeAndDateRange("7203", friday, friday) + interests, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterestByCodeAndDateRange(context.Background(), "7203", friday, friday) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -124,7 +125,7 @@ func TestWeeklyMarginInterestEndpoint(t *testing.T) { Date: friday, } - resp, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterest(params) + resp, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterest(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -192,7 +193,7 @@ func TestWeeklyMarginInterestEndpoint(t *testing.T) { startDate = startDate.AddDate(0, 0, -28) // 4週間前 startFriday := startDate.Format("2006-01-02") - interests, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterestByCodeAndDateRange("7203", startFriday, endFriday) + interests, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterestByCodeAndDateRange(context.Background(), "7203", startFriday, endFriday) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -242,7 +243,7 @@ func TestWeeklyMarginInterestEndpoint(t *testing.T) { Date: friday, } - resp, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterest(params) + resp, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterest(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -260,7 +261,7 @@ func TestWeeklyMarginInterestEndpoint(t *testing.T) { if resp.PaginationKey != "" { // 次のページを取得 params.PaginationKey = resp.PaginationKey - resp2, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterest(params) + resp2, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterest(context.Background(), params) if err != nil { t.Fatalf("Failed to get next page: %v", err) } @@ -279,7 +280,7 @@ func TestWeeklyMarginInterestEndpoint(t *testing.T) { Date: friday, } - resp, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterest(params) + resp, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterest(context.Background(), params) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") @@ -330,7 +331,7 @@ func TestWeeklyMarginInterestEndpoint(t *testing.T) { // エラーケースのテスト // 存在しない銘柄コード - interests, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterestByCodeAndDateRange("99999", "2024-01-05", "2024-01-05") + interests, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterestByCodeAndDateRange(context.Background(), "99999", "2024-01-05", "2024-01-05") if err == nil && len(interests) > 0 { t.Error("Expected error or empty result for invalid code") } @@ -346,7 +347,7 @@ func TestWeeklyMarginInterestEndpoint(t *testing.T) { Date: mondayStr, } - resp, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterest(params) + resp, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterest(context.Background(), params) if err == nil && resp != nil && len(resp.Data) > 0 { t.Logf("Warning: Got data for non-Friday date %s", mondayStr) } diff --git a/topix.go b/topix.go index 94a798f..c5e7ea2 100644 --- a/topix.go +++ b/topix.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" @@ -87,7 +88,7 @@ type TOPIXParams struct { // パラメータ: // - From/To: 期間指定(例: "20240101" または "2024-01-01") // - PaginationKey: ページネーション用キー -func (s *TOPIXService) GetTOPIXData(params TOPIXParams) (*TOPIXResponse, error) { +func (s *TOPIXService) GetTOPIXData(ctx context.Context, params TOPIXParams) (*TOPIXResponse, error) { path := "/indices/bars/daily/topix" query := "?" @@ -106,7 +107,7 @@ func (s *TOPIXService) GetTOPIXData(params TOPIXParams) (*TOPIXResponse, error) } var resp TOPIXResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get TOPIX data: %w", err) } @@ -115,7 +116,7 @@ func (s *TOPIXService) GetTOPIXData(params TOPIXParams) (*TOPIXResponse, error) // GetTOPIXByDateRange は指定した期間のTOPIX指数データを取得します。 // ページネーションを使用して全データを取得します。 -func (s *TOPIXService) GetTOPIXByDateRange(from, to string) ([]TOPIXData, error) { +func (s *TOPIXService) GetTOPIXByDateRange(ctx context.Context, from, to string) ([]TOPIXData, error) { var allTOPIX []TOPIXData paginationKey := "" @@ -126,7 +127,7 @@ func (s *TOPIXService) GetTOPIXByDateRange(from, to string) ([]TOPIXData, error) PaginationKey: paginationKey, } - resp, err := s.GetTOPIXData(params) + resp, err := s.GetTOPIXData(ctx, params) if err != nil { return nil, err } @@ -145,7 +146,7 @@ func (s *TOPIXService) GetTOPIXByDateRange(from, to string) ([]TOPIXData, error) // GetAllTOPIXData は全期間のTOPIX指数データを取得します。 // ページネーションを使用して大量データを分割取得します。 -func (s *TOPIXService) GetAllTOPIXData() ([]TOPIXData, error) { +func (s *TOPIXService) GetAllTOPIXData(ctx context.Context) ([]TOPIXData, error) { var allTOPIX []TOPIXData paginationKey := "" @@ -154,7 +155,7 @@ func (s *TOPIXService) GetAllTOPIXData() ([]TOPIXData, error) { PaginationKey: paginationKey, } - resp, err := s.GetTOPIXData(params) + resp, err := s.GetTOPIXData(ctx, params) if err != nil { return nil, err } @@ -172,8 +173,8 @@ func (s *TOPIXService) GetAllTOPIXData() ([]TOPIXData, error) { } // GetLatestTOPIX は最新のTOPIX指数データを取得します。 -func (s *TOPIXService) GetLatestTOPIX() (*TOPIXData, error) { - resp, err := s.GetTOPIXData(TOPIXParams{}) +func (s *TOPIXService) GetLatestTOPIX(ctx context.Context) (*TOPIXData, error) { + resp, err := s.GetTOPIXData(ctx, TOPIXParams{}) if err != nil { return nil, err } diff --git a/topix_test.go b/topix_test.go index bbd5bbc..5a473e0 100644 --- a/topix_test.go +++ b/topix_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -66,7 +67,7 @@ func TestTOPIXService_GetTOPIXData(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Execute - resp, err := service.GetTOPIXData(tt.params) + resp, err := service.GetTOPIXData(context.Background(), tt.params) // Verify if err != nil { @@ -124,7 +125,7 @@ func TestTOPIXService_GetTOPIXByDateRange(t *testing.T) { mockClient.SetResponse("GET", "/indices/bars/daily/topix?from=20240101&to=20240103&pagination_key=next_page_key", mockResponse2) // Execute - topixData, err := service.GetTOPIXByDateRange("20240101", "20240103") + topixData, err := service.GetTOPIXByDateRange(context.Background(), "20240101", "20240103") // Verify if err != nil { @@ -164,7 +165,7 @@ func TestTOPIXService_GetLatestTOPIX(t *testing.T) { mockClient.SetResponse("GET", "/indices/bars/daily/topix", mockResponse) // Execute - latest, err := service.GetLatestTOPIX() + latest, err := service.GetLatestTOPIX(context.Background()) // Verify if err != nil { @@ -195,7 +196,7 @@ func TestTOPIXService_GetLatestTOPIX_NoData(t *testing.T) { mockClient.SetResponse("GET", "/indices/bars/daily/topix", mockResponse) // Execute - _, err := service.GetLatestTOPIX() + _, err := service.GetLatestTOPIX(context.Background()) // Verify if err == nil { @@ -212,7 +213,7 @@ func TestTOPIXService_GetTOPIXData_Error(t *testing.T) { mockClient.SetError("GET", "/indices/bars/daily/topix", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetTOPIXData(TOPIXParams{}) + _, err := service.GetTOPIXData(context.Background(), TOPIXParams{}) // Verify if err == nil { diff --git a/trades_spec.go b/trades_spec.go index e71ca62..5abe9b2 100644 --- a/trades_spec.go +++ b/trades_spec.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "github.com/utahta/jquants/client" @@ -119,7 +120,7 @@ const ( // - section指定あり、from/to指定なし: 指定したセクションの全期間のデータ // - section指定なし、from/to指定あり: すべてのセクションの指定した期間のデータ // - section指定なし、from/to指定なし: すべてのセクションの全期間のデータ -func (s *TradesSpecService) GetTradesSpec(params TradesSpecParams) (*TradesSpecResponse, error) { +func (s *TradesSpecService) GetTradesSpec(ctx context.Context, params TradesSpecParams) (*TradesSpecResponse, error) { path := "/equities/investor-types" query := "?" @@ -141,7 +142,7 @@ func (s *TradesSpecService) GetTradesSpec(params TradesSpecParams) (*TradesSpecR } var resp TradesSpecResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get trades spec: %w", err) } @@ -150,7 +151,7 @@ func (s *TradesSpecService) GetTradesSpec(params TradesSpecParams) (*TradesSpecR // GetTradesSpecByDateRange は指定期間の投資部門別情報を取得します。 // ページネーションを使用して全データを取得します。 -func (s *TradesSpecService) GetTradesSpecByDateRange(from, to string) ([]TradesSpec, error) { +func (s *TradesSpecService) GetTradesSpecByDateRange(ctx context.Context, from, to string) ([]TradesSpec, error) { var allTradesSpec []TradesSpec paginationKey := "" @@ -161,7 +162,7 @@ func (s *TradesSpecService) GetTradesSpecByDateRange(from, to string) ([]TradesS PaginationKey: paginationKey, } - resp, err := s.GetTradesSpec(params) + resp, err := s.GetTradesSpec(ctx, params) if err != nil { return nil, err } @@ -180,7 +181,7 @@ func (s *TradesSpecService) GetTradesSpecByDateRange(from, to string) ([]TradesS // GetTradesSpecBySection は指定セクションの投資部門別情報を取得します。 // ページネーションを使用して全データを取得します。 -func (s *TradesSpecService) GetTradesSpecBySection(section string) ([]TradesSpec, error) { +func (s *TradesSpecService) GetTradesSpecBySection(ctx context.Context, section string) ([]TradesSpec, error) { var allTradesSpec []TradesSpec paginationKey := "" @@ -190,7 +191,7 @@ func (s *TradesSpecService) GetTradesSpecBySection(section string) ([]TradesSpec PaginationKey: paginationKey, } - resp, err := s.GetTradesSpec(params) + resp, err := s.GetTradesSpec(ctx, params) if err != nil { return nil, err } @@ -209,7 +210,7 @@ func (s *TradesSpecService) GetTradesSpecBySection(section string) ([]TradesSpec // GetAllTradesSpec は全セクション・全期間の投資部門別情報を取得します。 // ページネーションを使用して大量データを分割取得します。 -func (s *TradesSpecService) GetAllTradesSpec() ([]TradesSpec, error) { +func (s *TradesSpecService) GetAllTradesSpec(ctx context.Context) ([]TradesSpec, error) { var allTradesSpec []TradesSpec paginationKey := "" @@ -218,7 +219,7 @@ func (s *TradesSpecService) GetAllTradesSpec() ([]TradesSpec, error) { PaginationKey: paginationKey, } - resp, err := s.GetTradesSpec(params) + resp, err := s.GetTradesSpec(ctx, params) if err != nil { return nil, err } @@ -237,7 +238,7 @@ func (s *TradesSpecService) GetAllTradesSpec() ([]TradesSpec, error) { // GetTradesSpecBySectionAndDateRange は指定セクション・期間の投資部門別情報を取得します。 // ページネーションを使用して全データを取得します。 -func (s *TradesSpecService) GetTradesSpecBySectionAndDateRange(section, from, to string) ([]TradesSpec, error) { +func (s *TradesSpecService) GetTradesSpecBySectionAndDateRange(ctx context.Context, section, from, to string) ([]TradesSpec, error) { var allTradesSpec []TradesSpec paginationKey := "" @@ -249,7 +250,7 @@ func (s *TradesSpecService) GetTradesSpecBySectionAndDateRange(section, from, to PaginationKey: paginationKey, } - resp, err := s.GetTradesSpec(params) + resp, err := s.GetTradesSpec(ctx, params) if err != nil { return nil, err } diff --git a/trades_spec_test.go b/trades_spec_test.go index 9ddd424..d498e86 100644 --- a/trades_spec_test.go +++ b/trades_spec_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -95,7 +96,7 @@ func TestTradesSpecService_GetTradesSpec(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Execute - resp, err := service.GetTradesSpec(tt.params) + resp, err := service.GetTradesSpec(context.Background(), tt.params) // Verify if err != nil { @@ -165,7 +166,7 @@ func TestTradesSpecService_GetTradesSpecByDateRange(t *testing.T) { mockClient.SetResponse("GET", "/equities/investor-types?from=20170104&to=20170120&pagination_key=next_page_key", mockResponse2) // Execute - tradesSpec, err := service.GetTradesSpecByDateRange("20170104", "20170120") + tradesSpec, err := service.GetTradesSpecByDateRange(context.Background(), "20170104", "20170120") // Verify if err != nil { @@ -202,7 +203,7 @@ func TestTradesSpecService_GetTradesSpecBySection(t *testing.T) { mockClient.SetResponse("GET", "/equities/investor-types?section=TSEPrime", mockResponse) // Execute - tradesSpec, err := service.GetTradesSpecBySection("TSEPrime") + tradesSpec, err := service.GetTradesSpecBySection(context.Background(), "TSEPrime") // Verify if err != nil { @@ -250,7 +251,7 @@ func TestTradesSpecService_GetTradesSpecBySectionAndDateRange(t *testing.T) { mockClient.SetResponse("GET", "/equities/investor-types?section=TSEPrime&from=20230324&to=20230403", mockResponse) // Execute - tradesSpec, err := service.GetTradesSpecBySectionAndDateRange("TSEPrime", "20230324", "20230403") + tradesSpec, err := service.GetTradesSpecBySectionAndDateRange(context.Background(), "TSEPrime", "20230324", "20230403") // Verify if err != nil { @@ -379,7 +380,7 @@ func TestTradesSpecService_GetTradesSpec_Error(t *testing.T) { mockClient.SetError("GET", "/equities/investor-types", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetTradesSpec(TradesSpecParams{}) + _, err := service.GetTradesSpec(context.Background(), TradesSpecParams{}) // Verify if err == nil { diff --git a/trading_calendar.go b/trading_calendar.go index 18a5584..45b41ed 100644 --- a/trading_calendar.go +++ b/trading_calendar.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "github.com/utahta/jquants/client" @@ -50,7 +51,7 @@ const ( // - hol_div指定あり、from/to指定あり: 指定された休日区分について指定された期間分のデータ // - hol_div指定なし、from/to指定あり: 指定された期間分のデータ // - hol_div指定なし、from/to指定なし: 全期間分のデータ -func (s *TradingCalendarService) GetTradingCalendar(params TradingCalendarParams) (*TradingCalendarResponse, error) { +func (s *TradingCalendarService) GetTradingCalendar(ctx context.Context, params TradingCalendarParams) (*TradingCalendarResponse, error) { path := "/markets/calendar" query := "?" @@ -69,7 +70,7 @@ func (s *TradingCalendarService) GetTradingCalendar(params TradingCalendarParams } var resp TradingCalendarResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get trading calendar: %w", err) } @@ -77,8 +78,8 @@ func (s *TradingCalendarService) GetTradingCalendar(params TradingCalendarParams } // GetAllTradingCalendar は全期間・全区分の取引カレンダーを取得します。 -func (s *TradingCalendarService) GetAllTradingCalendar() ([]TradingCalendar, error) { - resp, err := s.GetTradingCalendar(TradingCalendarParams{}) +func (s *TradingCalendarService) GetAllTradingCalendar(ctx context.Context) ([]TradingCalendar, error) { + resp, err := s.GetTradingCalendar(ctx, TradingCalendarParams{}) if err != nil { return nil, err } @@ -86,8 +87,8 @@ func (s *TradingCalendarService) GetAllTradingCalendar() ([]TradingCalendar, err } // GetTradingCalendarByHolidayDivision は指定した休日区分の全期間の取引カレンダーを取得します。 -func (s *TradingCalendarService) GetTradingCalendarByHolidayDivision(holDiv string) ([]TradingCalendar, error) { - resp, err := s.GetTradingCalendar(TradingCalendarParams{ +func (s *TradingCalendarService) GetTradingCalendarByHolidayDivision(ctx context.Context, holDiv string) ([]TradingCalendar, error) { + resp, err := s.GetTradingCalendar(ctx, TradingCalendarParams{ HolidayDivision: holDiv, }) if err != nil { @@ -97,8 +98,8 @@ func (s *TradingCalendarService) GetTradingCalendarByHolidayDivision(holDiv stri } // GetTradingCalendarByHolidayDivisionAndDateRange は指定した休日区分・期間の取引カレンダーを取得します。 -func (s *TradingCalendarService) GetTradingCalendarByHolidayDivisionAndDateRange(holDiv, from, to string) ([]TradingCalendar, error) { - resp, err := s.GetTradingCalendar(TradingCalendarParams{ +func (s *TradingCalendarService) GetTradingCalendarByHolidayDivisionAndDateRange(ctx context.Context, holDiv, from, to string) ([]TradingCalendar, error) { + resp, err := s.GetTradingCalendar(ctx, TradingCalendarParams{ HolidayDivision: holDiv, From: from, To: to, @@ -110,8 +111,8 @@ func (s *TradingCalendarService) GetTradingCalendarByHolidayDivisionAndDateRange } // GetTradingCalendarByDateRange は指定した期間の取引カレンダーを取得します。 -func (s *TradingCalendarService) GetTradingCalendarByDateRange(from, to string) ([]TradingCalendar, error) { - resp, err := s.GetTradingCalendar(TradingCalendarParams{ +func (s *TradingCalendarService) GetTradingCalendarByDateRange(ctx context.Context, from, to string) ([]TradingCalendar, error) { + resp, err := s.GetTradingCalendar(ctx, TradingCalendarParams{ From: from, To: to, }) @@ -122,8 +123,8 @@ func (s *TradingCalendarService) GetTradingCalendarByDateRange(from, to string) } // GetTradingDays は指定した期間の営業日のみを取得します。 -func (s *TradingCalendarService) GetTradingDays(from, to string) ([]TradingCalendar, error) { - resp, err := s.GetTradingCalendar(TradingCalendarParams{ +func (s *TradingCalendarService) GetTradingDays(ctx context.Context, from, to string) ([]TradingCalendar, error) { + resp, err := s.GetTradingCalendar(ctx, TradingCalendarParams{ HolidayDivision: HolidayDivisionTradingDay, From: from, To: to, @@ -135,8 +136,8 @@ func (s *TradingCalendarService) GetTradingDays(from, to string) ([]TradingCalen } // GetNonTradingDays は指定した期間の非営業日のみを取得します。 -func (s *TradingCalendarService) GetNonTradingDays(from, to string) ([]TradingCalendar, error) { - resp, err := s.GetTradingCalendar(TradingCalendarParams{ +func (s *TradingCalendarService) GetNonTradingDays(ctx context.Context, from, to string) ([]TradingCalendar, error) { + resp, err := s.GetTradingCalendar(ctx, TradingCalendarParams{ HolidayDivision: HolidayDivisionNonTradingDay, From: from, To: to, @@ -148,8 +149,8 @@ func (s *TradingCalendarService) GetNonTradingDays(from, to string) ([]TradingCa } // GetOSEHolidayTradingDays はOSEで祝日取引を実施する日を取得します。 -func (s *TradingCalendarService) GetOSEHolidayTradingDays(from, to string) ([]TradingCalendar, error) { - resp, err := s.GetTradingCalendar(TradingCalendarParams{ +func (s *TradingCalendarService) GetOSEHolidayTradingDays(ctx context.Context, from, to string) ([]TradingCalendar, error) { + resp, err := s.GetTradingCalendar(ctx, TradingCalendarParams{ HolidayDivision: HolidayDivisionOSEHolidayTrading, From: from, To: to, diff --git a/trading_calendar_test.go b/trading_calendar_test.go index 3196aaf..64a2d2a 100644 --- a/trading_calendar_test.go +++ b/trading_calendar_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -66,7 +67,7 @@ func TestTradingCalendarService_GetTradingCalendar(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Execute - resp, err := service.GetTradingCalendar(tt.params) + resp, err := service.GetTradingCalendar(context.Background(), tt.params) // Verify if err != nil { @@ -102,7 +103,7 @@ func TestTradingCalendarService_GetAllTradingCalendar(t *testing.T) { mockClient.SetResponse("GET", "/markets/calendar", mockResponse) // Execute - data, err := service.GetAllTradingCalendar() + data, err := service.GetAllTradingCalendar(context.Background()) // Verify if err != nil { @@ -128,7 +129,7 @@ func TestTradingCalendarService_GetTradingCalendarByHolidayDivision(t *testing.T mockClient.SetResponse("GET", "/markets/calendar?hol_div=1", mockResponse) // Execute - data, err := service.GetTradingCalendarByHolidayDivision("1") + data, err := service.GetTradingCalendarByHolidayDivision(context.Background(), "1") // Verify if err != nil { @@ -159,7 +160,7 @@ func TestTradingCalendarService_GetTradingCalendarByHolidayDivisionAndDateRange( mockClient.SetResponse("GET", "/markets/calendar?hol_div=1&from=20240101&to=20240131", mockResponse) // Execute - data, err := service.GetTradingCalendarByHolidayDivisionAndDateRange("1", "20240101", "20240131") + data, err := service.GetTradingCalendarByHolidayDivisionAndDateRange(context.Background(), "1", "20240101", "20240131") // Verify if err != nil { @@ -196,7 +197,7 @@ func TestTradingCalendarService_GetTradingCalendarByDateRange(t *testing.T) { mockClient.SetResponse("GET", "/markets/calendar?from=20240101&to=20240107", mockResponse) // Execute - resp, err := service.GetTradingCalendarByDateRange("20240101", "20240107") + resp, err := service.GetTradingCalendarByDateRange(context.Background(), "20240101", "20240107") // Verify if err != nil { @@ -234,7 +235,7 @@ func TestTradingCalendarService_GetTradingDays(t *testing.T) { mockClient.SetResponse("GET", "/markets/calendar?hol_div=1&from=20240101&to=20240107", mockResponse) // Execute - tradingDays, err := service.GetTradingDays("20240101", "20240107") + tradingDays, err := service.GetTradingDays(context.Background(), "20240101", "20240107") // Verify if err != nil { @@ -322,7 +323,7 @@ func TestTradingCalendarService_GetTradingCalendar_Error(t *testing.T) { mockClient.SetError("GET", "/markets/calendar", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetTradingCalendar(TradingCalendarParams{}) + _, err := service.GetTradingCalendar(context.Background(), TradingCalendarParams{}) // Verify if err == nil { diff --git a/weekly_margin_interest.go b/weekly_margin_interest.go index 83e9db1..514fafb 100644 --- a/weekly_margin_interest.go +++ b/weekly_margin_interest.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "encoding/json" "fmt" @@ -118,7 +119,7 @@ func (r *WeeklyMarginInterestResponse) UnmarshalJSON(data []byte) error { } // GetWeeklyMarginInterest は信用取引週末残高を取得します。 -func (s *WeeklyMarginInterestService) GetWeeklyMarginInterest(params WeeklyMarginInterestParams) (*WeeklyMarginInterestResponse, error) { +func (s *WeeklyMarginInterestService) GetWeeklyMarginInterest(ctx context.Context, params WeeklyMarginInterestParams) (*WeeklyMarginInterestResponse, error) { // codeまたはdateのいずれかが必須 if params.Code == "" && params.Date == "" { return nil, fmt.Errorf("either code or date parameter is required") @@ -148,7 +149,7 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterest(params WeeklyMargi } var resp WeeklyMarginInterestResponse - if err := s.client.DoRequest("GET", path, nil, &resp); err != nil { + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { return nil, fmt.Errorf("failed to get weekly margin interest: %w", err) } @@ -157,7 +158,7 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterest(params WeeklyMargi // GetWeeklyMarginInterestByCode は指定銘柄の信用取引週末残高を取得します。 // ページネーションを使用して全データを取得します。 -func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCode(code string) ([]WeeklyMarginInterest, error) { +func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCode(ctx context.Context, code string) ([]WeeklyMarginInterest, error) { var allData []WeeklyMarginInterest paginationKey := "" @@ -167,7 +168,7 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCode(code string) PaginationKey: paginationKey, } - resp, err := s.GetWeeklyMarginInterest(params) + resp, err := s.GetWeeklyMarginInterest(ctx, params) if err != nil { return nil, err } @@ -186,7 +187,7 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCode(code string) // GetWeeklyMarginInterestByDate は指定日の全銘柄信用取引週末残高を取得します。 // ページネーションを使用して全データを取得します。 -func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByDate(date string) ([]WeeklyMarginInterest, error) { +func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByDate(ctx context.Context, date string) ([]WeeklyMarginInterest, error) { var allData []WeeklyMarginInterest paginationKey := "" @@ -196,7 +197,7 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByDate(date string) PaginationKey: paginationKey, } - resp, err := s.GetWeeklyMarginInterest(params) + resp, err := s.GetWeeklyMarginInterest(ctx, params) if err != nil { return nil, err } @@ -214,7 +215,7 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByDate(date string) } // GetWeeklyMarginInterestByCodeAndDateRange は指定銘柄・期間の信用取引週末残高を取得します。 -func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCodeAndDateRange(code, from, to string) ([]WeeklyMarginInterest, error) { +func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCodeAndDateRange(ctx context.Context, code, from, to string) ([]WeeklyMarginInterest, error) { var allData []WeeklyMarginInterest paginationKey := "" @@ -226,7 +227,7 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCodeAndDateRange( PaginationKey: paginationKey, } - resp, err := s.GetWeeklyMarginInterest(params) + resp, err := s.GetWeeklyMarginInterest(ctx, params) if err != nil { return nil, err } @@ -244,8 +245,8 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCodeAndDateRange( } // GetWeeklyMarginInterestByCodeAndDate は指定銘柄の指定公表日の信用取引週末残高を取得します。 -func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCodeAndDate(code, date string) ([]WeeklyMarginInterest, error) { - resp, err := s.GetWeeklyMarginInterest(WeeklyMarginInterestParams{ +func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCodeAndDate(ctx context.Context, code, date string) ([]WeeklyMarginInterest, error) { + resp, err := s.GetWeeklyMarginInterest(ctx, WeeklyMarginInterestParams{ Code: code, Date: date, }) diff --git a/weekly_margin_interest_test.go b/weekly_margin_interest_test.go index cf4acee..fbe8f90 100644 --- a/weekly_margin_interest_test.go +++ b/weekly_margin_interest_test.go @@ -1,6 +1,7 @@ package jquants import ( + "context" "fmt" "testing" @@ -72,7 +73,7 @@ func TestWeeklyMarginInterestService_GetWeeklyMarginInterest(t *testing.T) { mockClient.SetResponse("GET", tt.wantPath, mockResponse) // Execute - resp, err := service.GetWeeklyMarginInterest(tt.params) + resp, err := service.GetWeeklyMarginInterest(context.Background(), tt.params) // Verify if err != nil { @@ -98,7 +99,7 @@ func TestWeeklyMarginInterestService_GetWeeklyMarginInterest_RequiresCodeOrDate( service := NewWeeklyMarginInterestService(mockClient) // Execute with empty code and date - _, err := service.GetWeeklyMarginInterest(WeeklyMarginInterestParams{}) + _, err := service.GetWeeklyMarginInterest(context.Background(), WeeklyMarginInterestParams{}) // Verify if err == nil { @@ -153,7 +154,7 @@ func TestWeeklyMarginInterestService_GetWeeklyMarginInterestByCode(t *testing.T) mockClient.SetResponse("GET", "/markets/margin-interest?code=13010&pagination_key=next_page_key", mockResponse2) // Execute - data, err := service.GetWeeklyMarginInterestByCode("13010") + data, err := service.GetWeeklyMarginInterestByCode(context.Background(), "13010") // Verify if err != nil { @@ -197,7 +198,7 @@ func TestWeeklyMarginInterestService_GetWeeklyMarginInterestByDate(t *testing.T) mockClient.SetResponse("GET", "/markets/margin-interest?date=20230217", mockResponse) // Execute - data, err := service.GetWeeklyMarginInterestByDate("20230217") + data, err := service.GetWeeklyMarginInterestByDate(context.Background(), "20230217") // Verify if err != nil { @@ -241,7 +242,7 @@ func TestWeeklyMarginInterestService_GetWeeklyMarginInterestByCodeAndDateRange(t mockClient.SetResponse("GET", "/markets/margin-interest?code=86970&from=20230101&to=20230331", mockResponse) // Execute - data, err := service.GetWeeklyMarginInterestByCodeAndDateRange("86970", "20230101", "20230331") + data, err := service.GetWeeklyMarginInterestByCodeAndDateRange(context.Background(), "86970", "20230101", "20230331") // Verify if err != nil { @@ -278,7 +279,7 @@ func TestWeeklyMarginInterestService_GetWeeklyMarginInterestByCodeAndDate(t *tes mockClient.SetResponse("GET", "/markets/margin-interest?code=86970&date=20230324", mockResponse) // Execute - data, err := service.GetWeeklyMarginInterestByCodeAndDate("86970", "20230324") + data, err := service.GetWeeklyMarginInterestByCodeAndDate(context.Background(), "86970", "20230324") // Verify if err != nil { @@ -463,7 +464,7 @@ func TestWeeklyMarginInterestService_GetWeeklyMarginInterest_Error(t *testing.T) mockClient.SetError("GET", "/markets/margin-interest?code=13010", fmt.Errorf("unauthorized")) // Execute - _, err := service.GetWeeklyMarginInterest(WeeklyMarginInterestParams{Code: "13010"}) + _, err := service.GetWeeklyMarginInterest(context.Background(), WeeklyMarginInterestParams{Code: "13010"}) // Verify if err == nil { From de113c5f170726891d3d6cfad8f8aadd5d927a26 Mon Sep 17 00:00:00 2001 From: utahta Date: Sat, 18 Jul 2026 22:01:46 +0900 Subject: [PATCH 2/5] Update documentation for context support and trim self-evident content - README: add ctx to all code examples, fix method names that no longer exist (GetInfo -> GetAllListedInfo etc.), document the cache cancellation semantics in the cache section - CLAUDE.md: drop sections derivable from the code (directory layout, test pattern details) and keep only guidance that changes behavior --- CLAUDE.md | 37 ++++++------------------------------- README.md | 31 +++++++++++++++++-------------- 2 files changed, 23 insertions(+), 45 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b6e125c..88ef6a3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,38 +25,13 @@ make test-e2e # E2Eテスト(JQUANTS_API_KEY が必要) make test-run TEST=TestQuotesService_GetDailyQuotes # 特定のテスト ``` -## ディレクトリ構造 - -- `client/`: HTTPクライアント(認証、キャッシュ)とモック -- `types/`: カスタム型(JSONの不整合な型を処理) -- `docs/v2/`: v2 APIドキュメント -- `test/e2e/`: E2Eテスト - -## 新しいAPIサービスの追加方法 - -1. 新しいサービスファイルを作成(例:`new_service.go`) -2. サービス構造体とメソッドを実装 -3. `jquants.go`の`JQuantsAPI`構造体に新サービスを追加 -4. 対応するテストファイルを作成(例:`new_service_test.go`) -5. `docs/v2/`ディレクトリにドキュメントを追加 - -## テスト実装のパターン - -```go -func TestService_Method(t *testing.T) { - mockClient := &client.MockClient{ - DoFunc: func(req *http.Request) (*http.Response, error) { - // モックレスポンスを返す - }, - } - service := &Service{client: mockClient} - // テスト実行 -} -``` +## 新しいAPIサービスの追加時の注意 + +- `jquants.go`の`JQuantsAPI`構造体への登録を忘れない(忘れてもコンパイルは通る) +- `docs/v2/`ディレクトリにドキュメントを追加する ## 実装上の注意点 1. **nil安全性**: APIレスポンスの欠損フィールドはポインタで表現 -2. **エラーハンドリング**: 一貫したエラーラップとコンテキスト情報の付与 -3. **型変換**: `types`パッケージのカスタム型を使用してJSONの不整合を処理 -4. **定数定義**: 市場区分コード、業種コード、開示書類種別などは定数として定義済み +2. **型変換**: APIはJSONの型を不整合に返すことがあるため、`types`パッケージのカスタム型で処理 +3. **定数定義**: 市場区分コード、業種コード、開示書類種別などは定数として定義済み(再定義しない) diff --git a/README.md b/README.md index 4012fa4..58fcb0f 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ go get github.com/utahta/jquants package main import ( + "context" "fmt" "log" @@ -41,7 +42,8 @@ func main() { jq := jquants.NewJQuantsAPI(httpClient) // 株価データを取得 - quotes, err := jq.Quotes.GetDailyQuotesByCode("7203") // トヨタ自動車 + ctx := context.Background() + quotes, err := jq.Quotes.GetDailyQuotesByCode(ctx, "7203") // トヨタ自動車 if err != nil { log.Fatal(err) } @@ -91,6 +93,7 @@ size := httpClient.CacheSize() - キャッシュはGETリクエストのみに適用されます - キャッシュキーはリクエストパス(クエリパラメータ含む)で区別されます - 同時リクエストの重複排除(singleflight)により効率的に動作します +- 重複排除の待機中にコンテキストをキャンセルした場合、その呼び出し元だけが即座にエラーで戻り、進行中のリクエスト自体は完了してキャッシュに保存されます - キャッシュはクライアントインスタンスの生存期間のみ有効です ## 利用可能なAPI @@ -127,7 +130,7 @@ size := httpClient.CacheSize() ```go // 特定銘柄の直近データ -quotes, err := jq.Quotes.GetDailyQuotesByCode("7203") +quotes, err := jq.Quotes.GetDailyQuotesByCode(ctx, "7203") // 日付範囲指定 params := jquants.DailyQuotesParams{ @@ -135,7 +138,7 @@ params := jquants.DailyQuotesParams{ From: "2024-01-01", To: "2024-01-31", } -response, err := jq.Quotes.GetDailyQuotes(params) +response, err := jq.Quotes.GetDailyQuotes(ctx, params) // v2 APIでは短縮フィールド名を使用 for _, q := range response.Data { @@ -148,14 +151,14 @@ for _, q := range response.Data { ```go // 全銘柄を取得 -companies, err := jq.Listed.GetInfo() +companies, err := jq.Listed.GetAllListedInfo(ctx) // 特定銘柄の情報を取得 -company, err := jq.Listed.GetInfoByCode("7203") -fmt.Printf("企業名: %s\n", company.Name) +companies, err := jq.Listed.GetListedInfoByCode(ctx, "7203") +fmt.Printf("企業名: %s\n", companies[0].Name) // 市場区分で絞り込み(定数を使用) -primeCompanies, err := jq.Listed.GetListedByMarket(jquants.MarketPrime, "") +primeCompanies, err := jq.Listed.GetListedByMarket(ctx, jquants.MarketPrime, "") for _, company := range primeCompanies { fmt.Printf("%s (%s) - %s\n", company.Name, company.Code, company.MktName) } @@ -165,13 +168,13 @@ for _, company := range primeCompanies { ```go // 最新の財務情報 -statement, err := jq.Statements.GetLatestStatements("7203") +statement, err := jq.Statements.GetLatestStatements(ctx, "7203") if statement.NetSales != nil { fmt.Printf("売上高: %.0f円\n", *statement.NetSales) } // 特定日の財務情報 -statements, err := jq.Statements.GetStatementsByDate("2024-01-15") +statements, err := jq.Statements.GetStatementsByDate(ctx, "2024-01-15") // 開示書類種別での絞り込み for _, stmt := range statements { @@ -189,10 +192,10 @@ for _, stmt := range statements { ```go // 銘柄コードで取得 -data, err := jq.DailyMarginInterest.GetDailyMarginInterestByCode("13260") +data, err := jq.DailyMarginInterest.GetDailyMarginInterestByCode(ctx, "13260") // 公表日で取得 -data, err := jq.DailyMarginInterest.GetDailyMarginInterestByDate("20240208") +data, err := jq.DailyMarginInterest.GetDailyMarginInterestByDate(ctx, "20240208") // 公表理由の確認 for _, d := range data { @@ -212,13 +215,13 @@ params := jquants.DailyQuotesParams{ } // 最初のページ -response, err := jq.Quotes.GetDailyQuotes(params) +response, err := jq.Quotes.GetDailyQuotes(ctx, params) quotes := response.Data // 次のページがある場合 if response.PaginationKey != "" { params.PaginationKey = response.PaginationKey - nextResponse, err := jq.Quotes.GetDailyQuotes(params) + nextResponse, err := jq.Quotes.GetDailyQuotes(ctx, params) quotes = append(quotes, nextResponse.Data...) } ``` @@ -313,7 +316,7 @@ cd cmd/gitbook2md && go build ## エラーハンドリング ```go -quotes, err := jq.Quotes.GetDailyQuotesByCode("9999") +quotes, err := jq.Quotes.GetDailyQuotesByCode(ctx, "9999") if err != nil { // APIエラーの詳細を取得 if apiErr, ok := err.(*client.APIError); ok { From 0f4f7a6f142ce05fe69a65ff35644decec466376 Mon Sep 17 00:00:00 2001 From: utahta Date: Sat, 18 Jul 2026 22:02:30 +0900 Subject: [PATCH 3/5] Handle null OHLC values for close-only indices The indices API returns null O/H/L for indices that are distributed with a closing price only (e.g. codes 0504, 6000, 6095, 6096, B507), which previously decoded to 0 and broke E2E validation. - Change Index.O/H/L to *float64 (nil when close-only); C stays float64 since every published record has a closing price - Validate OHLC in the E2E test only when present, and require O/H/L to be all present or all nil - GetIndices_HistoricalData now specifies a code since the API requires code or date, and fails loudly instead of swallowing errors --- indices.go | 30 +++++++++--------- indices_test.go | 46 ++++++++++++++++++++++----- test/e2e/e2e_test.go | 9 ++++++ test/e2e/indices_test.go | 68 ++++++++++++++++++++++------------------ 4 files changed, 100 insertions(+), 53 deletions(-) diff --git a/indices.go b/indices.go index 2735625..88549d2 100644 --- a/indices.go +++ b/indices.go @@ -23,22 +23,22 @@ func NewIndicesService(c client.HTTPClient) *IndicesService { // Index は指数四本値データを表します。 // J-Quants API /indices/bars/daily エンドポイントのレスポンスデータ。 type Index struct { - Date string `json:"Date"` // 日付(YYYY-MM-DD形式) - Code string `json:"Code"` // 指数コード - O float64 `json:"O"` // 始値 - H float64 `json:"H"` // 高値 - L float64 `json:"L"` // 安値 - C float64 `json:"C"` // 終値 + Date string `json:"Date"` // 日付(YYYY-MM-DD形式) + Code string `json:"Code"` // 指数コード + O *float64 `json:"O"` // 始値(終値のみ配信の指数・期間ではnull) + H *float64 `json:"H"` // 高値(終値のみ配信の指数・期間ではnull) + L *float64 `json:"L"` // 安値(終値のみ配信の指数・期間ではnull) + C float64 `json:"C"` // 終値 } // RawIndex is used for unmarshaling JSON response with mixed types type RawIndex struct { - Date string `json:"Date"` - Code string `json:"Code"` - O types.Float64String `json:"O"` - H types.Float64String `json:"H"` - L types.Float64String `json:"L"` - C types.Float64String `json:"C"` + Date string `json:"Date"` + Code string `json:"Code"` + O *types.Float64String `json:"O"` + H *types.Float64String `json:"H"` + L *types.Float64String `json:"L"` + C types.Float64String `json:"C"` } // IndicesResponse は指数四本値のレスポンスです。 @@ -69,9 +69,9 @@ func (i *IndicesResponse) UnmarshalJSON(data []byte) error { i.Data[idx] = Index{ Date: ri.Date, Code: ri.Code, - O: float64(ri.O), - H: float64(ri.H), - L: float64(ri.L), + O: types.ToFloat64Ptr(ri.O), + H: types.ToFloat64Ptr(ri.H), + L: types.ToFloat64Ptr(ri.L), C: float64(ri.C), } } diff --git a/indices_test.go b/indices_test.go index eea8c60..a0e4897 100644 --- a/indices_test.go +++ b/indices_test.go @@ -67,9 +67,9 @@ func TestIndicesService_GetIndices(t *testing.T) { { Date: "2024-01-31", Code: "0000", - O: 2400.0, - H: 2420.0, - L: 2390.0, + O: floatPtr(2400.0), + H: floatPtr(2420.0), + L: floatPtr(2390.0), C: 2410.0, }, }, @@ -106,7 +106,7 @@ func TestIndicesService_GetIndicesByCode(t *testing.T) { // Mock response - 最初のページ mockResponse1 := IndicesResponse{ Data: []Index{ - {Date: "2024-01-01", Code: "0000", O: 2400.0, H: 2420.0, L: 2390.0, C: 2410.0}, + {Date: "2024-01-01", Code: "0000", O: floatPtr(2400.0), H: floatPtr(2420.0), L: floatPtr(2390.0), C: 2410.0}, {Date: "2024-01-02", Code: "0000", C: 2420.0}, }, PaginationKey: "next_page_key", @@ -223,7 +223,7 @@ func TestIndicesService_GetSectorIndex(t *testing.T) { // Mock response - 情報・通信業 mockResponse := IndicesResponse{ Data: []Index{ - {Date: "2024-02-01", Code: "0058", O: 3000.0, H: 3050.0, L: 2980.0, C: 3020.0}, + {Date: "2024-02-01", Code: "0058", O: floatPtr(3000.0), H: floatPtr(3050.0), L: floatPtr(2980.0), C: 3020.0}, }, } mockClient.SetResponse("GET", "/indices/bars/daily?code=0058", mockResponse) @@ -279,9 +279,9 @@ func TestIndicesService_GetIndicesByCodeAndDate(t *testing.T) { { Date: "2024-01-01", Code: "0000", - O: 2400.0, - H: 2420.0, - L: 2390.0, + O: floatPtr(2400.0), + H: floatPtr(2420.0), + L: floatPtr(2390.0), C: 2410.0, }, }, @@ -351,6 +351,36 @@ func TestIndicesService_GetIndicesByCodeAndDateRange(t *testing.T) { } } +func TestIndicesService_GetIndices_CloseOnlyIndex(t *testing.T) { + // 終値のみ配信の指数はO/H/Lがnullで返される(例: 東証REIT用途別指数など) + mockClient := client.NewMockClient() + service := NewIndicesService(mockClient) + + mockResponse := map[string]interface{}{ + "data": []map[string]interface{}{ + {"Date": "2025-06-13", "Code": "0504", "O": nil, "H": nil, "L": nil, "C": 1122.85}, + }, + "pagination_key": "", + } + mockClient.SetResponse("GET", "/indices/bars/daily?date=20250613", mockResponse) + + resp, err := service.GetIndices(context.Background(), IndicesParams{Date: "20250613"}) + if err != nil { + t.Fatalf("GetIndices() error = %v", err) + } + if len(resp.Data) != 1 { + t.Fatalf("GetIndices() returned %d items, want 1", len(resp.Data)) + } + + index := resp.Data[0] + if index.O != nil || index.H != nil || index.L != nil { + t.Errorf("O/H/L = %v/%v/%v, want all nil", index.O, index.H, index.L) + } + if index.C != 1122.85 { + t.Errorf("C = %v, want 1122.85", index.C) + } +} + func TestIndicesService_GetIndices_Error(t *testing.T) { // Setup mockClient := client.NewMockClient() diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go index 339f2b7..c722ada 100644 --- a/test/e2e/e2e_test.go +++ b/test/e2e/e2e_test.go @@ -4,6 +4,7 @@ package e2e import ( + "fmt" "os" "strings" "testing" @@ -56,3 +57,11 @@ func getTestDateFormatted() string { // APIレスポンスで使用されるYYYY-MM-DD形式で返す return "2025-06-13" } + +// fmtPrice はnil許容の価格フィールドをログ表示用に整形する +func fmtPrice(p *float64) string { + if p == nil { + return "nil" + } + return fmt.Sprintf("%.2f", *p) +} diff --git a/test/e2e/indices_test.go b/test/e2e/indices_test.go index 1e50b3b..5c47dcb 100644 --- a/test/e2e/indices_test.go +++ b/test/e2e/indices_test.go @@ -53,37 +53,45 @@ func TestIndicesEndpoint(t *testing.T) { t.Errorf("Index[%d]: Code is empty", i) } - // 四本値の検証 - if index.O <= 0 { - t.Errorf("Index[%d]: Open = %v, want > 0", i, index.O) - } - if index.H <= 0 { - t.Errorf("Index[%d]: High = %v, want > 0", i, index.H) - } - if index.L <= 0 { - t.Errorf("Index[%d]: Low = %v, want > 0", i, index.L) - } + // 終値の検証(終値のみ配信の指数はO/H/Lがnil) if index.C <= 0 { t.Errorf("Index[%d]: Close = %v, want > 0", i, index.C) } - // 四本値の論理的整合性チェック - if index.H < index.L { - t.Errorf("Index[%d]: High (%v) < Low (%v)", i, index.H, index.L) - } - if index.O > index.H || index.O < index.L { - t.Errorf("Index[%d]: Open (%v) is outside High (%v) - Low (%v) range", - i, index.O, index.H, index.L) - } - if index.C > index.H || index.C < index.L { - t.Errorf("Index[%d]: Close (%v) is outside High (%v) - Low (%v) range", - i, index.C, index.H, index.L) + // 四本値の検証 + if index.O != nil && index.H != nil && index.L != nil { + o, h, l := *index.O, *index.H, *index.L + if o <= 0 { + t.Errorf("Index[%d]: Open = %v, want > 0", i, o) + } + if h <= 0 { + t.Errorf("Index[%d]: High = %v, want > 0", i, h) + } + if l <= 0 { + t.Errorf("Index[%d]: Low = %v, want > 0", i, l) + } + + // 四本値の論理的整合性チェック + if h < l { + t.Errorf("Index[%d]: High (%v) < Low (%v)", i, h, l) + } + if o > h || o < l { + t.Errorf("Index[%d]: Open (%v) is outside High (%v) - Low (%v) range", + i, o, h, l) + } + if index.C > h || index.C < l { + t.Errorf("Index[%d]: Close (%v) is outside High (%v) - Low (%v) range", + i, index.C, h, l) + } + } else if index.O != nil || index.H != nil || index.L != nil { + t.Errorf("Index[%d]: O/H/L should be all present or all nil, got O=%s, H=%s, L=%s", + i, fmtPrice(index.O), fmtPrice(index.H), fmtPrice(index.L)) } // 最初の5件の詳細ログ if i < 5 { - t.Logf("Index[%d]: Code=%s, Date=%s, O=%.2f, H=%.2f, L=%.2f, C=%.2f", - i, index.Code, index.Date, index.O, index.H, index.L, index.C) + t.Logf("Index[%d]: Code=%s, Date=%s, O=%s, H=%s, L=%s, C=%.2f", + i, index.Code, index.Date, fmtPrice(index.O), fmtPrice(index.H), fmtPrice(index.L), index.C) } } @@ -201,8 +209,8 @@ func TestIndicesEndpoint(t *testing.T) { // 最初と最後のデータをログ if i == 0 || i == len(indices)-1 { - t.Logf("TOPIX Core30 [%s]: Close=%.2f (O=%.2f, H=%.2f, L=%.2f)", - index.Date, index.C, index.O, index.H, index.L) + t.Logf("TOPIX Core30 [%s]: Close=%.2f (O=%s, H=%s, L=%s)", + index.Date, index.C, fmtPrice(index.O), fmtPrice(index.H), fmtPrice(index.L)) } } @@ -240,15 +248,16 @@ func TestIndicesEndpoint(t *testing.T) { // 最初と最後のデータをログ if i == 0 || i == len(indices)-1 { - t.Logf("TOPIX [%s]: Close=%.2f (O=%.2f, H=%.2f, L=%.2f)", - index.Date, index.C, index.O, index.H, index.L) + t.Logf("TOPIX [%s]: Close=%.2f (O=%s, H=%s, L=%s)", + index.Date, index.C, fmtPrice(index.O), fmtPrice(index.H), fmtPrice(index.L)) } } }) t.Run("GetIndices_HistoricalData", func(t *testing.T) { - // 過去の特定期間のデータ取得 + // 過去の特定期間のデータ取得(codeまたはdateの指定が必須のためcodeを指定) params := jquants.IndicesParams{ + Code: jquants.IndexTOPIX, From: "2024-01-01", To: "2024-01-31", } @@ -258,8 +267,7 @@ func TestIndicesEndpoint(t *testing.T) { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } - t.Logf("Failed to get historical indices: %v", err) - return + t.Fatalf("Failed to get historical indices: %v", err) } if resp != nil && len(resp.Data) > 0 { From 400a0d5e33eac0b5ee0ec7a126e871e6cb87c198 Mon Sep 17 00:00:00 2001 From: utahta Date: Sat, 18 Jul 2026 22:24:59 +0900 Subject: [PATCH 4/5] Fix empty string coercion to zero in financial statements The v2 /fins/summary API returns empty strings for unset numeric fields (e.g. dividend forecasts), not null. Float64String leaves the value at zero for empty strings, so pointer fields decoded to a non-nil pointer to 0 -- making "not set" indistinguishable from a real 0. - Switch RawStatement numeric fields from *types.Float64String to types.Float64StringWithDash, which models absent (""), undetermined ("-") and present values correctly - Guard Float64StringWithDash.UnmarshalJSON against JSON null, which previously slipped through the float64 branch and recorded 0 - Add Float64StringWithDash.ToInt64Ptr for share-count fields - Fix a unit test that asserted the buggy behavior (empty string -> 0) --- statements.go | 356 ++++++++++++++++++++++----------------------- statements_test.go | 50 ++++++- types/json.go | 17 +++ types/json_test.go | 40 ++++- 4 files changed, 278 insertions(+), 185 deletions(-) diff --git a/statements.go b/statements.go index bbaace3..262823e 100644 --- a/statements.go +++ b/statements.go @@ -183,79 +183,79 @@ type RawStatement struct { NxtFYEn string `json:"NxtFYEn"` // 連結財務数値 - Sales *types.Float64String `json:"Sales"` - OP *types.Float64String `json:"OP"` - OdP *types.Float64String `json:"OdP"` - NP *types.Float64String `json:"NP"` - TA *types.Float64String `json:"TA"` - Eq *types.Float64String `json:"Eq"` - CashEq *types.Float64String `json:"CashEq"` - CFO *types.Float64String `json:"CFO"` - CFI *types.Float64String `json:"CFI"` - CFF *types.Float64String `json:"CFF"` + Sales types.Float64StringWithDash `json:"Sales"` + OP types.Float64StringWithDash `json:"OP"` + OdP types.Float64StringWithDash `json:"OdP"` + NP types.Float64StringWithDash `json:"NP"` + TA types.Float64StringWithDash `json:"TA"` + Eq types.Float64StringWithDash `json:"Eq"` + CashEq types.Float64StringWithDash `json:"CashEq"` + CFO types.Float64StringWithDash `json:"CFO"` + CFI types.Float64StringWithDash `json:"CFI"` + CFF types.Float64StringWithDash `json:"CFF"` // 財務指標 - EPS *types.Float64String `json:"EPS"` - DEPS *types.Float64String `json:"DEPS"` - BPS *types.Float64String `json:"BPS"` - EqAR *types.Float64String `json:"EqAR"` + EPS types.Float64StringWithDash `json:"EPS"` + DEPS types.Float64StringWithDash `json:"DEPS"` + BPS types.Float64StringWithDash `json:"BPS"` + EqAR types.Float64StringWithDash `json:"EqAR"` // 配当実績 - Div1Q *types.Float64String `json:"Div1Q"` - Div2Q *types.Float64String `json:"Div2Q"` - Div3Q *types.Float64String `json:"Div3Q"` - DivFY *types.Float64String `json:"DivFY"` - DivAnn *types.Float64String `json:"DivAnn"` - DivUnit *types.Float64String `json:"DivUnit"` - DivTotalAnn *types.Float64String `json:"DivTotalAnn"` - PayoutRatioAn *types.Float64String `json:"PayoutRatioAnn"` + Div1Q types.Float64StringWithDash `json:"Div1Q"` + Div2Q types.Float64StringWithDash `json:"Div2Q"` + Div3Q types.Float64StringWithDash `json:"Div3Q"` + DivFY types.Float64StringWithDash `json:"DivFY"` + DivAnn types.Float64StringWithDash `json:"DivAnn"` + DivUnit types.Float64StringWithDash `json:"DivUnit"` + DivTotalAnn types.Float64StringWithDash `json:"DivTotalAnn"` + PayoutRatioAn types.Float64StringWithDash `json:"PayoutRatioAnn"` // 配当予想 - FDiv1Q *types.Float64String `json:"FDiv1Q"` - FDiv2Q *types.Float64String `json:"FDiv2Q"` - FDiv3Q *types.Float64String `json:"FDiv3Q"` - FDivFY *types.Float64String `json:"FDivFY"` - FDivAnn *types.Float64String `json:"FDivAnn"` - FDivUnit *types.Float64String `json:"FDivUnit"` - FDivTotalAnn *types.Float64String `json:"FDivTotalAnn"` - FPayoutRatioAn *types.Float64String `json:"FPayoutRatioAnn"` + FDiv1Q types.Float64StringWithDash `json:"FDiv1Q"` + FDiv2Q types.Float64StringWithDash `json:"FDiv2Q"` + FDiv3Q types.Float64StringWithDash `json:"FDiv3Q"` + FDivFY types.Float64StringWithDash `json:"FDivFY"` + FDivAnn types.Float64StringWithDash `json:"FDivAnn"` + FDivUnit types.Float64StringWithDash `json:"FDivUnit"` + FDivTotalAnn types.Float64StringWithDash `json:"FDivTotalAnn"` + FPayoutRatioAn types.Float64StringWithDash `json:"FPayoutRatioAnn"` // 翌期配当予想 - NxFDiv1Q *types.Float64String `json:"NxFDiv1Q"` - NxFDiv2Q *types.Float64String `json:"NxFDiv2Q"` - NxFDiv3Q *types.Float64String `json:"NxFDiv3Q"` - NxFDivFY *types.Float64String `json:"NxFDivFY"` - NxFDivAnn *types.Float64String `json:"NxFDivAnn"` - NxFDivUnit *types.Float64String `json:"NxFDivUnit"` - NxFPayoutRatioAn *types.Float64String `json:"NxFPayoutRatioAnn"` + NxFDiv1Q types.Float64StringWithDash `json:"NxFDiv1Q"` + NxFDiv2Q types.Float64StringWithDash `json:"NxFDiv2Q"` + NxFDiv3Q types.Float64StringWithDash `json:"NxFDiv3Q"` + NxFDivFY types.Float64StringWithDash `json:"NxFDivFY"` + NxFDivAnn types.Float64StringWithDash `json:"NxFDivAnn"` + NxFDivUnit types.Float64StringWithDash `json:"NxFDivUnit"` + NxFPayoutRatioAn types.Float64StringWithDash `json:"NxFPayoutRatioAnn"` // 第2四半期業績予想 - FSales2Q *types.Float64String `json:"FSales2Q"` - FOP2Q *types.Float64String `json:"FOP2Q"` - FOdP2Q *types.Float64String `json:"FOdP2Q"` - FNP2Q *types.Float64String `json:"FNP2Q"` - FEPS2Q *types.Float64String `json:"FEPS2Q"` + FSales2Q types.Float64StringWithDash `json:"FSales2Q"` + FOP2Q types.Float64StringWithDash `json:"FOP2Q"` + FOdP2Q types.Float64StringWithDash `json:"FOdP2Q"` + FNP2Q types.Float64StringWithDash `json:"FNP2Q"` + FEPS2Q types.Float64StringWithDash `json:"FEPS2Q"` // 翌期第2四半期業績予想 - NxFSales2Q *types.Float64String `json:"NxFSales2Q"` - NxFOP2Q *types.Float64String `json:"NxFOP2Q"` - NxFOdP2Q *types.Float64String `json:"NxFOdP2Q"` - NxFNp2Q *types.Float64String `json:"NxFNp2Q"` - NxFEPS2Q *types.Float64String `json:"NxFEPS2Q"` + NxFSales2Q types.Float64StringWithDash `json:"NxFSales2Q"` + NxFOP2Q types.Float64StringWithDash `json:"NxFOP2Q"` + NxFOdP2Q types.Float64StringWithDash `json:"NxFOdP2Q"` + NxFNp2Q types.Float64StringWithDash `json:"NxFNp2Q"` + NxFEPS2Q types.Float64StringWithDash `json:"NxFEPS2Q"` // 期末業績予想 - FSales *types.Float64String `json:"FSales"` - FOP *types.Float64String `json:"FOP"` - FOdP *types.Float64String `json:"FOdP"` - FNP *types.Float64String `json:"FNP"` - FEPS *types.Float64String `json:"FEPS"` + FSales types.Float64StringWithDash `json:"FSales"` + FOP types.Float64StringWithDash `json:"FOP"` + FOdP types.Float64StringWithDash `json:"FOdP"` + FNP types.Float64StringWithDash `json:"FNP"` + FEPS types.Float64StringWithDash `json:"FEPS"` // 翌期末業績予想 - NxFSales *types.Float64String `json:"NxFSales"` - NxFOP *types.Float64String `json:"NxFOP"` - NxFOdP *types.Float64String `json:"NxFOdP"` - NxFNp *types.Float64String `json:"NxFNp"` - NxFEPS *types.Float64String `json:"NxFEPS"` + NxFSales types.Float64StringWithDash `json:"NxFSales"` + NxFOP types.Float64StringWithDash `json:"NxFOP"` + NxFOdP types.Float64StringWithDash `json:"NxFOdP"` + NxFNp types.Float64StringWithDash `json:"NxFNp"` + NxFEPS types.Float64StringWithDash `json:"NxFEPS"` // その他 MatChgSub string `json:"MatChgSub"` @@ -264,48 +264,48 @@ type RawStatement struct { ChgNoASRev string `json:"ChgNoASRev"` ChgAcEst string `json:"ChgAcEst"` RetroRst string `json:"RetroRst"` - ShOutFY *types.Float64String `json:"ShOutFY"` - TrShFY *types.Float64String `json:"TrShFY"` - AvgSh *types.Float64String `json:"AvgSh"` + ShOutFY types.Float64StringWithDash `json:"ShOutFY"` + TrShFY types.Float64StringWithDash `json:"TrShFY"` + AvgSh types.Float64StringWithDash `json:"AvgSh"` // 非連結財務数値 - NCSales *types.Float64String `json:"NCSales"` - NCOP *types.Float64String `json:"NCOP"` - NCOdP *types.Float64String `json:"NCOdP"` - NCNP *types.Float64String `json:"NCNP"` - NCEPS *types.Float64String `json:"NCEPS"` - NCTA *types.Float64String `json:"NCTA"` - NCEq *types.Float64String `json:"NCEq"` - NCEqAR *types.Float64String `json:"NCEqAR"` - NCBPS *types.Float64String `json:"NCBPS"` + NCSales types.Float64StringWithDash `json:"NCSales"` + NCOP types.Float64StringWithDash `json:"NCOP"` + NCOdP types.Float64StringWithDash `json:"NCOdP"` + NCNP types.Float64StringWithDash `json:"NCNP"` + NCEPS types.Float64StringWithDash `json:"NCEPS"` + NCTA types.Float64StringWithDash `json:"NCTA"` + NCEq types.Float64StringWithDash `json:"NCEq"` + NCEqAR types.Float64StringWithDash `json:"NCEqAR"` + NCBPS types.Float64StringWithDash `json:"NCBPS"` // 非連結第2四半期予想 - FNCSales2Q *types.Float64String `json:"FNCSales2Q"` - FNCOP2Q *types.Float64String `json:"FNCOP2Q"` - FNCOdP2Q *types.Float64String `json:"FNCOdP2Q"` - FNCNP2Q *types.Float64String `json:"FNCNP2Q"` - FNCEPS2Q *types.Float64String `json:"FNCEPS2Q"` + FNCSales2Q types.Float64StringWithDash `json:"FNCSales2Q"` + FNCOP2Q types.Float64StringWithDash `json:"FNCOP2Q"` + FNCOdP2Q types.Float64StringWithDash `json:"FNCOdP2Q"` + FNCNP2Q types.Float64StringWithDash `json:"FNCNP2Q"` + FNCEPS2Q types.Float64StringWithDash `json:"FNCEPS2Q"` // 翌期非連結第2四半期予想 - NxFNCSales2Q *types.Float64String `json:"NxFNCSales2Q"` - NxFNCOP2Q *types.Float64String `json:"NxFNCOP2Q"` - NxFNCOdP2Q *types.Float64String `json:"NxFNCOdP2Q"` - NxFNCNP2Q *types.Float64String `json:"NxFNCNP2Q"` - NxFNCEPS2Q *types.Float64String `json:"NxFNCEPS2Q"` + NxFNCSales2Q types.Float64StringWithDash `json:"NxFNCSales2Q"` + NxFNCOP2Q types.Float64StringWithDash `json:"NxFNCOP2Q"` + NxFNCOdP2Q types.Float64StringWithDash `json:"NxFNCOdP2Q"` + NxFNCNP2Q types.Float64StringWithDash `json:"NxFNCNP2Q"` + NxFNCEPS2Q types.Float64StringWithDash `json:"NxFNCEPS2Q"` // 非連結期末予想 - FNCSales *types.Float64String `json:"FNCSales"` - FNCOP *types.Float64String `json:"FNCOP"` - FNCOdP *types.Float64String `json:"FNCOdP"` - FNCNP *types.Float64String `json:"FNCNP"` - FNCEPS *types.Float64String `json:"FNCEPS"` + FNCSales types.Float64StringWithDash `json:"FNCSales"` + FNCOP types.Float64StringWithDash `json:"FNCOP"` + FNCOdP types.Float64StringWithDash `json:"FNCOdP"` + FNCNP types.Float64StringWithDash `json:"FNCNP"` + FNCEPS types.Float64StringWithDash `json:"FNCEPS"` // 翌期非連結期末予想 - NxFNCSales *types.Float64String `json:"NxFNCSales"` - NxFNCOP *types.Float64String `json:"NxFNCOP"` - NxFNCOdP *types.Float64String `json:"NxFNCOdP"` - NxFNCNP *types.Float64String `json:"NxFNCNP"` - NxFNCEPS *types.Float64String `json:"NxFNCEPS"` + NxFNCSales types.Float64StringWithDash `json:"NxFNCSales"` + NxFNCOP types.Float64StringWithDash `json:"NxFNCOP"` + NxFNCOdP types.Float64StringWithDash `json:"NxFNCOdP"` + NxFNCNP types.Float64StringWithDash `json:"NxFNCNP"` + NxFNCEPS types.Float64StringWithDash `json:"NxFNCEPS"` } type StatementsResponse struct { @@ -347,79 +347,79 @@ func (s *StatementsResponse) UnmarshalJSON(data []byte) error { NxtFYEn: rs.NxtFYEn, // 連結財務数値 - Sales: types.ToFloat64Ptr(rs.Sales), - OP: types.ToFloat64Ptr(rs.OP), - OdP: types.ToFloat64Ptr(rs.OdP), - NP: types.ToFloat64Ptr(rs.NP), - TA: types.ToFloat64Ptr(rs.TA), - Eq: types.ToFloat64Ptr(rs.Eq), - CashEq: types.ToFloat64Ptr(rs.CashEq), - CFO: types.ToFloat64Ptr(rs.CFO), - CFI: types.ToFloat64Ptr(rs.CFI), - CFF: types.ToFloat64Ptr(rs.CFF), + Sales: rs.Sales.ToFloat64Ptr(), + OP: rs.OP.ToFloat64Ptr(), + OdP: rs.OdP.ToFloat64Ptr(), + NP: rs.NP.ToFloat64Ptr(), + TA: rs.TA.ToFloat64Ptr(), + Eq: rs.Eq.ToFloat64Ptr(), + CashEq: rs.CashEq.ToFloat64Ptr(), + CFO: rs.CFO.ToFloat64Ptr(), + CFI: rs.CFI.ToFloat64Ptr(), + CFF: rs.CFF.ToFloat64Ptr(), // 財務指標 - EPS: types.ToFloat64Ptr(rs.EPS), - DEPS: types.ToFloat64Ptr(rs.DEPS), - BPS: types.ToFloat64Ptr(rs.BPS), - EqAR: types.ToFloat64Ptr(rs.EqAR), + EPS: rs.EPS.ToFloat64Ptr(), + DEPS: rs.DEPS.ToFloat64Ptr(), + BPS: rs.BPS.ToFloat64Ptr(), + EqAR: rs.EqAR.ToFloat64Ptr(), // 配当実績 - Div1Q: types.ToFloat64Ptr(rs.Div1Q), - Div2Q: types.ToFloat64Ptr(rs.Div2Q), - Div3Q: types.ToFloat64Ptr(rs.Div3Q), - DivFY: types.ToFloat64Ptr(rs.DivFY), - DivAnn: types.ToFloat64Ptr(rs.DivAnn), - DivUnit: types.ToFloat64Ptr(rs.DivUnit), - DivTotalAnn: types.ToFloat64Ptr(rs.DivTotalAnn), - PayoutRatioAn: types.ToFloat64Ptr(rs.PayoutRatioAn), + Div1Q: rs.Div1Q.ToFloat64Ptr(), + Div2Q: rs.Div2Q.ToFloat64Ptr(), + Div3Q: rs.Div3Q.ToFloat64Ptr(), + DivFY: rs.DivFY.ToFloat64Ptr(), + DivAnn: rs.DivAnn.ToFloat64Ptr(), + DivUnit: rs.DivUnit.ToFloat64Ptr(), + DivTotalAnn: rs.DivTotalAnn.ToFloat64Ptr(), + PayoutRatioAn: rs.PayoutRatioAn.ToFloat64Ptr(), // 配当予想 - FDiv1Q: types.ToFloat64Ptr(rs.FDiv1Q), - FDiv2Q: types.ToFloat64Ptr(rs.FDiv2Q), - FDiv3Q: types.ToFloat64Ptr(rs.FDiv3Q), - FDivFY: types.ToFloat64Ptr(rs.FDivFY), - FDivAnn: types.ToFloat64Ptr(rs.FDivAnn), - FDivUnit: types.ToFloat64Ptr(rs.FDivUnit), - FDivTotalAnn: types.ToFloat64Ptr(rs.FDivTotalAnn), - FPayoutRatioAn: types.ToFloat64Ptr(rs.FPayoutRatioAn), + FDiv1Q: rs.FDiv1Q.ToFloat64Ptr(), + FDiv2Q: rs.FDiv2Q.ToFloat64Ptr(), + FDiv3Q: rs.FDiv3Q.ToFloat64Ptr(), + FDivFY: rs.FDivFY.ToFloat64Ptr(), + FDivAnn: rs.FDivAnn.ToFloat64Ptr(), + FDivUnit: rs.FDivUnit.ToFloat64Ptr(), + FDivTotalAnn: rs.FDivTotalAnn.ToFloat64Ptr(), + FPayoutRatioAn: rs.FPayoutRatioAn.ToFloat64Ptr(), // 翌期配当予想 - NxFDiv1Q: types.ToFloat64Ptr(rs.NxFDiv1Q), - NxFDiv2Q: types.ToFloat64Ptr(rs.NxFDiv2Q), - NxFDiv3Q: types.ToFloat64Ptr(rs.NxFDiv3Q), - NxFDivFY: types.ToFloat64Ptr(rs.NxFDivFY), - NxFDivAnn: types.ToFloat64Ptr(rs.NxFDivAnn), - NxFDivUnit: types.ToFloat64Ptr(rs.NxFDivUnit), - NxFPayoutRatioAn: types.ToFloat64Ptr(rs.NxFPayoutRatioAn), + NxFDiv1Q: rs.NxFDiv1Q.ToFloat64Ptr(), + NxFDiv2Q: rs.NxFDiv2Q.ToFloat64Ptr(), + NxFDiv3Q: rs.NxFDiv3Q.ToFloat64Ptr(), + NxFDivFY: rs.NxFDivFY.ToFloat64Ptr(), + NxFDivAnn: rs.NxFDivAnn.ToFloat64Ptr(), + NxFDivUnit: rs.NxFDivUnit.ToFloat64Ptr(), + NxFPayoutRatioAn: rs.NxFPayoutRatioAn.ToFloat64Ptr(), // 第2四半期業績予想 - FSales2Q: types.ToFloat64Ptr(rs.FSales2Q), - FOP2Q: types.ToFloat64Ptr(rs.FOP2Q), - FOdP2Q: types.ToFloat64Ptr(rs.FOdP2Q), - FNP2Q: types.ToFloat64Ptr(rs.FNP2Q), - FEPS2Q: types.ToFloat64Ptr(rs.FEPS2Q), + FSales2Q: rs.FSales2Q.ToFloat64Ptr(), + FOP2Q: rs.FOP2Q.ToFloat64Ptr(), + FOdP2Q: rs.FOdP2Q.ToFloat64Ptr(), + FNP2Q: rs.FNP2Q.ToFloat64Ptr(), + FEPS2Q: rs.FEPS2Q.ToFloat64Ptr(), // 翌期第2四半期業績予想 - NxFSales2Q: types.ToFloat64Ptr(rs.NxFSales2Q), - NxFOP2Q: types.ToFloat64Ptr(rs.NxFOP2Q), - NxFOdP2Q: types.ToFloat64Ptr(rs.NxFOdP2Q), - NxFNp2Q: types.ToFloat64Ptr(rs.NxFNp2Q), - NxFEPS2Q: types.ToFloat64Ptr(rs.NxFEPS2Q), + NxFSales2Q: rs.NxFSales2Q.ToFloat64Ptr(), + NxFOP2Q: rs.NxFOP2Q.ToFloat64Ptr(), + NxFOdP2Q: rs.NxFOdP2Q.ToFloat64Ptr(), + NxFNp2Q: rs.NxFNp2Q.ToFloat64Ptr(), + NxFEPS2Q: rs.NxFEPS2Q.ToFloat64Ptr(), // 期末業績予想 - FSales: types.ToFloat64Ptr(rs.FSales), - FOP: types.ToFloat64Ptr(rs.FOP), - FOdP: types.ToFloat64Ptr(rs.FOdP), - FNP: types.ToFloat64Ptr(rs.FNP), - FEPS: types.ToFloat64Ptr(rs.FEPS), + FSales: rs.FSales.ToFloat64Ptr(), + FOP: rs.FOP.ToFloat64Ptr(), + FOdP: rs.FOdP.ToFloat64Ptr(), + FNP: rs.FNP.ToFloat64Ptr(), + FEPS: rs.FEPS.ToFloat64Ptr(), // 翌期末業績予想 - NxFSales: types.ToFloat64Ptr(rs.NxFSales), - NxFOP: types.ToFloat64Ptr(rs.NxFOP), - NxFOdP: types.ToFloat64Ptr(rs.NxFOdP), - NxFNp: types.ToFloat64Ptr(rs.NxFNp), - NxFEPS: types.ToFloat64Ptr(rs.NxFEPS), + NxFSales: rs.NxFSales.ToFloat64Ptr(), + NxFOP: rs.NxFOP.ToFloat64Ptr(), + NxFOdP: rs.NxFOdP.ToFloat64Ptr(), + NxFNp: rs.NxFNp.ToFloat64Ptr(), + NxFEPS: rs.NxFEPS.ToFloat64Ptr(), // その他 MatChgSub: rs.MatChgSub, @@ -428,48 +428,48 @@ func (s *StatementsResponse) UnmarshalJSON(data []byte) error { ChgNoASRev: rs.ChgNoASRev, ChgAcEst: rs.ChgAcEst, RetroRst: rs.RetroRst, - ShOutFY: types.ToInt64Ptr(rs.ShOutFY), - TrShFY: types.ToInt64Ptr(rs.TrShFY), - AvgSh: types.ToInt64Ptr(rs.AvgSh), + ShOutFY: rs.ShOutFY.ToInt64Ptr(), + TrShFY: rs.TrShFY.ToInt64Ptr(), + AvgSh: rs.AvgSh.ToInt64Ptr(), // 非連結財務数値 - NCSales: types.ToFloat64Ptr(rs.NCSales), - NCOP: types.ToFloat64Ptr(rs.NCOP), - NCOdP: types.ToFloat64Ptr(rs.NCOdP), - NCNP: types.ToFloat64Ptr(rs.NCNP), - NCEPS: types.ToFloat64Ptr(rs.NCEPS), - NCTA: types.ToFloat64Ptr(rs.NCTA), - NCEq: types.ToFloat64Ptr(rs.NCEq), - NCEqAR: types.ToFloat64Ptr(rs.NCEqAR), - NCBPS: types.ToFloat64Ptr(rs.NCBPS), + NCSales: rs.NCSales.ToFloat64Ptr(), + NCOP: rs.NCOP.ToFloat64Ptr(), + NCOdP: rs.NCOdP.ToFloat64Ptr(), + NCNP: rs.NCNP.ToFloat64Ptr(), + NCEPS: rs.NCEPS.ToFloat64Ptr(), + NCTA: rs.NCTA.ToFloat64Ptr(), + NCEq: rs.NCEq.ToFloat64Ptr(), + NCEqAR: rs.NCEqAR.ToFloat64Ptr(), + NCBPS: rs.NCBPS.ToFloat64Ptr(), // 非連結第2四半期予想 - FNCSales2Q: types.ToFloat64Ptr(rs.FNCSales2Q), - FNCOP2Q: types.ToFloat64Ptr(rs.FNCOP2Q), - FNCOdP2Q: types.ToFloat64Ptr(rs.FNCOdP2Q), - FNCNP2Q: types.ToFloat64Ptr(rs.FNCNP2Q), - FNCEPS2Q: types.ToFloat64Ptr(rs.FNCEPS2Q), + FNCSales2Q: rs.FNCSales2Q.ToFloat64Ptr(), + FNCOP2Q: rs.FNCOP2Q.ToFloat64Ptr(), + FNCOdP2Q: rs.FNCOdP2Q.ToFloat64Ptr(), + FNCNP2Q: rs.FNCNP2Q.ToFloat64Ptr(), + FNCEPS2Q: rs.FNCEPS2Q.ToFloat64Ptr(), // 翌期非連結第2四半期予想 - NxFNCSales2Q: types.ToFloat64Ptr(rs.NxFNCSales2Q), - NxFNCOP2Q: types.ToFloat64Ptr(rs.NxFNCOP2Q), - NxFNCOdP2Q: types.ToFloat64Ptr(rs.NxFNCOdP2Q), - NxFNCNP2Q: types.ToFloat64Ptr(rs.NxFNCNP2Q), - NxFNCEPS2Q: types.ToFloat64Ptr(rs.NxFNCEPS2Q), + NxFNCSales2Q: rs.NxFNCSales2Q.ToFloat64Ptr(), + NxFNCOP2Q: rs.NxFNCOP2Q.ToFloat64Ptr(), + NxFNCOdP2Q: rs.NxFNCOdP2Q.ToFloat64Ptr(), + NxFNCNP2Q: rs.NxFNCNP2Q.ToFloat64Ptr(), + NxFNCEPS2Q: rs.NxFNCEPS2Q.ToFloat64Ptr(), // 非連結期末予想 - FNCSales: types.ToFloat64Ptr(rs.FNCSales), - FNCOP: types.ToFloat64Ptr(rs.FNCOP), - FNCOdP: types.ToFloat64Ptr(rs.FNCOdP), - FNCNP: types.ToFloat64Ptr(rs.FNCNP), - FNCEPS: types.ToFloat64Ptr(rs.FNCEPS), + FNCSales: rs.FNCSales.ToFloat64Ptr(), + FNCOP: rs.FNCOP.ToFloat64Ptr(), + FNCOdP: rs.FNCOdP.ToFloat64Ptr(), + FNCNP: rs.FNCNP.ToFloat64Ptr(), + FNCEPS: rs.FNCEPS.ToFloat64Ptr(), // 翌期非連結期末予想 - NxFNCSales: types.ToFloat64Ptr(rs.NxFNCSales), - NxFNCOP: types.ToFloat64Ptr(rs.NxFNCOP), - NxFNCOdP: types.ToFloat64Ptr(rs.NxFNCOdP), - NxFNCNP: types.ToFloat64Ptr(rs.NxFNCNP), - NxFNCEPS: types.ToFloat64Ptr(rs.NxFNCEPS), + NxFNCSales: rs.NxFNCSales.ToFloat64Ptr(), + NxFNCOP: rs.NxFNCOP.ToFloat64Ptr(), + NxFNCOdP: rs.NxFNCOdP.ToFloat64Ptr(), + NxFNCNP: rs.NxFNCNP.ToFloat64Ptr(), + NxFNCEPS: rs.NxFNCEPS.ToFloat64Ptr(), } } diff --git a/statements_test.go b/statements_test.go index 38b98fb..3b4c631 100644 --- a/statements_test.go +++ b/statements_test.go @@ -558,15 +558,53 @@ func TestStatementsResponse_UnmarshalJSON(t *testing.T) { } sEmpty := respEmpty.Data[0] - // Empty string is converted to 0 for numeric types in current implementation - if sEmpty.Sales == nil || *sEmpty.Sales != 0 { - t.Errorf("Expected Sales 0 for empty string, got %v", sEmpty.Sales) + // 空文字(非設定)は0ではなくnilになる(0円と未設定を区別する) + if sEmpty.Sales != nil { + t.Errorf("Expected Sales nil for empty string, got %v", *sEmpty.Sales) } if sEmpty.MatChgSub != "" { t.Errorf("Expected MatChgSub '' for empty string, got %s", sEmpty.MatChgSub) } - // Empty string is converted to 0 for numeric types in current implementation - if sEmpty.ShOutFY == nil || *sEmpty.ShOutFY != 0 { - t.Errorf("Expected ShOutFY 0 for empty string, got %v", sEmpty.ShOutFY) + if sEmpty.ShOutFY != nil { + t.Errorf("Expected ShOutFY nil for empty string, got %v", *sEmpty.ShOutFY) + } +} + +func TestStatementsResponse_UnmarshalJSON_MissingValueVariants(t *testing.T) { + // 空文字(非設定)、"-"(未定)、null はいずれもnil、数値・数値文字列は値になる + jsonData := `{ + "data": [ + { + "DiscDate": "2024-01-15", + "Code": "72030", + "Sales": 1000.5, + "OP": "200.5", + "OdP": "", + "NP": "-", + "TA": null + } + ] + }` + + var resp StatementsResponse + if err := json.Unmarshal([]byte(jsonData), &resp); err != nil { + t.Fatalf("UnmarshalJSON failed: %v", err) + } + + s := resp.Data[0] + if s.Sales == nil || *s.Sales != 1000.5 { + t.Errorf("Sales = %v, want 1000.5", s.Sales) + } + if s.OP == nil || *s.OP != 200.5 { + t.Errorf("OP = %v, want 200.5", s.OP) + } + if s.OdP != nil { + t.Errorf("OdP = %v, want nil for empty string", *s.OdP) + } + if s.NP != nil { + t.Errorf("NP = %v, want nil for dash", *s.NP) + } + if s.TA != nil { + t.Errorf("TA = %v, want nil for null", *s.TA) } } diff --git a/types/json.go b/types/json.go index 6297342..18bc627 100644 --- a/types/json.go +++ b/types/json.go @@ -138,6 +138,14 @@ type Float64StringWithDash struct { } func (f *Float64StringWithDash) UnmarshalJSON(data []byte) error { + // JSON null means the value is absent. Without this guard the float64 + // branch below would succeed as a no-op and record 0. + if string(data) == "null" { + f.value = nil + f.isUndefined = false + return nil + } + // Try to unmarshal as float64 first var floatVal float64 if err := json.Unmarshal(data, &floatVal); err == nil { @@ -180,6 +188,15 @@ func (f *Float64StringWithDash) ToFloat64Ptr() *float64 { return f.value } +// ToInt64Ptr returns the value as an int64 pointer +func (f *Float64StringWithDash) ToInt64Ptr() *int64 { + if f.value == nil { + return nil + } + val := int64(*f.value) + return &val +} + // StringWithDash is a custom type that handles "-" as a special value type StringWithDash struct { value string diff --git a/types/json_test.go b/types/json_test.go index d27808c..12f55d0 100644 --- a/types/json_test.go +++ b/types/json_test.go @@ -201,4 +201,42 @@ func floatPtr(f float64) *float64 { func int64Ptr(i int64) *int64 { return &i -} \ No newline at end of file +} + +func float64Ptr(f float64) *float64 { + return &f +} + +func TestFloat64StringWithDash_UnmarshalJSON(t *testing.T) { + tests := []struct { + name string + input string + want *float64 + wantInt *int64 + }{ + {name: "number", input: `123.45`, want: float64Ptr(123.45), wantInt: int64Ptr(123)}, + {name: "numeric string", input: `"678.9"`, want: float64Ptr(678.9), wantInt: int64Ptr(678)}, + {name: "empty string", input: `""`, want: nil, wantInt: nil}, + {name: "dash", input: `"-"`, want: nil, wantInt: nil}, + {name: "null", input: `null`, want: nil, wantInt: nil}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var f Float64StringWithDash + if err := json.Unmarshal([]byte(tt.input), &f); err != nil { + t.Fatalf("UnmarshalJSON(%s) error = %v", tt.input, err) + } + + got := f.ToFloat64Ptr() + if (got == nil) != (tt.want == nil) || (got != nil && *got != *tt.want) { + t.Errorf("ToFloat64Ptr() = %v, want %v", got, tt.want) + } + + gotInt := f.ToInt64Ptr() + if (gotInt == nil) != (tt.wantInt == nil) || (gotInt != nil && *gotInt != *tt.wantInt) { + t.Errorf("ToInt64Ptr() = %v, want %v", gotInt, tt.wantInt) + } + }) + } +} From e037081bbcf6b1dfed40108881d374d39f4b06d2 Mon Sep 17 00:00:00 2001 From: utahta Date: Sat, 18 Jul 2026 22:31:31 +0900 Subject: [PATCH 5/5] Suppress gosec G703 for user-specified output path in gitbook2md The output path is intentionally provided by the CLI user, so path traversal does not apply. G703 is a new rule in recent gosec versions and started failing CI without any code change. --- cmd/gitbook2md/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/gitbook2md/main.go b/cmd/gitbook2md/main.go index 0584a1c..5d75ad9 100644 --- a/cmd/gitbook2md/main.go +++ b/cmd/gitbook2md/main.go @@ -667,7 +667,7 @@ func main() { } if outputFile != "" { - err = os.WriteFile(outputFile, []byte(markdown), 0644) // #nosec G306 + err = os.WriteFile(outputFile, []byte(markdown), 0644) // #nosec G306 G703 -- 出力先はCLI利用者が意図して指定するパス if err != nil { log.Fatal(err) }