Introducing + Kotlin: Unlocking Real-Time and Historical Stock Market Data

Aug 11, 2023

In this blog post, we will guide you through accessing real-time and historical market data using's Stocks APIs and the JVM client SDK written in the Kotlin programming language. 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, you will first need to create an account and obtain an API key to authenticate your requests.

The next step is to set up your environment. To use's JVM client library with Kotlin, you would need to include it in your Gradle project. Add the following configuration to your build.gradle file:

repositories {
    maven { url "" }

dependencies {
    implementation 'com.github.polygon-io:client-jvm:vX.Y.Z' 

Please replace vX.Y.Z with the current release version of the client library. You can find this in the GitHub releases of the polygon-io/client-jvm repository.

After the setup, read the Stocks API documentation to familiarize yourself with the available data. Finally, please see the client-jvm client library to access the APIs using Kotlin, which contains 100+ pre-canned example code snippets to help you get started and explore various API functionalities.

Accessing Market Data

Using the 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:

val polygonClient = PolygonRestClient(
    <API KEY>, 
    httpClientProvider = okHttpClientProvider

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:

fun stocksAggregatesBars(polygonClient: PolygonRestClient) {
    val params = AggregatesParameters(
        ticker = "AAPL",
        timespan = "day",
        fromDate = "2023-07-03",
        toDate = "2023-07-07",
        limit = 50_000,

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

// last trade
fun stocksLastTrade(polygonClient: PolygonRestClient) {
    println("Last AAPL trade: ")

// last quote (NBBO)
fun stocksLastQuote(polygonClient: PolygonRestClient) {
    println("Last AAPL quote: ")

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

fun stocksSnapshotsAll(polygonClient: PolygonRestClient) {
    println("All tickers snapshot: ")

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

Exploring Reference Data Endpoints'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:

fun stocksTickerDetails(polygonClient: PolygonRestClient) {
    println("Ticker Details: ")
    polygonClient.referenceClient.getTickerDetailsV3Blocking("AAPL", TickerDetailsParameters())

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

fun stocksTickerNews(polygonClient: PolygonRestClient) {
    println("AAPL news:")
    val params = TickerNewsParametersV2(ticker = ComparisonQueryFilterParameters.equal("AAPL"), limit = 2)

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

fun stocksDividends(polygonClient: PolygonRestClient) {
    println("AAPL dividends:")
            ticker = ComparisonQueryFilterParameters.equal("AAPL"),
            limit = 50,

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

Streaming Real-Time Data

The 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 APIs and Kotlin, you'll need the OkHttp library for handling WebSocket connections.

Here's an example of subscribing to all Aggregate Bars and printing them to the console:

package io.polygon.kotlin.sdk.sample

import io.polygon.kotlin.sdk.websocket.*
import kotlinx.coroutines.delay

suspend fun stocksWebsocketSample(polygonKey: String) {
    val websocketClient = PolygonWebSocketClient(
        object : PolygonWebSocketListener {
            override fun onAuthenticated(client: PolygonWebSocketClient) {

            override fun onReceive(
                client: PolygonWebSocketClient,
                message: PolygonWebSocketMessage
            ) {
                when (message) {
                    is PolygonWebSocketMessage.RawMessage -> println(String(
                    else -> println("Receieved Message: $message")

            override fun onDisconnect(client: PolygonWebSocketClient) {

            override fun onError(client: PolygonWebSocketClient, error: Throwable) {
                println("Error: ")


    val subscriptions = listOf(
        PolygonWebSocketSubscription(PolygonWebSocketChannel.Stocks.Trades, "*"),
        //PolygonWebSocketSubscription(PolygonWebSocketChannel.Stocks.Quotes, "*"),
        //PolygonWebSocketSubscription(PolygonWebSocketChannel.Stocks.AggPerSecond, "*"),
        //PolygonWebSocketSubscription(PolygonWebSocketChannel.Stocks.AggPerMinute, "*")


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's APIs and Kotlin. 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 Kotlin examples. Then, build your own applications to deepen your knowledge and gain hands-on experience.

From the blog

See what's happening at

integration quantconnect Feature Image

Integration: QuantConnect

We are excited to announce our integration with QuantConnect! This offering empowers users with state-of-the-art research, backtesting, parameter optimization, and live trading capabilities, all fueled by the robust market data APIs and WebSocket Streams of