Introducing

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

Apr 17, 2023

In this blog post, we will guide you through accessing real-time and historical market data using Polygon.io's Stocks APIs and the JavaScript programming language. Polygon.io is a financial data platform that provides comprehensive market data for Stocks, Options, Indices, Forex, and Crypto. This information is invaluable for developers, investors, and financial institutions to gain insights and make informed decisions.

Getting Started

To access real-time and historical market data with Polygon.io, you will first need to create an account and obtain an API key to authenticate your requests. Next, read the Stocks API documentation to familiarize yourself with the available data. Finally, install the "@polygon.io/client-js" client library to access the APIs using JavaScript:

npm install --save @polygon.io/client-js

Additionally, be sure to check out the polygon-io/client-js GitHub repository, which contains 100+ pre-canned example code snippets to help you get started and explore various API functionalities.

Accessing Market Data

Using the Polygon.io APIs, you can access various types of market data, including aggregated bar data, quotes, trades data, snapshots, and technical indicators for selected ticker symbols.

To authenticate your requests, you'll need to use your API key. Here's an example of initializing the REST client with your API key:

const { restClient } = require('@polygon.io/client-js');
const rest = restClient("API KEY");

Now you're ready to make requests. We'll start with an example that fetches Aggregate Bars, that include the open, high, low, close prices, and volume data, which is great for creating visualizations:

rest.stocks.aggregates("AAPL", 1, "day", "2023-01-01", "2019-04-14").then((data) => {
	console.log(data);
}).catch(e => {
	console.error('An error happened:', e);
});

It is also easy to retrieve the last trade and last quote (NBBO) for any ticker:

// last trade
rest.stocks.lastTrade("AAPL").then((data) => {
	console.log(data);
}).catch(e => {
	console.error('An error happened:', e);
});

// last quote (NBBO)
rest.stocks.lastQuote("AAPL").then((data) => {
	console.log(data);
}).catch(e => {
	console.error('An error happened:', e);
});

Or, maybe you want a market-wide snapshot of all tickers:

rest.stocks.snapshotAllTickers().then((data) => {
	console.log(data);
}).catch(e => {
	console.error('An error happened:', e);
});

These examples demonstrate how to access various types of market data using the Polygon.io APIs and JavaScript. For more information, please see the polygon-io/client-js repo for compete example code snippets and the documentation.

Exploring Reference Data Endpoints

Polygon.io's reference data endpoints offer a range of information such as ticker symbols, exchanges, and historical events like stock splits and dividends. Use these endpoints to enrich your existing data and answer questions about market trends.

Retrieve details about a specific ticker and the company behind it:

rest.reference.tickerDetails("AAPL").then((data) => {
	console.log(data);
}).catch(e => {
	console.error('An error happened:', e);
});

Get the most recent news articles relating to a stock ticker symbol:

rest.reference.tickerNews("AAPL").then((data) => {
	console.log(data);
}).catch(e => {
	console.error('An error happened:', e);
});

Fetch a list of historical cash dividends information for a stock:

rest.reference.dividends("AAPL").then((data) => {
	console.log(data);
}).catch(e => {
	console.error('An error happened:', e);
});

These examples showcase how easy it is to access the reference data endpoints with the Polygon.io APIs and JavaScript.

Streaming Real-Time Data

The Polygon.io Stocks WebSocket API provides real-time and 15-minute delayed data streaming access to stock market data from all US stock exchanges. Streaming data types include aggregates, trades, and quotes for individual stock tickers and across the entire market.

To stream real-time data using the Polygon.io APIs and JavaScript, you'll need the

ws
package for handling WebSocket connections. Install the package using the following command:

npm install ws

Next, the following example subscribes to all Aggregate Bars prints them to the console:

const WebSocket = require('ws')
const APIKEY = 'API KEY'
const ws = new WebSocket('wss://delayed.polygon.io/stocks') // 15-min delay
//const ws = new WebSocket('wss://socket.polygon.io/stocks') // real-time

// Connection Opened:
ws.on('open', () => {
	console.log('Connected!')
	ws.send(`{"action":"auth","params":"${APIKEY}"}`)

	// aggregates
	//ws.send(`{"action":"subscribe","params":"AM.*"}`) // min
	ws.send(`{"action":"subscribe","params":"A.*"}`) // sec

	// trades
	//ws.send(`{"action":"subscribe","params":"T.*"}`)
	//ws.send(`{"action":"subscribe","params":"T.TSLA"}`)

	// quotes
	//ws.send(`{"action":"subscribe","params":"Q.*"}`)
	//ws.send(`{"action":"subscribe","params":"Q.TSLA"}`)
})

// Per message packet:
ws.on('message', ( data ) => {
	data = JSON.parse( data )
	data.map(( msg ) => {
		if( msg.ev === 'status' ){
			return console.log('Status Update:', msg.message)
		}
		console.log(msg)
	})
})

ws.on('error', console.log)

Next Steps

By following this guide, you should now have a solid understanding of how to access market data, reference data, and real-time streaming data using Polygon.io's APIs and JavaScript. These powerful tools will help you analyze market trends, develop real-time financial applications, and gain valuable insights.

Start by signing up, exploring the Stocks API documentation, and experimenting with the provided JavaScript examples. Then, build your own applications to deepen your knowledge and gain 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.