diff --git a/internal/quotes/alpaca.go b/internal/quotes/alpaca.go index 48df5ee..0c34927 100644 --- a/internal/quotes/alpaca.go +++ b/internal/quotes/alpaca.go @@ -40,6 +40,9 @@ type Alpaca struct { StreamURL string // AlpacaStream if "" (the feed is added) DataURL string // AlpacaData if "" Log func(format string, args ...any) + // Now is the time, by which the session is open or over (nil: + // time.Now; a test's clock) + Now func() time.Time mu sync.Mutex wanted map[string]time.Time // when each symbol was last wanted @@ -49,6 +52,14 @@ type Alpaca struct { err error // the stream's last failure (nil: connected) } +// now is the time by a's clock. +func (a *Alpaca) now() time.Time { + if a.Now != nil { + return a.Now() + } + return time.Now() +} + func (a *Alpaca) init() { if a.wanted == nil { a.wanted, a.fetched, a.subbed = map[string]time.Time{}, map[string]time.Time{}, map[string]bool{} @@ -255,7 +266,7 @@ func (a *Alpaca) fetch(ctx context.Context, syms []string) error { if err := json.Unmarshal(body, &snaps); err != nil { return fmt.Errorf("Alpaca: %w", err) } - now := time.Now() + now := a.now() a.mu.Lock() for _, s := range syms { a.fetched[s] = now @@ -358,7 +369,7 @@ func (a *Alpaca) clock(ctx context.Context) { defer t.Stop() n := 0 for { - a.Book.Clock(time.Now()) + a.Book.Clock(a.now()) if n++; n%5 == 0 { var syms []string for s := range a.following() { diff --git a/internal/quotes/alpaca_test.go b/internal/quotes/alpaca_test.go index 6bf3d42..c28fb92 100644 --- a/internal/quotes/alpaca_test.go +++ b/internal/quotes/alpaca_test.go @@ -121,8 +121,11 @@ func TestAlpacaSnapshots(t *testing.T) { func TestAlpacaStream(t *testing.T) { srv, subs := fakeAlpaca(t) ws := "ws" + strings.TrimPrefix(srv.URL, "http") + "/v2/" + // Monday before the open, whenever the test is run: the session not + // over, so no close yet + monday := time.Date(2026, 11, 9, 9, 0, 0, 0, eastern) a := &Alpaca{Key: "KEY", Secret: "SECRET", Book: NewBook(nil), Pinned: []string{"AAPL"}, - DataURL: srv.URL + "/v2/", StreamURL: ws} + DataURL: srv.URL + "/v2/", StreamURL: ws, Now: func() time.Time { return monday }} ctx, cancel := context.WithCancel(context.Background()) defer cancel() go a.Run(ctx)