DEV Community

Cover image for How to Fetch the Bitcoin Price from Kraken API in PureScript
Alexej Bondarenko
Alexej Bondarenko

Posted on

How to Fetch the Bitcoin Price from Kraken API in PureScript

In the fast-evolving world of cryptocurrencies, staying updated with real-time prices is crucial for both enthusiasts and investors. Bitcoin, being the pioneer and most valued cryptocurrency, holds significant interest. This article delves into how one can harness the capabilities of PureScript, a powerful and expressive functional programming language, to fetch Bitcoin prices from the Kraken API.

PureScript, often likened to Haskell, is a strongly-typed language that compiles to JavaScript. It's known for its robust type system and functional programming paradigms, making it an excellent choice for writing reliable, maintainable web applications. Its strong type system can enforce correctness at compile time, reducing runtime errors and enhancing code quality.

Kraken, on the other hand, is one of the largest and most respected cryptocurrency exchanges in the world. It offers a comprehensive API that provides access to real-time and historical market data, including Bitcoin prices. Utilizing this API, developers can integrate cryptocurrency data into their applications or perform analysis.

In this article, we will guide you through setting up a PureScript environment, understanding the basics of the Kraken API, and step by step, demonstrate how to write a PureScript application to fetch the current Bitcoin price. This journey will not only enhance your understanding of PureScript and APIs but also provide you with a practical tool for cryptocurrency data retrieval.

Whether you are a seasoned PureScript developer or new to the language, this guide aims to provide valuable insights and practical steps to effectively interact with the Kraken API. So, let's dive in and explore the intersection of functional programming and cryptocurrency data fetching.

Setting Up Your PureScript Environment

Getting started with PureScript requires setting up the appropriate development environment. This section will guide you through the installation of the PureScript compiler, Spago (the PureScript package manager and build tool), and the creation of a new PureScript project.
Installing PureScript
Prerequisites

Node.js: PureScript compiles to JavaScript, so Node.js is required to run the resulting code. Install the latest version of Node.js from nodejs.org.

Installation Steps

Install PureScript: Use npm (Node.js package manager) to install PureScript globally. Open your terminal or command prompt and run:

npm install -g purescript
Enter fullscreen mode Exit fullscreen mode

Verify Installation: Ensure PureScript is installed correctly by checking its version:

purs --version
Enter fullscreen mode Exit fullscreen mode

Installing Spago

Spago is a PureScript package manager and build tool, designed to work with the PureScript package set.
Installation Steps

Install Spago: Again, use npm to install Spago globally:

npm install -g spago
Enter fullscreen mode Exit fullscreen mode

Verify Installation: Check if Spago is installed properly:

spago --version
Enter fullscreen mode Exit fullscreen mode

Setting Up a New PureScript Project

Now that you have PureScript and Spago installed, you can set up a new PureScript project.
Creating the Project

Create a New Directory: Make a new directory for your project and navigate into it:

mkdir my-purescript-project
cd my-purescript-project
Enter fullscreen mode Exit fullscreen mode

Initialize the Project: Use Spago to initialize a new PureScript project:

spago init
Enter fullscreen mode Exit fullscreen mode

This command will create a new PureScript project in your current directory. It includes some basic files:

src/Main.purs: A sample PureScript source file.

test/Main.purs: A sample test file for your project.

spago.dhall: Configuration file for your project dependencies and build settings.

Exploring the Project

Take a moment to explore the structure of your new PureScript project. The src directory will hold your PureScript code, and test is for your test files. The spago.dhall file allows you to manage dependencies and specify project settings.
Next Steps

With your PureScript environment set up, you're ready to start writing PureScript code and explore its capabilities. The next section will introduce you to the Kraken API, which we will use to fetch Bitcoin prices.

Understanding the Kraken API

Before diving into coding, it's crucial to understand the Kraken API, which will be our gateway to fetching Bitcoin prices. This section will provide an overview of what the Kraken API offers, focusing on the specific endpoint we'll use for retrieving Bitcoin prices.

What is the Kraken API?

Kraken is a popular cryptocurrency exchange that provides a feature-rich API. This API allows developers to access market data, manage accounts, execute trades, and more. For our purpose, we are interested in the public market data that Kraken provides, specifically the current price of Bitcoin.
Key Features of the Kraken API

Public and Private Endpoints: The API offers both public and private endpoints. Public endpoints provide market data like asset prices, order book details, and recent trades.

Private endpoints, which require authentication, are for managing accounts and executing trades.

Rate Limits: Kraken imposes rate limits to ensure fair usage of their API. It’s important to be aware of these limits when designing your application to avoid being temporarily banned from the API.

Data Format: Responses from the Kraken API are typically in JSON format, making it easy to parse and use in your application.

The Endpoint for Bitcoin Prices

To fetch Bitcoin prices, we will use a specific public endpoint provided by Kraken:

Endpoint URL: https://api.kraken.com/0/public/Ticker

Query Parameters: To retrieve Bitcoin data, we need to specify the pair parameter. For Bitcoin-to-USD, the parameter is pair=XBTUSD.

Understanding the Response

The response from this endpoint will be in JSON format and will contain several pieces of information, including the current ask price, bid price, and last traded price. Here’s a simplified example of what the response might look like:


{
  "error": [],
  "result": {
    "XXBTZUSD": {
      "a": ["50000.00000", "1", "1.000"],
      "b": ["49995.00000", "1", "1.000"],
      "c": ["50000.00000", "0.00345678"]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

In this response:

a is the ask array, where a[0] is the best ask price.
b is the bid array, with b[0] being the best bid price.
c is the last trade closed array, c[0] being the last trade price.

Next Steps

With a clear understanding of the Kraken API, particularly the endpoint for fetching Bitcoin prices, we are now ready to move into the practical aspects of using PureScript to make HTTP requests and process this data.

In the following sections, we will discuss how to make HTTP requests in PureScript, parse the JSON responses, and specifically extract the Bitcoin price information from the Kraken API's response. This will involve exploring some of the functional programming paradigms that PureScript offers, ensuring a robust and type-safe approach to interacting with external APIs.

Making HTTP Requests in PureScript

To fetch the Bitcoin price from the Kraken API, we need to make HTTP requests from our PureScript application. PureScript offers several libraries for handling HTTP requests and responses, one of which is purescript-affjax. This section will guide you through using this library to send requests to the Kraken API and handle the responses.

Understanding purescript-affjax

purescript-affjax is a popular library in the PureScript ecosystem for making asynchronous HTTP requests. It uses the Aff monad, which handles asynchronous code in a functional way. This library simplifies the process of making HTTP requests and parsing responses.
Installing purescript-affjax

Before you can use purescript-affjax, you need to add it to your project. You can do this using Spago, the PureScript package manager.

Add the Dependency: Run the following command in your project directory:

spago install affjax
Enter fullscreen mode Exit fullscreen mode

Making a GET Request

To fetch data from the Kraken API, we will use a GET request. Here’s a basic example of how to make a GET request to the Kraken API using purescript-affjax.
Importing Necessary Modules

First, import the necessary modules in your PureScript file:


import Prelude

import Affjax (AJAX, get)
import Affjax.ResponseFormat (json)
import Effect.Aff (launchAff_)
import Effect.Class.Console (log)
Enter fullscreen mode Exit fullscreen mode

Writing the Request Function

Now, let's write a function to perform the GET request:


fetchBitcoinPrice :: Effect Unit
fetchBitcoinPrice = launchAff_ do
  response <- get json "https://api.kraken.com/0/public/Ticker?pair=XBTUSD"
  case response of
    Left error -> log $ "Request failed: " <> show error
    Right res -> log $ "Received response: " <> show res.body
Enter fullscreen mode Exit fullscreen mode

In this function:

launchAff_ is used to execute an asynchronous action.
get json makes a GET request and expects a JSON response.

The URL "https://api.kraken.com/0/public/Ticker?pair=XBTUSD" is the Kraken API endpoint for the Bitcoin price.

The response is either an error (Left error) or a successful response (Right res), which we log to the console. (If you are interested in more details about this topic, I have written about it in detail in the following article: PureScript Get Request - How to Make a HTTP Request in PS )

Running the Function

To run this function, you can call fetchBitcoinPrice from your Main.purs file or wherever you handle your application's entry point.

Next Steps

Having set up the basic structure for making HTTP requests, the next step is to parse the JSON response from the Kraken API. We will need to define PureScript types that correspond to the structure of the API response and write functions to extract the Bitcoin price information. This will involve using PureScript's strong type system to ensure that our data handling is both correct and efficient.

Parsing API Responses

After making an HTTP request to the Kraken API, the next crucial step is parsing the JSON response to extract meaningful data. PureScript, with its strong type system, offers a reliable way to handle JSON parsing. This section will guide you through the process of parsing the Kraken API response and extracting the Bitcoin price information.
Understanding JSON Parsing in PureScript

In PureScript, JSON parsing is typically done using the purescript-foreign-generic library, which provides tools for decoding and encoding JSON in a type-safe manner. This involves defining PureScript types that mirror the structure of the JSON data you expect to receive and then using these types to decode the JSON.

Installing purescript-foreign-generic

If you haven’t already, you'll need to add purescript-foreign-generic to your project:

spago install foreign-generic
Enter fullscreen mode Exit fullscreen mode

Defining PureScript Types for Kraken Response

Based on the structure of the Kraken API response, we'll define corresponding PureScript types. Here's an example:


import Prelude

import Data.Foreign.Class (class Decode, class Encode)
import Data.Foreign.Generic (defaultOptions, genericDecode, genericEncode, Options)
import Foreign.Class (class ReadForeign, read)

-- Define a type for the response
newtype KrakenResponse = KrakenResponse
  { result :: Result
  , error :: Array String
  }

derive instance genericKrakenResponse :: Generic KrakenResponse _
instance decodeKrakenResponse :: Decode KrakenResponse where
  decode = genericDecode defaultOptions
instance encodeKrakenResponse :: Encode KrakenResponse where
  encode = genericEncode defaultOptions

-- Define a type for the Result
type Result = Record (Ticker :: Ticker)

-- Define a type for the Ticker
type Ticker = Record
  ( lastTradePrice :: Array String
  )

derive instance genericTicker :: Generic Ticker _
instance decodeTicker :: Decode Ticker where
  decode = genericDecode defaultOptions
instance encodeTicker :: Encode Ticker where
  encode = genericEncode defaultOptions
Enter fullscreen mode Exit fullscreen mode

Parsing the JSON Response

With the types defined, we can now parse the JSON response from the Kraken API:


parseKrakenResponse :: String -> Either String KrakenResponse
parseKrakenResponse jsonString =
  case read jsonString of
    Left error -> Left $ "Error parsing JSON: " <> show error
    Right value -> case decode value of
      Left error -> Left $ "Error decoding KrakenResponse: " <> show error
      Right response -> Right response
Enter fullscreen mode Exit fullscreen mode

In this function, read attempts to parse the raw JSON string, and decode tries to convert the parsed JSON into our KrakenResponse type. The function returns either an error message or the successfully parsed response.
Extracting Bitcoin Price

Once we have the KrakenResponse, we can extract the Bitcoin price:


extractBitcoinPrice :: KrakenResponse -> Maybe String
extractBitcoinPrice response =
  response.result.XXBTZUSD.lastTradePrice
Enter fullscreen mode Exit fullscreen mode

This function navigates through the KrakenResponse to find the last traded price of Bitcoin.

Next Steps

Now that we have the mechanism to parse the Kraken API response and extract the Bitcoin price, the final step is to integrate this parsing logic with our HTTP request function. We will update the function to not only fetch data from the Kraken API but also to parse the response and extract the relevant Bitcoin price information, handling any potential errors along the way. This will complete our PureScript application for fetching Bitcoin prices from the Kraken API.

Fetching Bitcoin Price from Kraken

Having set up the HTTP request functionality and the JSON parsing mechanism, we are now ready to combine these components to fetch the current Bitcoin price from the Kraken API. This section will walk you through the process of integrating the HTTP request with the JSON parsing to retrieve and display the Bitcoin price.

Integrating HTTP Requests with JSON Parsing

We'll update our fetchBitcoinPrice function to not only make the HTTP request but also to parse the response and extract the Bitcoin price.

Updated fetchBitcoinPrice Function


import Prelude

import Affjax (AJAX, get)
import Affjax.ResponseFormat (json)
import Effect.Aff (Aff, launchAff_)
import Effect.Class.Console (log)

-- Other imports and type definitions from previous sections go here

fetchBitcoinPrice :: Aff Unit
fetchBitcoinPrice = do
  response <- get json "https://api.kraken.com/0/public/Ticker?pair=XBTUSD"
  case response of
    Left error -> 
      log $ "Request failed: " <> show error
    Right res -> 
      case parseKrakenResponse (show res.body) of
        Left parseError -> 
          log $ "Parsing failed: " <> parseError
        Right krakenResponse ->
          case extractBitcoinPrice krakenResponse of
            Nothing ->
              log "Could not extract Bitcoin price."
            Just price ->
              log $ "The current Bitcoin price is: " <> price

launchFetch :: Effect Unit
launchFetch = launchAff_ fetchBitcoinPrice
Enter fullscreen mode Exit fullscreen mode

In this updated function:

We make the GET request to the Kraken API.

If the request is successful, we attempt to parse the response using parseKrakenResponse.

If parsing is successful, we extract the Bitcoin price using extractBitcoinPrice.

Finally, we log the result to the console.

Error Handling

The function includes error handling at each step:

If the HTTP request fails, we log the request error.
If parsing the response fails, we log the parsing error.
If we cannot extract the Bitcoin price, we log an appropriate message.

Running the Application

To run the application and fetch the Bitcoin price, call launchFetch from your application's entry point, typically in the Main.purs file.


module Main where

import Prelude
import Effect (Effect)
import MyModule (launchFetch)  -- Replace with the actual module name

main :: Effect Unit
main = do
  launchFetch
Enter fullscreen mode Exit fullscreen mode

Conclusion

With the fetchBitcoinPrice function in place, your PureScript application is now capable of fetching real-time Bitcoin price data from the Kraken API. This not only demonstrates the power of PureScript in handling HTTP requests and JSON parsing but also gives you a practical tool for cryptocurrency data retrieval.

Remember, this example can be extended or modified to fetch different types of data from the Kraken API or other similar services, showcasing the versatility and capability of PureScript in working with external APIs.

Top comments (0)