Introducing

Polygon.io + Go: Unlocking Real-Time and Historical Stock Market Data

Mar 10, 2023

In this blog post, we will show you how to access market data using Polygon.io's Stock API and the Go programming language. Polygon.io is a financial data platform that provides both real-time and historical market data for Stocks, Options, Forex, and Crypto. With access to this information, developers, investors, and financial institutions can gain valuable insights and make informed decisions.

Getting Started

To access real-time and historical stock market data with Polygon.io you will need to first create an account and obtain an API key to authenticate your requests. Next, to learn more about the wide range of market data, reference data, and real-time streaming data that is available, please read Stock API documentation.

To get started, please make sure you're running at least Go 1.18+ since this client makes use of Go generics. You'll need to get the polygon-io/client-go client library like this:

go get github.com/polygon-io/client-go

From here, interacting with the Polygon.io API's is easy. We have over 50 example code snippet to help you get started, here's one on how to get aggregate bars for a stock over a given date range (code here):

// set params
params := models.ListAggsParams{
	Ticker:     "AAPL",
	Multiplier: 1,
	Timespan:   "minute",
	From:       models.Millis(time.Date(2023, 1, 1, ...),
	To:         models.Millis(time.Date(2023, 3, 9, ...),
}.WithOrder(models.Desc).WithLimit(50000).WithAdjusted(true)

// make request
iter := c.ListAggs(context.Background(), params)

// do something with the result
for iter.Next() {
	log.Print(iter.Item()) 
}

To see this in action, below is a step-by-step guided video tour for getting started with Polygon.io's APIs. Whether you are new to Polygon.io, or have used it before, this video will be a helpful resource for you as you started.

With these steps in place, you are now ready to start accessing all that Polygon.io's APIs offer with the Go programming language. For more information, please see the polygon-io/client-go github repo.

Market Data Endpoints

In this section, we will look at why Market Data Endpoints are a key feature of Polygon.io's APIs and how they provide access to real-time and historical data for the stock market. There are several types of market data endpoints available that provide real-time and historical, including:

  • Aggregated bar data for stocks (charting, candlesticks, visualization, etc)
  • Quotes for stocks (NBBO)
  • Trades data for stocks (raw trade data)
  • Snapshots (see entire markets current state wth a single API call)
  • Technical indicators (SMA, EMA, MACD, and RSI)

To access real-time and historical market data using Polygon.io's APIs and Go, you can make REST API requests to the appropriate endpoints. For example, you can use the following code to retrieve real-time trade and quote data for

AAPL
:

// set params
params := &models.GetLastTradeParams{
	Ticker:     "AAPL",
}

// make request
res, err := c.GetLastTrade(context.Background(), params)
if err != nil {
	log.Fatal(err)
}

// do something with the result
log.Print(res) 

For more information, please see the polygon-io/client-go github repository.

Reference Data Endpoints

In this section we'll be diving into how to use Polygon.io's reference data with Go to access important reference data. There is a range of endpoints, which can be used to retrieve data such as ticker symbols, exchanges, and historical events like stock splits and dividends, amongst other things.

To use these endpoints with Go, you can follow the code snippets provided in the client-Go library's rest/examples directory. The Tickers endpoint can be used to get a list of all active ticker symbols in the stock market, which can be used as a seed for other queries.

For example, you can fetch all dividends or stock splits for these stocks. These reference data endpoints can be powerful when chained together, and can help you to answer questions, enrich existing data, or act as a type of index for ticker symbols that exist.

// init client
c := polygon.New(os.Getenv("POLYGON_API_KEY"))

// set params
params := models.ListTickersParams{}.
	WithType("CS").
	WithMarket(models.AssetStocks).
	WithExchange("XNAS").
	WithActive(true).
	WithSort(models.TickerSymbol).
	WithOrder(models.Asc).
	WithLimit(1000)

// make request
iter := c.ListTickers(context.Background(), params)

// do something with the result
for iter.Next() {
	log.Print(iter.Item()) 
}
if iter.Err() != nil {
	log.Fatal(iter.Err())
}

For more information, please see the polygon-io/client-go repository and the documentation.

Streaming Real-Time Data

The Polygon.io Stocks WebSocket API provides both real-time and 15-minute delayed data streaming access to stock market data from all US stock exchanges (see pricing). Things happen very quickly in the world of finance and having the latest information is essential for monitoring portfolio performance, reacting quickly to news, doing research or conducting technical analysis, making day trading decisions, and for executing algorithmic trading strategies.

Here are the types of data which can be streamed via a websocket in real-time for both individual stock ticker and across the entire market (all tickers):

  • Aggregates (Per Minute): Stream real-time minute aggregates.
  • Aggregates (Per Second): Stream real-time second aggregates.
  • Trades: Stream real-time trades.
  • Quotes: Stream real-time quotes.

To get started, all you need is Go 1.18+ and the polygon-io/client-go library where we leverage a websocket to stream real-time data. The code sample below, subscribes to all trades across the entire market and prints them to the console:

c, err := polygonws.New(polygonws.Config{
	APIKey: os.Getenv("POLYGON_API_KEY"),
	Feed:   polygonws.RealTime,
	Market: polygonws.Stocks,
	Log:    log,
})
if err != nil {
	log.Fatal(err)
}
defer c.Close()

// aggregates
//_ = c.Subscribe(polygonws.StocksMinAggs, "*")
_ = c.Subscribe(polygonws.StocksSecAggs, "*")

// trades
//_ = c.Subscribe(polygonws.StocksTrades, "*")
//_ = c.Subscribe(polygonws.StocksTrades, "TSLA")

// quotes
//_ = c.Subscribe(polygonws.StocksQuotes, "*")
//_ = c.Subscribe(polygonws.StocksQuotes, "TSLA")

if err := c.Connect(); err != nil {
	log.Error(err)
	return
}

for {
	select {
	case <-sigint:
		return
	case <-c.Error():
		return
	case out, more := <-c.Output():
		if !more {
			return
		}
		switch out.(type) {
        case models.EquityAgg:
			log.WithFields(logrus.Fields{"aggregate": out}).Info()
		case models.EquityTrade:
			log.WithFields(logrus.Fields{"trade": out}).Info()
		case models.EquityQuote:
			log.WithFields(logrus.Fields{"quote": out}).Info()
		}
	}
}

To see this in action, below is a step-by-step guided video tour for getting started with streaming real-time stock market data with Polygon.io. This video will be a helpful resource for you as you get started streaming aggregates, trades, and quotes.

With these steps in place, you are now ready to start streaming the real-time data that Polygon.io's APIs offer. For more information, please see the polygon-io/client-go github repo.

Next Steps

You should now have a well-rounded understanding of how to use Polygon.io's APIs and Go to access market data, reference data, and real-time streaming data. By using Polygon.io's APIs, you have extremely powerful tools at your fingertips to analyze market trends, develop real-time financial applications and gain valuable insights.

The best way to get started is to sign up, explore the Stock API documentation, experiment with different endpoints using the Go examples, and then build your own applications to increase your knowledge and gain practical hands-on experience.

From the blog

See what's happening at polygon.io

case study fey Feature Image

Case Study: Fey

Discover how Fey, a rising star in fintech, transformed their financial application's capabilities with Polygon.io's API services. Dive into our latest case study to see how we're powering innovation in finance.