Skip to content

live

import "github.com/wnjoon/go-yfinance/pkg/live"

Package live provides real-time WebSocket streaming for Yahoo Finance data.

Overview

The live package enables real-time price updates via Yahoo Finance's WebSocket streaming API. Messages are delivered as protobuf-encoded pricing data and decoded into [models.PricingData] structs.

Basic Usage

ws, err := live.New()
if err != nil {
    log.Fatal(err)
}
defer ws.Close()

// Subscribe to symbols
ws.Subscribe([]string{"AAPL", "MSFT", "GOOGL"})

// Listen for updates
ws.Listen(func(data *models.PricingData) {
    fmt.Printf("%s: $%.2f (%.2f%%)\n",
        data.ID, data.Price, data.ChangePercent)
})

Async Listening

For non-blocking operation, use ListenAsync:

ws.Subscribe([]string{"AAPL"})
ws.ListenAsync(func(data *models.PricingData) {
    fmt.Printf("%s: $%.2f\n", data.ID, data.Price)
})

// Do other work...
time.Sleep(10 * time.Second)
ws.Close()

Error Handling

Set an error handler to receive connection errors:

ws, _ := live.New(
    live.WithErrorHandler(func(err error) {
        log.Printf("WebSocket error: %v", err)
    }),
)

Configuration Options

Data Fields

The [models.PricingData] struct contains real-time market data:

  • ID: Ticker symbol
  • Price: Current price
  • Change: Price change from previous close
  • ChangePercent: Percentage change
  • DayHigh, DayLow: Day's high and low
  • DayVolume: Trading volume
  • Bid, Ask: Current bid/ask prices
  • MarketHours: Market state (pre/regular/post/closed)

Thread Safety

All WebSocket methods are safe for concurrent use from multiple goroutines.

Index

Constants

const (
    // DefaultURL is the Yahoo Finance WebSocket endpoint.
    DefaultURL = "wss://streamer.finance.yahoo.com/?version=2"

    // DefaultHeartbeatInterval is the interval for re-sending subscriptions.
    DefaultHeartbeatInterval = 15 * time.Second

    // DefaultReconnectDelay is the delay before attempting reconnection.
    DefaultReconnectDelay = 3 * time.Second
)

type ErrorHandler

ErrorHandler is a callback function for handling errors.

type ErrorHandler func(error)

type MessageHandler

MessageHandler is a callback function for handling pricing data.

type MessageHandler func(*models.PricingData)

type Option

Option is a function that configures a WebSocket.

type Option func(*WebSocket)

func WithErrorHandler

func WithErrorHandler(handler ErrorHandler) Option

WithErrorHandler sets the error handler callback.

func WithHeartbeatInterval

func WithHeartbeatInterval(d time.Duration) Option

WithHeartbeatInterval sets the heartbeat interval.

func WithReconnectDelay

func WithReconnectDelay(d time.Duration) Option

WithReconnectDelay sets the reconnection delay.

func WithURL

func WithURL(url string) Option

WithURL sets a custom WebSocket URL.

type WebSocket

WebSocket represents a WebSocket client for Yahoo Finance streaming.

type WebSocket struct {
    // contains filtered or unexported fields
}

func New

func New(opts ...Option) (*WebSocket, error)

New creates a new WebSocket client.

Example:

ws, err := live.New()
if err != nil {
    log.Fatal(err)
}
defer ws.Close()

func (*WebSocket) Close

func (ws *WebSocket) Close() error

Close closes the WebSocket connection.

func (*WebSocket) Connect

func (ws *WebSocket) Connect() error

Connect establishes the WebSocket connection.

func (*WebSocket) IsConnected

func (ws *WebSocket) IsConnected() bool

IsConnected returns true if the WebSocket is connected.

func (*WebSocket) Listen

func (ws *WebSocket) Listen(handler MessageHandler) error

Listen starts listening for messages and calls the handler for each message. This method blocks until Close() is called or an unrecoverable error occurs.

Example:

ws.Listen(func(data *models.PricingData) {
    fmt.Printf("%s: $%.2f\n", data.ID, data.Price)
})

func (*WebSocket) ListenAsync

func (ws *WebSocket) ListenAsync(handler MessageHandler) error

ListenAsync starts listening in a separate goroutine. Returns immediately. Use Close() to stop listening.

Example:

ws.ListenAsync(func(data *models.PricingData) {
    fmt.Printf("%s: $%.2f\n", data.ID, data.Price)
})
// ... do other work ...
ws.Close()

func (*WebSocket) Subscribe

func (ws *WebSocket) Subscribe(symbols []string) error

Subscribe adds symbols to the subscription list and sends subscribe message.

Example:

ws.Subscribe([]string{"AAPL", "MSFT"})

func (*WebSocket) Subscriptions

func (ws *WebSocket) Subscriptions() []string

Subscriptions returns the current list of subscribed symbols.

func (*WebSocket) Unsubscribe

func (ws *WebSocket) Unsubscribe(symbols []string) error

Unsubscribe removes symbols from the subscription list.

Example:

ws.Unsubscribe([]string{"AAPL"})