mirror of
https://github.com/D-Modem/bbs.git
synced 2026-11-28 17:38:04 -08:00
Live stock quotes from Alpaca's market data
[quotes] alpaca_key and alpaca_secret follow Alpaca's stream (IEX on the free plan, every exchange on a paid one) for the symbols callers look at, up to alpaca_symbols at a time, and fetch any other by its snapshot. The quotes begin again with each session's first trade, so a live feed kept over days has the right change. bbs quotes alpaca tries the keys. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B82eRTDuJZo7JNHQEC6M1Y
This commit is contained in:
12 files changed
+1089
-16
No files matched your search
@@ -992,6 +992,18 @@ address = 127.0.0.1:2513
|
||||
;listen = 233.215.21.4:10378
|
||||
;interface = eth1
|
||||
;delay = 15 minutes
|
||||
; or Alpaca's market data (alpaca.markets), live: its free plan has IEX's
|
||||
; trades and quotes for 30 symbols at a time on its stream (those callers
|
||||
; looked at last, and default), any symbol by its snapshots. The keys are
|
||||
; an Alpaca account's (a paper-trading one will do): keep this file 0640.
|
||||
; Alpaca's terms ask for 30 days' notice before its data is shown to
|
||||
; others. bbs quotes alpaca AAPL tries them
|
||||
;alpaca_key = PK...
|
||||
;alpaca_secret = ...
|
||||
; iex (the free plan), sip (every exchange: a paid plan) or delayed_sip
|
||||
;alpaca_feed = iex
|
||||
; the most symbols on the stream at once (the free plan's limit)
|
||||
;alpaca_symbols = 30
|
||||
|
||||
; Time. The BBS's clock can follow time servers, and the BBS can be a
|
||||
; time server itself: NTP, NTS (NTP made secure with TLS keys) and PTP.
|
||||
|
||||
+55
-3
@@ -37,6 +37,14 @@ func startNews(ctx context.Context, b *bbs.BBS, cfg *server.Config) {
|
||||
if q := cfg.Quotes; q != nil {
|
||||
b.Quotes = "es.Board{Path: q.File, LiveDelay: q.Delay}
|
||||
b.QuoteDefault = q.Default
|
||||
if q.AlpacaKey != "" {
|
||||
prev, _ := quotes.Load(q.File)
|
||||
al := alpaca(q, quotes.NewBook(prev))
|
||||
al.Log = b.Log.Printf
|
||||
b.Quotes.Live, b.Quotes.Fetch = al.Book, al.Want
|
||||
b.Quotes.LiveSource, b.Quotes.LiveScope, b.Quotes.LiveCredit = "Alpaca "+q.AlpacaFeed, al.Scope(), al.Credit()
|
||||
go al.Run(ctx)
|
||||
}
|
||||
if q.Listen != "" {
|
||||
prev, _ := quotes.Load(q.File)
|
||||
b.Quotes.Live = quotes.NewBook(prev)
|
||||
@@ -49,6 +57,12 @@ func startNews(ctx context.Context, b *bbs.BBS, cfg *server.Config) {
|
||||
}
|
||||
}
|
||||
|
||||
// alpaca is [quotes]' Alpaca, into b.
|
||||
func alpaca(q *server.QuoteSettings, b *quotes.Book) *quotes.Alpaca {
|
||||
return "es.Alpaca{Key: q.AlpacaKey, Secret: q.AlpacaSecret, Feed: q.AlpacaFeed, Max: q.AlpacaSymbols,
|
||||
Pinned: q.Default, Book: b, UserAgent: q.UserAgent}
|
||||
}
|
||||
|
||||
func feedStatus(fs *feeds.Service) []bbs.FeedStatus {
|
||||
var out []bbs.FeedStatus
|
||||
for _, st := range fs.Statuses() {
|
||||
@@ -124,7 +138,7 @@ func feedsCmd(cfg *server.Config, args []string) {
|
||||
}
|
||||
}
|
||||
|
||||
// quotesCmd: bbs quotes fetch [DATE] | load FILE | show SYMBOL...
|
||||
// quotesCmd: bbs quotes fetch [DATE] | load FILE | show SYMBOL... | alpaca [SYMBOL...]
|
||||
func quotesCmd(cfg *server.Config, args []string) {
|
||||
if len(args) == 0 {
|
||||
usage()
|
||||
@@ -197,8 +211,14 @@ func quotesCmd(cfg *server.Config, args []string) {
|
||||
fatal(err)
|
||||
}
|
||||
save(b, "IEX TOPS capture")
|
||||
case "show":
|
||||
s, err := quotes.Load(path)
|
||||
case "show", "alpaca":
|
||||
var s *quotes.Snapshot
|
||||
var err error
|
||||
if args[0] == "show" {
|
||||
s, err = quotes.Load(path)
|
||||
} else {
|
||||
s, err = alpacaCheck(cfg.Quotes, prev, args[1:])
|
||||
}
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
@@ -220,3 +240,35 @@ func quotesCmd(cfg *server.Config, args []string) {
|
||||
usage()
|
||||
}
|
||||
}
|
||||
|
||||
// alpacaCheck tries [quotes]' Alpaca keys: the symbols' snapshots by REST,
|
||||
// then the stream, for a few seconds.
|
||||
func alpacaCheck(q *server.QuoteSettings, prev *quotes.Snapshot, syms []string) (*quotes.Snapshot, error) {
|
||||
if q.AlpacaKey == "" {
|
||||
return nil, fmt.Errorf("no alpaca_key in [quotes]")
|
||||
}
|
||||
if len(syms) == 0 {
|
||||
syms = q.Default
|
||||
}
|
||||
var norm []string
|
||||
for _, s := range syms {
|
||||
if n := quotes.Normalize(s); n != "" {
|
||||
norm = append(norm, n)
|
||||
}
|
||||
}
|
||||
al := alpaca(q, quotes.NewBook(prev))
|
||||
al.Pinned = nil
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
if err := al.Fetch(ctx, norm); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fmt.Printf("snapshots (%s feed): OK\n", q.AlpacaFeed)
|
||||
al.Log = func(f string, a ...any) { fmt.Printf(f+"\n", a...) }
|
||||
sctx, scancel := context.WithTimeout(ctx, 8*time.Second)
|
||||
defer scancel()
|
||||
al.Want(sctx, norm)
|
||||
al.Run(sctx)
|
||||
al.Book.Clock(time.Now())
|
||||
return al.Book.Snapshot("Alpaca " + q.AlpacaFeed), nil
|
||||
}
|
||||
@@ -172,6 +172,7 @@ func usage() {
|
||||
files (some 16 GB, read as they come, not kept)
|
||||
bbs [-config FILE] quotes load FILE quotes from a TOPS capture (pcap, pcapng, .gz)
|
||||
bbs [-config FILE] quotes show SYMBOL... the quotes kept
|
||||
bbs [-config FILE] quotes alpaca [SYMBOL...] try [quotes]' Alpaca keys: the symbols now
|
||||
bbs [-config FILE] gemini cert [-force] make the Gemini server's certificate (it asks
|
||||
for host names, organization and years)
|
||||
`)
|
||||
|
||||
@@ -759,6 +759,10 @@ Stock quotes from IEX (the Investors Exchange): its own trades and quotes, not t
|
||||
| `listen` | | | a live TOPS feed (IEX's real-time feed, or its free delayed one; both need a connection to IEX): its UDP address (a multicast group, joined on the interface), and how far behind it is, for the callers. Examples: `233.215.21.4:10378`. |
|
||||
| `interface` | | | a live TOPS feed (IEX's real-time feed, or its free delayed one; both need a connection to IEX): its UDP address (a multicast group, joined on the interface), and how far behind it is, for the callers. Examples: `eth1`. |
|
||||
| `delay` | | | a live TOPS feed (IEX's real-time feed, or its free delayed one; both need a connection to IEX): its UDP address (a multicast group, joined on the interface), and how far behind it is, for the callers. Examples: `15 minutes`. |
|
||||
| `alpaca_key` | | | or Alpaca's market data (alpaca.markets), live: its free plan has IEX's trades and quotes for 30 symbols at a time on its stream (those callers looked at last, and default), any symbol by its snapshots. The keys are an Alpaca account's (a paper-trading one will do): keep this file 0640. Alpaca's terms ask for 30 days' notice before its data is shown to others. bbs quotes alpaca AAPL tries them. Examples: `PK...`. |
|
||||
| `alpaca_secret` | | | or Alpaca's market data (alpaca.markets), live: its free plan has IEX's trades and quotes for 30 symbols at a time on its stream (those callers looked at last, and default), any symbol by its snapshots. The keys are an Alpaca account's (a paper-trading one will do): keep this file 0640. Alpaca's terms ask for 30 days' notice before its data is shown to others. bbs quotes alpaca AAPL tries them. Examples: `...`. |
|
||||
| `alpaca_feed` | | | iex (the free plan), sip (every exchange: a paid plan) or delayed_sip. Examples: `iex`. |
|
||||
| `alpaca_symbols` | | | the most symbols on the stream at once (the free plan's limit) Examples: `30`. |
|
||||
|
||||
|
||||
## `[time]`
|
||||
|
||||
@@ -148,7 +148,7 @@ The quotes are IEX's (the Investors Exchange): its own trades and quotes,
|
||||
not the whole market's, with IEX's credit on each screen. Every caller has
|
||||
a list of symbols (`default` until they add or remove one); a symbol
|
||||
chosen shows its last trade, open, high, low, close, extended-hours price,
|
||||
bid and ask, and IEX volume.
|
||||
bid and ask, and IEX volume (all the market's, from Alpaca's paid plan).
|
||||
|
||||
### The day before's prices, free (HIST)
|
||||
|
||||
@@ -202,4 +202,40 @@ securities are left out; odd lots count toward volume but not the last
|
||||
sale, high or low; trades outside regular hours are the extended-hours
|
||||
price.
|
||||
|
||||
### Live from Alpaca
|
||||
|
||||
```
|
||||
[quotes]
|
||||
alpaca_key = PK...
|
||||
alpaca_secret = ...
|
||||
alpaca_feed = iex
|
||||
alpaca_symbols = 30
|
||||
```
|
||||
|
||||
[Alpaca](https://alpaca.markets/data)'s market data needs no connection
|
||||
to IEX: an account (a paper-trading one will do) gives a key and secret.
|
||||
Its free plan (`alpaca_feed = iex`) has IEX's trades and quotes, live; a
|
||||
paid one (`sip`) every US exchange's, and `delayed_sip` them 15 minutes
|
||||
late.
|
||||
|
||||
A symbol a caller looks at is fetched then (Alpaca's snapshot: the day so
|
||||
far, and the day before's close for the change), and followed on Alpaca's
|
||||
stream: the default symbols and those looked at most recently, up to
|
||||
`alpaca_symbols` (the free plan allows 30 at a time). What is followed is
|
||||
fetched again every five minutes; the rest when it is next looked at, if
|
||||
a minute old. The quotes begin again with each session's first trade, so
|
||||
nothing need run each morning. The session (before the open, regular
|
||||
hours, after hours, closed) is by the clock: a weekday with no trades by
|
||||
9:35 is taken for a holiday.
|
||||
|
||||
`bbs quotes alpaca AAPL MSFT` tries the keys: the snapshots, then the
|
||||
stream for a few seconds. Keep the configuration file 0640, as the keys
|
||||
are in it.
|
||||
|
||||
Alpaca's terms are for personal, non-commercial use: to make its data
|
||||
available to others through your own application, they ask for 30 days'
|
||||
written notice first, and its written consent to republish it. Tell them
|
||||
of the BBS before you turn this on. `listen` and `alpaca_key` are one or
|
||||
the other.
|
||||
|
||||
**See also:** [Message areas](Message-Areas), [Newsgroups and NNTP](Newsgroups-and-NNTP), [Sysop tools](Sysop-Tools)
|
||||
+28
-9
@@ -419,18 +419,19 @@ func (s *Session) stockQuotes() error {
|
||||
}
|
||||
for {
|
||||
s.N.Doing("Stock quotes")
|
||||
syms := s.symbols()
|
||||
s.B.Quotes.Want(syms...)
|
||||
snap, err := s.B.Quotes.Current()
|
||||
if err != nil {
|
||||
s.UI.Say(view.Plain, "There are no quotes yet: "+err.Error()+".")
|
||||
return nil
|
||||
}
|
||||
syms := s.symbols()
|
||||
t := &view.Table{Title: "Stock quotes", Pick: "Number for more", Empty: "(no symbols: A adds one)",
|
||||
Note: QuoteNote(snap, s.B.Quotes.LiveDelay),
|
||||
Columns: []view.Column{{Title: "Symbol", Width: 8}, {Title: "Price", Width: 10, Right: true},
|
||||
{Title: "Change", Width: 9, Right: true}, {Title: "%", Width: 7, Right: true},
|
||||
{Title: "High", Width: 10, Right: true, Wide: true}, {Title: "Low", Width: 10, Right: true, Wide: true},
|
||||
{Title: "IEX volume", Width: 11, Right: true, Wide: true}},
|
||||
{Title: volumeLabel(snap), Width: 11, Right: true, Wide: true}},
|
||||
Actions: []view.Action{{ID: "add", Label: "Add", Key: 'A', PF: 4}, {ID: "remove", Label: "Remove", Key: 'R', PF: 5},
|
||||
{ID: "look", Label: "Look up", Key: 'L', PF: 6}}}
|
||||
for i, sym := range syms {
|
||||
@@ -455,8 +456,12 @@ func (s *Session) stockQuotes() error {
|
||||
}
|
||||
continue
|
||||
}
|
||||
s.B.Quotes.Want(sym)
|
||||
if now, err := s.B.Quotes.Current(); err == nil {
|
||||
snap = now
|
||||
}
|
||||
if _, ok := snap.Quotes[sym]; !ok {
|
||||
s.UI.Say(view.Bad, "IEX has no trades or quotes of "+sym+" in these prices.")
|
||||
s.UI.Say(view.Bad, "There are no trades or quotes of "+sym+" in these prices.")
|
||||
if c.Action == "look" {
|
||||
continue
|
||||
}
|
||||
@@ -537,7 +542,7 @@ func quoteCells(sym string, q *iex.Quote) []string {
|
||||
func QuoteNote(snap *iex.Snapshot, delay string) []view.Line {
|
||||
var when string
|
||||
if strings.Contains(snap.Source, "live") {
|
||||
when = "IEX's prices now"
|
||||
when = "The prices now"
|
||||
if delay != "" {
|
||||
when += ", " + delay + " behind"
|
||||
}
|
||||
@@ -550,15 +555,29 @@ func QuoteNote(snap *iex.Snapshot, delay string) []view.Line {
|
||||
when += " (as far as it went: " + snap.Session + ")"
|
||||
}
|
||||
}
|
||||
return []view.Line{view.T(view.Dim, when+". Trades and quotes on IEX only."),
|
||||
view.T(view.Dim, iex.Credit)}
|
||||
scope, credit := "on IEX only", iex.Credit
|
||||
if snap.Scope != "" && snap.Scope != "IEX" {
|
||||
scope = "on " + snap.Scope
|
||||
}
|
||||
if snap.Credit != "" {
|
||||
credit = snap.Credit
|
||||
}
|
||||
return []view.Line{view.T(view.Dim, when+". Trades and quotes "+scope+"."), view.T(view.Dim, credit)}
|
||||
}
|
||||
|
||||
// volumeLabel is what the volume is of: IEX's alone, or all the market's.
|
||||
func volumeLabel(snap *iex.Snapshot) string {
|
||||
if snap.Scope == "" || snap.Scope == "IEX" {
|
||||
return "IEX volume"
|
||||
}
|
||||
return "Volume"
|
||||
}
|
||||
|
||||
// quote is one symbol's quote in full.
|
||||
func (s *Session) quote(snap *iex.Snapshot, sym string) error {
|
||||
q := snap.Quotes[sym]
|
||||
if q == nil {
|
||||
s.UI.Say(view.Plain, "IEX has nothing of "+sym+" in these prices.")
|
||||
s.UI.Say(view.Plain, "There is nothing of "+sym+" in these prices.")
|
||||
return nil
|
||||
}
|
||||
lines := QuoteNote(snap, s.B.Quotes.LiveDelay)
|
||||
@@ -566,7 +585,7 @@ func (s *Session) quote(snap *iex.Snapshot, sym string) error {
|
||||
if d, p, ok := q.Change(); ok {
|
||||
lines = append(lines, view.V("Change:", fmt.Sprintf("%+.2f (%+.2f%%) from %s", d, p, money(q.PrevClose))))
|
||||
}
|
||||
if q.Last != 0 {
|
||||
if q.Last != 0 && !q.LastTime.IsZero() {
|
||||
lines = append(lines, view.V("Last trade:", fmt.Sprintf("%s, %d shares, %s ET", money(q.Last), q.LastSize,
|
||||
q.LastTime.In(easternTime()).Format("Mon 2 Jan 15:04:05"))))
|
||||
}
|
||||
@@ -580,7 +599,7 @@ func (s *Session) quote(snap *iex.Snapshot, sym string) error {
|
||||
if q.Bid != 0 || q.Ask != 0 {
|
||||
lines = append(lines, view.V("Bid/ask:", fmt.Sprintf("%s x %d / %s x %d", money(q.Bid), q.BidSize, money(q.Ask), q.AskSize)))
|
||||
}
|
||||
lines = append(lines, view.V("IEX volume:", fmt.Sprintf("%d shares", q.Volume)))
|
||||
lines = append(lines, view.V(volumeLabel(snap)+":", fmt.Sprintf("%d shares", q.Volume)))
|
||||
if q.Halted {
|
||||
lines = append(lines, view.T(view.Warn, "Trading is halted."))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,595 @@
|
||||
package quotes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
// Alpaca's market data: a stream of trades, quotes and bars over a
|
||||
// WebSocket, and snapshots (the day so far, the day before) by REST. Its
|
||||
// free plan has IEX's trades and quotes, live, for 30 symbols at a time
|
||||
// on the stream; its paid one every exchange's (feed "sip").
|
||||
const (
|
||||
AlpacaStream = "wss://stream.data.alpaca.markets/v2/"
|
||||
AlpacaData = "https://data.alpaca.markets/v2/"
|
||||
)
|
||||
|
||||
// Alpaca keeps a Book of the symbols callers look at, from Alpaca's market
|
||||
// data: each is fetched as a snapshot when wanted, and the most recently
|
||||
// wanted (up to Max) are followed on the stream.
|
||||
type Alpaca struct {
|
||||
Key, Secret string
|
||||
Feed string // "iex" (the free plan), "sip", "delayed_sip"
|
||||
Max int // the most symbols on the stream at once (the free plan's 30)
|
||||
Pinned []string
|
||||
Book *Book
|
||||
Client *http.Client
|
||||
UserAgent string
|
||||
StreamURL string // AlpacaStream if "" (the feed is added)
|
||||
DataURL string // AlpacaData if ""
|
||||
Log func(format string, args ...any)
|
||||
|
||||
mu sync.Mutex
|
||||
wanted map[string]time.Time // when each symbol was last wanted
|
||||
fetched map[string]time.Time // when each was last fetched whole
|
||||
subbed map[string]bool // those on the stream now
|
||||
kick chan struct{}
|
||||
err error // the stream's last failure (nil: connected)
|
||||
}
|
||||
|
||||
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{}
|
||||
a.kick = make(chan struct{}, 1)
|
||||
}
|
||||
if a.Max <= 0 {
|
||||
a.Max = 30
|
||||
}
|
||||
if a.Feed == "" {
|
||||
a.Feed = "iex"
|
||||
}
|
||||
if a.Client == nil {
|
||||
a.Client = &http.Client{Timeout: 20 * time.Second}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Alpaca) logf(format string, args ...any) {
|
||||
if a.Log != nil {
|
||||
a.Log(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
// Scope is whose trades the feed has, for the screens.
|
||||
func (a *Alpaca) Scope() string {
|
||||
if a.Feed == "iex" || a.Feed == "" {
|
||||
return "IEX"
|
||||
}
|
||||
return "all US exchanges"
|
||||
}
|
||||
|
||||
// Credit is what the screens say of the data.
|
||||
func (a *Alpaca) Credit() string {
|
||||
if a.Scope() == "IEX" {
|
||||
return "Market data from IEX, by way of Alpaca (alpaca.markets)."
|
||||
}
|
||||
return "Market data from the US exchanges' SIP, by way of Alpaca (alpaca.markets)."
|
||||
}
|
||||
|
||||
// Err is why the stream is not connected (nil: it is, or has not tried).
|
||||
func (a *Alpaca) Err() error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.err
|
||||
}
|
||||
|
||||
// Want: the symbols are about to be seen. Those not fetched in the last
|
||||
// minute, or not on the stream, are fetched now; all go on the stream, in
|
||||
// place of those wanted longest ago.
|
||||
func (a *Alpaca) Want(ctx context.Context, syms []string) {
|
||||
a.mu.Lock()
|
||||
a.init()
|
||||
now := time.Now()
|
||||
var fetch []string
|
||||
for _, s := range syms {
|
||||
if s = Normalize(s); s == "" {
|
||||
continue
|
||||
}
|
||||
a.wanted[s] = now
|
||||
if now.Sub(a.fetched[s]) > time.Minute || !a.subbed[s] && now.Sub(a.fetched[s]) > 15*time.Second {
|
||||
fetch = append(fetch, s)
|
||||
}
|
||||
}
|
||||
a.mu.Unlock()
|
||||
a.poke()
|
||||
if len(fetch) > 0 {
|
||||
if err := a.Fetch(ctx, fetch); err != nil {
|
||||
a.logf("quotes: Alpaca snapshots: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Alpaca) poke() {
|
||||
select {
|
||||
case a.kick <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// following are the symbols the stream should have: the pinned, then the
|
||||
// most recently wanted, up to Max.
|
||||
func (a *Alpaca) following() map[string]bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
out := map[string]bool{}
|
||||
for _, s := range a.Pinned {
|
||||
if len(out) < a.Max {
|
||||
out[s] = true
|
||||
}
|
||||
}
|
||||
var rest []string
|
||||
for s := range a.wanted {
|
||||
if !out[s] {
|
||||
rest = append(rest, s)
|
||||
}
|
||||
}
|
||||
sort.Slice(rest, func(i, j int) bool { return a.wanted[rest[i]].After(a.wanted[rest[j]]) })
|
||||
for _, s := range rest {
|
||||
if len(out) >= a.Max {
|
||||
break
|
||||
}
|
||||
out[s] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// alpacaBar, alpacaTrade, alpacaQuote are as the REST snapshots have them.
|
||||
type alpacaBar struct {
|
||||
T string `json:"t"`
|
||||
O float64 `json:"o"`
|
||||
H float64 `json:"h"`
|
||||
L float64 `json:"l"`
|
||||
C float64 `json:"c"`
|
||||
V uint64 `json:"v"`
|
||||
}
|
||||
|
||||
type alpacaTrade struct {
|
||||
T string `json:"t"`
|
||||
P float64 `json:"p"`
|
||||
S uint32 `json:"s"`
|
||||
C []string `json:"c"`
|
||||
}
|
||||
|
||||
type alpacaQuote struct {
|
||||
T string `json:"t"`
|
||||
BP float64 `json:"bp"`
|
||||
BS uint32 `json:"bs"`
|
||||
AP float64 `json:"ap"`
|
||||
AS uint32 `json:"as"`
|
||||
}
|
||||
|
||||
type alpacaSnapshot struct {
|
||||
LatestTrade *alpacaTrade `json:"latestTrade"`
|
||||
LatestQuote *alpacaQuote `json:"latestQuote"`
|
||||
DailyBar *alpacaBar `json:"dailyBar"`
|
||||
PrevDailyBar *alpacaBar `json:"prevDailyBar"`
|
||||
}
|
||||
|
||||
func alpacaTime(s string) time.Time {
|
||||
t, _ := time.Parse(time.RFC3339Nano, s)
|
||||
return t
|
||||
}
|
||||
|
||||
// regular: t is in regular hours (9:30 to 4, New York time).
|
||||
func regular(t time.Time) bool {
|
||||
et := t.In(eastern)
|
||||
m := et.Hour()*60 + et.Minute()
|
||||
return m >= 9*60+30 && m < 16*60
|
||||
}
|
||||
|
||||
// Fetch reads the symbols' snapshots into the book (at most 100 a request).
|
||||
func (a *Alpaca) Fetch(ctx context.Context, syms []string) error {
|
||||
a.mu.Lock()
|
||||
a.init()
|
||||
a.mu.Unlock()
|
||||
for len(syms) > 0 {
|
||||
n := min(len(syms), 100)
|
||||
if err := a.fetch(ctx, syms[:n]); err != nil {
|
||||
return err
|
||||
}
|
||||
syms = syms[n:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Alpaca) fetch(ctx context.Context, syms []string) error {
|
||||
base := a.DataURL
|
||||
if base == "" {
|
||||
base = AlpacaData
|
||||
}
|
||||
u := base + "stocks/snapshots?" + url.Values{"symbols": {strings.Join(syms, ",")}, "feed": {a.Feed}}.Encode()
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", u, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("APCA-API-KEY-ID", a.Key)
|
||||
req.Header.Set("APCA-API-SECRET-KEY", a.Secret)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if a.UserAgent != "" {
|
||||
req.Header.Set("User-Agent", a.UserAgent)
|
||||
}
|
||||
resp, err := a.Client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode != 200 {
|
||||
var e struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
json.Unmarshal(body, &e)
|
||||
if e.Message == "" {
|
||||
e.Message = resp.Status
|
||||
}
|
||||
if resp.StatusCode == 401 || resp.StatusCode == 403 {
|
||||
e.Message += " (are the key and secret right, and the feed one the plan has?)"
|
||||
}
|
||||
return fmt.Errorf("Alpaca: %s", e.Message)
|
||||
}
|
||||
var snaps map[string]*alpacaSnapshot
|
||||
if err := json.Unmarshal(body, &snaps); err != nil {
|
||||
return fmt.Errorf("Alpaca: %w", err)
|
||||
}
|
||||
now := time.Now()
|
||||
a.mu.Lock()
|
||||
for _, s := range syms {
|
||||
a.fetched[s] = now
|
||||
}
|
||||
a.mu.Unlock()
|
||||
for sym, sn := range snaps {
|
||||
if sn == nil {
|
||||
continue
|
||||
}
|
||||
q, date, ts := sn.quote(sym, now)
|
||||
if date != "" {
|
||||
a.Book.Put(q, date, ts)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// quote is a snapshot as a Quote, of the session of date.
|
||||
func (sn *alpacaSnapshot) quote(sym string, now time.Time) (Quote, string, int64) {
|
||||
q := Quote{Symbol: sym}
|
||||
day := sn.DailyBar
|
||||
if day == nil || alpacaTime(day.T).IsZero() {
|
||||
return q, "", 0
|
||||
}
|
||||
dt := alpacaTime(day.T)
|
||||
date := dt.In(eastern).Format("20060102")
|
||||
q.Open, q.High, q.Low, q.Volume = day.O, day.H, day.L, day.V
|
||||
if sn.PrevDailyBar != nil {
|
||||
q.PrevClose = sn.PrevDailyBar.C
|
||||
}
|
||||
ts := dt.UnixNano()
|
||||
if t := sn.LatestTrade; t != nil {
|
||||
tt := alpacaTime(t.T)
|
||||
if tt.In(eastern).Format("20060102") == date {
|
||||
ts = tt.UnixNano()
|
||||
if regular(tt) {
|
||||
q.Last, q.LastSize, q.LastTime = t.P, t.S, tt
|
||||
} else {
|
||||
q.Extended = t.P
|
||||
}
|
||||
}
|
||||
}
|
||||
if q.Last == 0 {
|
||||
q.Last = day.C // the day's last regular trade, as the bar has it
|
||||
}
|
||||
// the session over: the bar's close is the close
|
||||
sessionEnd := time.Date(dt.In(eastern).Year(), dt.In(eastern).Month(), dt.In(eastern).Day(), 16, 0, 0, 0, eastern)
|
||||
if !now.Before(sessionEnd) {
|
||||
q.Close = day.C
|
||||
}
|
||||
if lq := sn.LatestQuote; lq != nil {
|
||||
q.Bid, q.BidSize, q.Ask, q.AskSize = lq.BP, lq.BS, lq.AP, lq.AS
|
||||
}
|
||||
return q, date, ts
|
||||
}
|
||||
|
||||
// Run follows the stream until ctx is done, connecting again when it is
|
||||
// cut off (later each time, and much later when the keys are refused).
|
||||
func (a *Alpaca) Run(ctx context.Context) {
|
||||
a.mu.Lock()
|
||||
a.init()
|
||||
a.mu.Unlock()
|
||||
if len(a.Pinned) > 0 {
|
||||
a.Want(ctx, a.Pinned)
|
||||
}
|
||||
go a.clock(ctx)
|
||||
wait := time.Second
|
||||
for ctx.Err() == nil {
|
||||
start := time.Now()
|
||||
err := a.stream(ctx)
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.err = err
|
||||
a.subbed = map[string]bool{}
|
||||
a.mu.Unlock()
|
||||
a.logf("quotes: Alpaca stream: %v", err)
|
||||
if time.Since(start) > 5*time.Minute {
|
||||
wait = time.Second
|
||||
}
|
||||
var ae *alpacaError
|
||||
if errors.As(err, &ae) && (ae.Code == 401 || ae.Code == 402 || ae.Code == 409) {
|
||||
wait = 10 * time.Minute // not authenticated, or not allowed that feed: no use asking often
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(wait):
|
||||
}
|
||||
wait = min(wait*2, 10*time.Minute)
|
||||
}
|
||||
}
|
||||
|
||||
// clock keeps the session where the clock has it, and the snapshots of
|
||||
// what is followed fresh (each five minutes: the bars' highs and lows,
|
||||
// corrections).
|
||||
func (a *Alpaca) clock(ctx context.Context) {
|
||||
t := time.NewTicker(time.Minute)
|
||||
defer t.Stop()
|
||||
n := 0
|
||||
for {
|
||||
a.Book.Clock(time.Now())
|
||||
if n++; n%5 == 0 {
|
||||
var syms []string
|
||||
for s := range a.following() {
|
||||
syms = append(syms, s)
|
||||
}
|
||||
if err := a.Fetch(ctx, syms); err != nil && ctx.Err() == nil {
|
||||
a.logf("quotes: Alpaca snapshots: %v", err)
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// alpacaError is an error message of the stream's.
|
||||
type alpacaError struct {
|
||||
Code int
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (e *alpacaError) Error() string { return fmt.Sprintf("%s (%d)", e.Msg, e.Code) }
|
||||
|
||||
// alpacaMsg is any of the stream's messages (the fields are by type: "c"
|
||||
// is a trade's conditions but a bar's close, so it is kept raw).
|
||||
type alpacaMsg struct {
|
||||
T string `json:"T"`
|
||||
Sym string `json:"S"`
|
||||
Msg string `json:"msg"`
|
||||
Code int `json:"code"`
|
||||
Time string `json:"t"`
|
||||
P float64 `json:"p"`
|
||||
Size uint32 `json:"s"`
|
||||
C json.RawMessage `json:"c"`
|
||||
BP float64 `json:"bp"`
|
||||
BS uint32 `json:"bs"`
|
||||
AP float64 `json:"ap"`
|
||||
AS uint32 `json:"as"`
|
||||
O float64 `json:"o"`
|
||||
H float64 `json:"h"`
|
||||
L float64 `json:"l"`
|
||||
V uint64 `json:"v"`
|
||||
SC string `json:"sc"` // a status's code
|
||||
OS uint32 `json:"os"` // a correction's original size
|
||||
CS uint32 `json:"cs"` // and corrected size
|
||||
}
|
||||
|
||||
func scaled(p float64) int64 { return int64(math.Round(p * priceScale)) }
|
||||
|
||||
// stream is one connection to the stream, until it fails.
|
||||
func (a *Alpaca) stream(ctx context.Context) error {
|
||||
u := a.StreamURL
|
||||
if u == "" {
|
||||
u = AlpacaStream
|
||||
}
|
||||
u += a.Feed
|
||||
dctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
h := http.Header{}
|
||||
if a.UserAgent != "" {
|
||||
h.Set("User-Agent", a.UserAgent)
|
||||
}
|
||||
c, _, err := websocket.Dial(dctx, u, &websocket.DialOptions{HTTPClient: a.Client, HTTPHeader: h})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer c.CloseNow()
|
||||
c.SetReadLimit(4 << 20)
|
||||
read := func(ctx context.Context) ([]alpacaMsg, error) {
|
||||
_, data, err := c.Read(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ms []alpacaMsg
|
||||
if err := json.Unmarshal(data, &ms); err != nil {
|
||||
return nil, fmt.Errorf("Alpaca: %w", err)
|
||||
}
|
||||
for _, m := range ms {
|
||||
if m.T == "error" {
|
||||
return nil, &alpacaError{Code: m.Code, Msg: m.Msg}
|
||||
}
|
||||
}
|
||||
return ms, nil
|
||||
}
|
||||
send := func(v any) error {
|
||||
b, _ := json.Marshal(v)
|
||||
wctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
return c.Write(wctx, websocket.MessageText, b)
|
||||
}
|
||||
// connected, then authenticated
|
||||
if _, err := read(dctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := send(map[string]string{"action": "auth", "key": a.Key, "secret": a.Secret}); err != nil {
|
||||
return err
|
||||
}
|
||||
for authed := false; !authed; {
|
||||
ms, err := read(dctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range ms {
|
||||
authed = authed || m.T == "success" && m.Msg == "authenticated"
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.err = nil
|
||||
a.mu.Unlock()
|
||||
a.logf("quotes: Alpaca stream (%s) connected", a.Feed)
|
||||
|
||||
msgs := make(chan []alpacaMsg, 64)
|
||||
failed := make(chan error, 1)
|
||||
go func() {
|
||||
for {
|
||||
ms, err := read(ctx)
|
||||
if err != nil {
|
||||
failed <- err
|
||||
return
|
||||
}
|
||||
msgs <- ms
|
||||
}
|
||||
}()
|
||||
a.poke()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
c.Close(websocket.StatusNormalClosure, "")
|
||||
return ctx.Err()
|
||||
case err := <-failed:
|
||||
return err
|
||||
case <-a.kick:
|
||||
if err := a.resubscribe(send); err != nil {
|
||||
return err
|
||||
}
|
||||
case ms := <-msgs:
|
||||
for _, m := range ms {
|
||||
a.take(m)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// resubscribe brings the stream's symbols to those followed.
|
||||
func (a *Alpaca) resubscribe(send func(any) error) error {
|
||||
want := a.following()
|
||||
a.mu.Lock()
|
||||
var add, drop []string
|
||||
for s := range want {
|
||||
if !a.subbed[s] {
|
||||
add = append(add, s)
|
||||
}
|
||||
}
|
||||
for s := range a.subbed {
|
||||
if !want[s] {
|
||||
drop = append(drop, s)
|
||||
}
|
||||
}
|
||||
a.mu.Unlock()
|
||||
sort.Strings(add)
|
||||
sort.Strings(drop)
|
||||
msg := func(action string, syms []string) map[string]any {
|
||||
return map[string]any{"action": action, "trades": syms, "quotes": syms, "dailyBars": syms, "statuses": syms}
|
||||
}
|
||||
if len(drop) > 0 {
|
||||
if err := send(msg("unsubscribe", drop)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(add) > 0 {
|
||||
if err := send(msg("subscribe", add)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
for _, s := range drop {
|
||||
delete(a.subbed, s)
|
||||
}
|
||||
for _, s := range add {
|
||||
a.subbed[s] = true
|
||||
}
|
||||
a.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// take is one of the stream's messages, into the book.
|
||||
func (a *Alpaca) take(m alpacaMsg) {
|
||||
t := alpacaTime(m.Time)
|
||||
if t.IsZero() {
|
||||
return
|
||||
}
|
||||
ts := t.UnixNano()
|
||||
b := a.Book
|
||||
switch m.T {
|
||||
case "t":
|
||||
var flags byte
|
||||
var cond []string
|
||||
json.Unmarshal(m.C, &cond)
|
||||
for _, c := range cond {
|
||||
switch c {
|
||||
case "I":
|
||||
flags |= flagOddLot
|
||||
case "T", "U":
|
||||
flags |= flagExtended
|
||||
}
|
||||
}
|
||||
if !regular(t) {
|
||||
flags |= flagExtended
|
||||
}
|
||||
b.Trade(m.Sym, ts, m.Size, scaled(m.P), flags)
|
||||
case "q":
|
||||
b.Quote(m.Sym, ts, m.BS, scaled(m.BP), scaled(m.AP), m.AS)
|
||||
case "d":
|
||||
b.Day(m.Sym, ts, m.O, m.H, m.L, m.V)
|
||||
case "x": // a trade cancelled
|
||||
b.Break(m.Sym, ts, m.Size, scaled(m.P))
|
||||
case "c": // a trade corrected: its size, in the volume
|
||||
b.Break(m.Sym, ts, m.OS, 0)
|
||||
b.mu.Lock()
|
||||
if q := b.q[m.Sym]; q != nil {
|
||||
q.Volume += uint64(m.CS)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
case "s":
|
||||
switch m.SC {
|
||||
case "H", "P", "M":
|
||||
b.Status(m.Sym, ts, 'H')
|
||||
case "T", "Q":
|
||||
b.Status(m.Sym, ts, 'T')
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package quotes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
// fakeAlpaca answers as Alpaca's market data does: snapshots by REST, and
|
||||
// a stream that asks for the keys, then sends what is subscribed.
|
||||
func fakeAlpaca(t *testing.T) (*httptest.Server, chan map[string]any) {
|
||||
subs := make(chan map[string]any, 8)
|
||||
var mu sync.Mutex
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/v2/stocks/snapshots":
|
||||
if r.Header.Get("APCA-API-KEY-ID") != "KEY" || r.Header.Get("APCA-API-SECRET-KEY") != "SECRET" {
|
||||
w.WriteHeader(401)
|
||||
w.Write([]byte(`{"message":"forbidden."}`))
|
||||
return
|
||||
}
|
||||
if r.URL.Query().Get("feed") != "iex" {
|
||||
t.Errorf("feed %q", r.URL.Query().Get("feed"))
|
||||
}
|
||||
out := map[string]any{}
|
||||
for _, s := range strings.Split(r.URL.Query().Get("symbols"), ",") {
|
||||
if s == "NOSUCH" {
|
||||
continue
|
||||
}
|
||||
out[s] = map[string]any{
|
||||
"latestTrade": map[string]any{"t": "2026-11-06T20:59:59.5Z", "p": 342.41, "s": 50, "c": []string{"@"}},
|
||||
"latestQuote": map[string]any{"t": "2026-11-06T21:00:00Z", "bp": 342.3, "bs": 1, "ap": 342.5, "as": 2},
|
||||
"dailyBar": map[string]any{"t": "2026-11-06T05:00:00Z", "o": 338.59, "h": 345.76, "l": 338.59, "c": 342.41, "v": 500},
|
||||
"prevDailyBar": map[string]any{"t": "2026-11-05T05:00:00Z", "o": 335, "h": 341, "l": 334, "c": 340, "v": 900},
|
||||
}
|
||||
}
|
||||
json.NewEncoder(w).Encode(out)
|
||||
case "/v2/iex":
|
||||
c, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
defer c.CloseNow()
|
||||
ctx := r.Context()
|
||||
c.Write(ctx, websocket.MessageText, []byte(`[{"T":"success","msg":"connected"}]`))
|
||||
_, data, err := c.Read(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var auth map[string]string
|
||||
json.Unmarshal(data, &auth)
|
||||
if auth["action"] != "auth" || auth["key"] != "KEY" || auth["secret"] != "SECRET" {
|
||||
c.Write(ctx, websocket.MessageText, []byte(`[{"T":"error","code":402,"msg":"auth failed"}]`))
|
||||
return
|
||||
}
|
||||
c.Write(ctx, websocket.MessageText, []byte(`[{"T":"success","msg":"authenticated"}]`))
|
||||
for {
|
||||
_, data, err := c.Read(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var m map[string]any
|
||||
json.Unmarshal(data, &m)
|
||||
subs <- m
|
||||
mu.Lock()
|
||||
// a new session's first trades: Monday's, then an odd lot
|
||||
// and one after hours
|
||||
c.Write(ctx, websocket.MessageText, []byte(`[{"T":"subscription","trades":["AAPL"]},
|
||||
{"T":"t","S":"AAPL","p":345,"s":100,"c":["@"],"t":"2026-11-09T14:31:00Z"},
|
||||
{"T":"t","S":"AAPL","p":399,"s":10,"c":["@","I"],"t":"2026-11-09T14:32:00Z"},
|
||||
{"T":"q","S":"AAPL","bp":344.9,"bs":3,"ap":345.1,"as":4,"t":"2026-11-09T14:32:01Z"},
|
||||
{"T":"d","S":"AAPL","o":344,"h":346,"l":343.5,"c":345,"v":1200,"t":"2026-11-09T05:00:00Z"},
|
||||
{"T":"t","S":"AAPL","p":346.5,"s":5,"c":["@","T"],"t":"2026-11-09T21:30:00Z"},
|
||||
{"T":"s","S":"AAPL","sc":"H","t":"2026-11-09T21:31:00Z"}]`))
|
||||
mu.Unlock()
|
||||
}
|
||||
default:
|
||||
t.Errorf("asked for %s", r.URL)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, subs
|
||||
}
|
||||
|
||||
func TestAlpacaSnapshots(t *testing.T) {
|
||||
srv, _ := fakeAlpaca(t)
|
||||
a := &Alpaca{Key: "KEY", Secret: "SECRET", Book: NewBook(nil), DataURL: srv.URL + "/v2/"}
|
||||
if err := a.Fetch(context.Background(), []string{"AAPL", "NOSUCH"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := a.Book.Snapshot("Alpaca iex")
|
||||
q := s.Quotes["AAPL"]
|
||||
if q == nil || q.Open != 338.59 || q.High != 345.76 || q.Close != 342.41 || q.Last != 342.41 || q.PrevClose != 340 ||
|
||||
q.Volume != 500 || q.Bid != 342.3 || q.AskSize != 2 || q.LastTime.IsZero() {
|
||||
t.Fatalf("AAPL %+v", q)
|
||||
}
|
||||
if d, _, ok := q.Change(); !ok || d < 2.40 || d > 2.42 {
|
||||
t.Errorf("change %v", d)
|
||||
}
|
||||
if _, ok := s.Quotes["NOSUCH"]; ok {
|
||||
t.Error("a symbol Alpaca has not")
|
||||
}
|
||||
bad := &Alpaca{Key: "KEY", Secret: "WRONG", Book: NewBook(nil), DataURL: srv.URL + "/v2/"}
|
||||
if err := bad.Fetch(context.Background(), []string{"AAPL"}); err == nil || !strings.Contains(err.Error(), "forbidden") {
|
||||
t.Errorf("wrong secret: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAlpacaStream: Friday's quote from the snapshot, then Monday's trades
|
||||
// on the stream begin the quote again, with Friday's close the change is
|
||||
// from.
|
||||
func TestAlpacaStream(t *testing.T) {
|
||||
srv, subs := fakeAlpaca(t)
|
||||
ws := "ws" + strings.TrimPrefix(srv.URL, "http") + "/v2/"
|
||||
a := &Alpaca{Key: "KEY", Secret: "SECRET", Book: NewBook(nil), Pinned: []string{"AAPL"},
|
||||
DataURL: srv.URL + "/v2/", StreamURL: ws}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go a.Run(ctx)
|
||||
select {
|
||||
case m := <-subs:
|
||||
if m["action"] != "subscribe" || len(m["trades"].([]any)) != 1 || m["dailyBars"].([]any)[0] != "AAPL" {
|
||||
t.Errorf("subscribed %v", m)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("not subscribed (%v)", a.Err())
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if q := a.Book.Snapshot("x").Quotes["AAPL"]; q != nil && q.Halted {
|
||||
if q.PrevClose != 342.41 || q.Last != 345 || q.Open != 345 || q.High != 346 || q.Low != 343.5 ||
|
||||
q.Volume != 1205 || q.Extended != 346.5 || q.Bid != 344.9 || q.Close != 0 {
|
||||
t.Errorf("Monday's AAPL %+v", q)
|
||||
}
|
||||
// a symbol wanted goes on the stream too
|
||||
a.Want(ctx, []string{"MSFT"})
|
||||
select {
|
||||
case m := <-subs:
|
||||
if m["action"] != "subscribe" || m["quotes"].([]any)[0] != "MSFT" {
|
||||
t.Errorf("subscribed %v", m)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("MSFT not subscribed")
|
||||
}
|
||||
return
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("the stream's trades did not come: %+v (%v)", a.Book.Snapshot("x").Quotes["AAPL"], a.Err())
|
||||
}
|
||||
|
||||
func TestAlpacaRefused(t *testing.T) {
|
||||
srv, _ := fakeAlpaca(t)
|
||||
ws := "ws" + strings.TrimPrefix(srv.URL, "http") + "/v2/"
|
||||
a := &Alpaca{Key: "KEY", Secret: "WRONG", Book: NewBook(nil), StreamURL: ws}
|
||||
a.init()
|
||||
err := a.stream(context.Background())
|
||||
if ae, ok := err.(*alpacaError); !ok || ae.Code != 402 {
|
||||
t.Errorf("refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFollowing(t *testing.T) {
|
||||
a := &Alpaca{Max: 3, Pinned: []string{"SPY"}}
|
||||
a.init()
|
||||
now := time.Now()
|
||||
a.wanted["A"], a.wanted["B"], a.wanted["C"] = now.Add(-3*time.Minute), now.Add(-time.Minute), now
|
||||
f := a.following()
|
||||
if len(f) != 3 || !f["SPY"] || !f["C"] || !f["B"] || f["A"] {
|
||||
t.Errorf("following %v", f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClock(t *testing.T) {
|
||||
b := NewBook(nil)
|
||||
at := func(day, h, m int) time.Time { return time.Date(2026, 11, day, h, m, 0, 0, eastern) }
|
||||
for _, c := range []struct {
|
||||
when time.Time
|
||||
want string
|
||||
}{{at(7, 12, 0), "closed"}, {at(9, 3, 0), "closed"}, {at(9, 8, 0), "before the open"},
|
||||
{at(9, 9, 40), "closed"}} { // no trades by 9:35: a holiday
|
||||
b.Clock(c.when)
|
||||
if b.session != c.want {
|
||||
t.Errorf("%v: %q", c.when, b.session)
|
||||
}
|
||||
}
|
||||
b.Trade("AAPL", at(9, 9, 31).UnixNano(), 100, 3450000, 0)
|
||||
b.Clock(at(9, 10, 0))
|
||||
if b.session != "regular hours" {
|
||||
t.Errorf("trading: %q", b.session)
|
||||
}
|
||||
b.Clock(at(9, 17, 0))
|
||||
if b.session != "after hours" {
|
||||
t.Errorf("after: %q", b.session)
|
||||
}
|
||||
}
|
||||
+91
-2
@@ -42,13 +42,16 @@ func (q *Quote) Change() (float64, float64, bool) {
|
||||
}
|
||||
|
||||
// Price is the quote's price: the close if there is one, else the last
|
||||
// trade, else the middle of the bid and ask.
|
||||
// trade, else the last trade outside regular hours (before the open), else
|
||||
// the middle of the bid and ask.
|
||||
func (q *Quote) Price() float64 {
|
||||
switch {
|
||||
case q.Close != 0:
|
||||
return q.Close
|
||||
case q.Last != 0:
|
||||
return q.Last
|
||||
case q.Extended != 0:
|
||||
return q.Extended
|
||||
case q.Bid != 0 && q.Ask != 0:
|
||||
return (q.Bid + q.Ask) / 2
|
||||
}
|
||||
@@ -62,6 +65,10 @@ type Snapshot struct {
|
||||
Made time.Time
|
||||
Quotes map[string]*Quote
|
||||
Session string // where the session was: "closed", "regular hours" ...
|
||||
// Scope is whose trades these are ("": IEX's own), Credit whose data
|
||||
// it is ("": IEX's, as its HIST terms ask)
|
||||
Scope string `json:",omitempty"`
|
||||
Credit string `json:",omitempty"`
|
||||
}
|
||||
|
||||
// Book keeps the quotes as a feed's messages come: a Handler.
|
||||
@@ -73,11 +80,12 @@ type Book struct {
|
||||
session string
|
||||
prev map[string]float64 // the session before's closes
|
||||
last int64 // the newest timestamp seen (ns)
|
||||
day map[string]string // each quote's session (YYYYMMDD), when known
|
||||
}
|
||||
|
||||
// NewBook is an empty book; prev is the session before's (nil: none).
|
||||
func NewBook(prev *Snapshot) *Book {
|
||||
b := &Book{q: map[string]*Quote{}, test: map[string]bool{}, prev: map[string]float64{}}
|
||||
b := &Book{q: map[string]*Quote{}, test: map[string]bool{}, prev: map[string]float64{}, day: map[string]string{}}
|
||||
if prev != nil {
|
||||
for s, q := range prev.Quotes {
|
||||
if p := q.Price(); p != 0 {
|
||||
@@ -108,11 +116,35 @@ func (b *Book) seen(ts int64) {
|
||||
|
||||
func price(p int64) float64 { return float64(p) / priceScale }
|
||||
|
||||
func dateOf(ts int64) string { return time.Unix(0, ts).In(eastern).Format("20060102") }
|
||||
|
||||
// touch: a trade of sym at ts. The first of a new session (a live feed
|
||||
// kept over days) begins the quote again, with the session before's
|
||||
// price as the close the change is from.
|
||||
func (b *Book) touch(sym string, ts int64) {
|
||||
d := dateOf(ts)
|
||||
was := b.day[sym]
|
||||
b.day[sym] = d
|
||||
q := b.q[sym]
|
||||
if q == nil || was == "" || d <= was {
|
||||
return
|
||||
}
|
||||
prev := q.Close
|
||||
if prev == 0 {
|
||||
prev = q.Last
|
||||
}
|
||||
if prev == 0 {
|
||||
prev = q.PrevClose
|
||||
}
|
||||
*q = Quote{Symbol: sym, PrevClose: prev}
|
||||
}
|
||||
|
||||
// Trade: Handler.
|
||||
func (b *Book) Trade(sym string, ts int64, size uint32, p int64, flags byte) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.seen(ts)
|
||||
b.touch(sym, ts)
|
||||
q := b.get(sym)
|
||||
q.Volume += uint64(size)
|
||||
pr := price(p)
|
||||
@@ -200,6 +232,63 @@ func (b *Book) System(ts int64, event byte) {
|
||||
}
|
||||
}
|
||||
|
||||
// Put is a quote whole, as a source of them has it (Alpaca's snapshots):
|
||||
// of the session of date (YYYYMMDD), and as of ts.
|
||||
func (b *Book) Put(q Quote, date string, ts int64) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.seen(ts)
|
||||
c := q
|
||||
b.q[q.Symbol] = &c
|
||||
b.day[q.Symbol] = date
|
||||
}
|
||||
|
||||
// Day is a session's prices so far, as bars have them: the open, high and
|
||||
// low are taken where the trades have not given them, and the volume where
|
||||
// it is more. Not of the quote's session, it is left.
|
||||
func (b *Book) Day(sym string, ts int64, open, high, low float64, volume uint64) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
q := b.q[sym]
|
||||
if q == nil || b.day[sym] != dateOf(ts) {
|
||||
return
|
||||
}
|
||||
if q.Open == 0 {
|
||||
q.Open = open
|
||||
}
|
||||
if q.High == 0 || high > q.High {
|
||||
q.High = high
|
||||
}
|
||||
if q.Low == 0 || low != 0 && low < q.Low {
|
||||
q.Low = low
|
||||
}
|
||||
if volume > q.Volume {
|
||||
q.Volume = volume
|
||||
}
|
||||
}
|
||||
|
||||
// Clock: where the session is, by the clock, for a feed with no system
|
||||
// events (Alpaca's). A weekday with no trades by 9:35 is a holiday.
|
||||
func (b *Book) Clock(now time.Time) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
et := now.In(eastern)
|
||||
min := et.Hour()*60 + et.Minute()
|
||||
traded := b.last != 0 && dateOf(b.last) == et.Format("20060102")
|
||||
switch {
|
||||
case et.Weekday() == time.Saturday || et.Weekday() == time.Sunday, min < 4*60, min >= 20*60:
|
||||
b.session = "closed"
|
||||
case min < 9*60+30:
|
||||
b.session = "before the open"
|
||||
case !traded && min >= 9*60+35:
|
||||
b.session = "closed"
|
||||
case min < 16*60:
|
||||
b.session = "regular hours"
|
||||
default:
|
||||
b.session = "after hours"
|
||||
}
|
||||
}
|
||||
|
||||
// testSymbols are IEX's test securities, which trade like any other.
|
||||
var testSymbols = map[string]bool{"ZEXIT": true, "ZIEXT": true, "ZXIET": true, "ZVZZT": true, "ZWZZT": true,
|
||||
"ZXZZT": true, "ZBZX": true, "ZJZZT": true, "ZTEST": true, "CBO": true, "CBX": true, "NTEST": true}
|
||||
|
||||
@@ -200,6 +200,12 @@ type Board struct {
|
||||
Live *Book // a live feed (nil: none)
|
||||
// LiveDelay is how far behind the live feed is ("": real time)
|
||||
LiveDelay string
|
||||
// LiveSource names the live feed ("": IEX TOPS); LiveScope and
|
||||
// LiveCredit are its Snapshot's Scope and Credit
|
||||
LiveSource, LiveScope, LiveCredit string
|
||||
// Fetch, if set, is asked for symbols a caller is about to see (the
|
||||
// live feed's quotes are only of those asked for: Alpaca's)
|
||||
Fetch func(ctx context.Context, syms []string)
|
||||
|
||||
mu sync.Mutex
|
||||
snap *Snapshot
|
||||
@@ -210,7 +216,12 @@ type Board struct {
|
||||
// Current is the quotes as they are now; nil (and why) if there are none.
|
||||
func (b *Board) Current() (*Snapshot, error) {
|
||||
if b.Live != nil {
|
||||
s := b.Live.Snapshot("IEX TOPS (live)")
|
||||
src := b.LiveSource
|
||||
if src == "" {
|
||||
src = "IEX TOPS"
|
||||
}
|
||||
s := b.Live.Snapshot(src + " (live)")
|
||||
s.Scope, s.Credit = b.LiveScope, b.LiveCredit
|
||||
if len(s.Quotes) > 0 || b.Path == "" {
|
||||
return s, nil
|
||||
}
|
||||
@@ -234,6 +245,17 @@ func (b *Board) Current() (*Snapshot, error) {
|
||||
return b.snap, b.err
|
||||
}
|
||||
|
||||
// Want: the symbols are about to be seen, so a source that fetches them
|
||||
// on demand is asked for them (a few seconds at most).
|
||||
func (b *Board) Want(syms ...string) {
|
||||
if b.Fetch == nil || len(syms) == 0 {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
b.Fetch(ctx, syms)
|
||||
}
|
||||
|
||||
// Listen reads a live TOPS feed from UDP (a multicast group, joined on
|
||||
// the interface named, or a unicast port) into b until ctx is done.
|
||||
func Listen(ctx context.Context, addr, iface string, b *Book) error {
|
||||
|
||||
@@ -21,6 +21,13 @@ type QuoteSettings struct {
|
||||
Interface string // the interface its multicast group is joined on
|
||||
Delay string // how far behind the live feed is ("": real time)
|
||||
Default []string
|
||||
|
||||
// Alpaca's market data, live, instead of a TOPS feed (AlpacaKey "":
|
||||
// not)
|
||||
AlpacaKey, AlpacaSecret string
|
||||
AlpacaFeed string // iex, sip or delayed_sip
|
||||
AlpacaSymbols int // the most on its stream at once
|
||||
UserAgent string
|
||||
}
|
||||
|
||||
// userAgent is how the BBS names itself to the sites it reads, with the
|
||||
@@ -128,6 +135,26 @@ func (c *Config) feedSections(cf *config.File) error {
|
||||
return fmt.Errorf("[quotes] listen: %v", err)
|
||||
}
|
||||
}
|
||||
q.AlpacaKey = s.String("alpaca_key", "")
|
||||
q.AlpacaSecret = s.String("alpaca_secret", "")
|
||||
q.AlpacaFeed = s.String("alpaca_feed", "iex")
|
||||
q.UserAgent = userAgent(fs.String("contact", ""))
|
||||
var err error
|
||||
if q.AlpacaSymbols, err = s.Int("alpaca_symbols", 30, 1, 10000); err != nil {
|
||||
return fmt.Errorf("[quotes] %v", err)
|
||||
}
|
||||
switch {
|
||||
case q.AlpacaKey == "" && q.AlpacaSecret == "":
|
||||
case q.AlpacaKey == "" || q.AlpacaSecret == "":
|
||||
return fmt.Errorf("[quotes] alpaca_key and alpaca_secret go together")
|
||||
case q.Listen != "":
|
||||
return fmt.Errorf("[quotes] listen (a TOPS feed) or alpaca_key (Alpaca's), not both")
|
||||
case q.AlpacaFeed != "iex" && q.AlpacaFeed != "sip" && q.AlpacaFeed != "delayed_sip":
|
||||
return fmt.Errorf("[quotes] alpaca_feed: %q is not iex, sip or delayed_sip", q.AlpacaFeed)
|
||||
}
|
||||
if q.AlpacaKey != "" && q.AlpacaFeed == "delayed_sip" && q.Delay == "" {
|
||||
q.Delay = "15 minutes"
|
||||
}
|
||||
for _, sym := range strings.FieldsFunc(s.String("default", "SPY DIA QQQ AAPL MSFT"), func(r rune) bool { return r == ',' || r == ' ' }) {
|
||||
n := quotes.Normalize(sym)
|
||||
if n == "" {
|
||||
|
||||
@@ -77,9 +77,20 @@ delay = 15 minutes
|
||||
"[feed x]\nurl = ftp://example.org/\n",
|
||||
"[weather]\nquake_min = big\n",
|
||||
"[quotes]\ndefault = not a symbol!\n",
|
||||
"[quotes]\nalpaca_key = PK1\n",
|
||||
"[quotes]\nalpaca_key = PK1\nalpaca_secret = s\nlisten = 233.215.21.4:10378\n",
|
||||
"[quotes]\nalpaca_key = PK1\nalpaca_secret = s\nalpaca_feed = nasdaq\n",
|
||||
} {
|
||||
if _, err := Parse([]byte("[listen telnet]\ntype = telnet\naddress = :2300\n" + bad)); err == nil {
|
||||
t.Errorf("taken: %q", bad)
|
||||
}
|
||||
}
|
||||
|
||||
c, err = Parse([]byte("[listen telnet]\ntype = telnet\naddress = :2300\n[quotes]\nalpaca_key = PK1\nalpaca_secret = s\nalpaca_feed = delayed_sip\n"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if q := c.Quotes; q.AlpacaKey != "PK1" || q.AlpacaSecret != "s" || q.AlpacaSymbols != 30 || q.Delay != "15 minutes" {
|
||||
t.Errorf("Alpaca %+v", q)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user