DEV Community

Cover image for Kotlin Guide for Retrieving Forex Market Data
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on

Kotlin Guide for Retrieving Forex Market Data

In today’s interconnected financial landscape, currency exchange rates have a significant impact on the global economy. For software developers, having access to reliable and real-time foreign exchange (forex) data is crucial for creating robust financial tools and applications. TraderMade offers a robust API that delivers real-time market data, historical exchange rates, and currency conversion information for a diverse range of currency pairs.

This Kotlin-based tutorial will guide you through using the TraderMade API with the Kotlin programming language. It covers the entire process—from setting up your Kotlin development environment to retrieving and displaying forex data from the API.

API Key

To start using the TraderMade API, create an account, go to the API section of the dashboard, select a suitable plan, and copy your unique API key for integration.

Let’s Begin Coding

To ensure clarity, we’ve broken down this Kotlin tutorial into manageable steps. Let's start by setting up the development environment.

Environment Setup

The following essential libraries are imported at the beginning of the code:

1. Retrofit – This library facilitates HTTP communication with REST APIs. It streamlines the process by enabling you to define API endpoints through Kotlin interfaces.

2. GsonConverterFactory – Used for converting API JSON responses into Kotlin data classes. This factory uses the popular Gson library to handle the JSON parsing.

3. OkHttpClient – Acts as the underlying HTTP client for Retrofit. It provides customization options for your network requests, such as timeout settings and interceptors.

4. Logger – This utility records log messages during runtime, making it easier to debug and trace the application’s behavior.

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit
import java.util.logging.Logger
Enter fullscreen mode Exit fullscreen mode

Defining Data Models

In this step, we create two Kotlin data classes that mirror the structure of the API response:

1. LiveCurrencyResponse – This class captures the complete response returned by the API. It includes a list of Quote objects, each representing a real-time forex quote.

2. Quote – This class contains the detailed attributes for each currency rate, including:

a) Ask – The selling price at which the currency is offered.

b) Bid – The buying price that a trader is willing to pay.

c) Mid – The average of the bid and ask prices, representing the mid-market rate.

d) base_currency and quote_currency – Indicate the pair of currencies being exchanged (e.g., USD as the base and EUR as the quote).

data class LiveCurrencyResponse(val quotes: List<Quote>)
data class Quote(val ask: Double, val bid: Double, val mid: Double, val base_currency: String, val quote_currency: String)
Enter fullscreen mode Exit fullscreen mode

Creating the API Interface

This interface outlines the API endpoints and the methods used to interact with them:

1. @get("live") – This annotation indicates that the request is a GET call directed to the API’s “live” endpoint.

2. getLiveCurrencyData – This method defines the necessary parameters for the GET request:

a) apiKey – Your personal API key used for authenticating requests.

b) currencyPair – The specific currency pair you want data for (e.g., "USDEUR").

3. The method returns a Call object, which represents an asynchronous request. When executed, it retrieves the response from the API.

interface LiveCurrencyApiService {
    @GET("live")
    fun getLiveCurrencyData(@Query("api_key") apiKey: String, @Query("currency") currencyPair: String): Call<LiveCurrencyResponse>
}
Enter fullscreen mode Exit fullscreen mode

Setting Up the Main Function

The main function begins by creating an instance of the Logger to enable logging. Next, it defines the API key and specifies the currency pair to be tracked—here, USD to EUR. This configuration is essential, as these values are required to perform the API call.

fun main() {
    val logger = Logger.getLogger("TraderMadeLogger")
    // Replace your API key
    val apiKey = "API_KEY"
    val baseCurrency = "USD"
    val quoteCurrency = "EUR"
Enter fullscreen mode Exit fullscreen mode

Configuring OkHttpClient

In this step, we set up the OkHttpClient with specific timeout configurations:

1. Connect Timeout – Specifies the maximum time the client will wait while attempting to establish a connection.

2. Write Timeout – Specifies the maximum duration allowed for sending data to the server.

3. Read Timeout – Sets the limit for how long the client will wait to receive a response from the server.

These configurations help prevent the application from freezing and allow it to handle network delays or failures more effectively.

// OkHttpClient setup
    val client = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build()
Enter fullscreen mode Exit fullscreen mode

Configuring Retrofit

Next, we set up Retrofit:

1) baseUrl: This is the base URL of the API you're working with. In this case, it's the TraderMade API. Note that this URL directs you to the endpoint where you can access live currency data; however, you can modify the URL to access other services, such as currency conversions or forex historical data.

2) Client: The OkHttpClient instance was configured earlier.

3) addConverterFactory: We add the GsonConverterFactory to handle JSON-to-Kotlin object conversion.

// Retrofit setup
    val retrofit = Retrofit.Builder()
        .baseUrl("https://marketdata.tradermade.com/api/v1/")
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
Enter fullscreen mode Exit fullscreen mode

Making the API Request

At this stage. We need to perform an API call to retrieve data:

1. Create – An instance of LiveCurrencyApiService is initialized using the configured Retrofit object.

2. getLiveCurrencyData – This method is invoked with the API key and desired currency pair as arguments. It returns a Call object representing the pending request.

3. Execute – The execute function sends a synchronous request to the API. The Logger is used to monitor and log the request's progress for better visibility and debugging.

// Fetch live currency data
    val liveCurrencyService = retrofit.create(LiveCurrencyApiService::class.java)
    val liveCurrencyCall = liveCurrencyService.getLiveCurrencyData(apiKey, "$baseCurrency$quoteCurrency")
    logger.info("Starting live currency request...")
    val liveCurrencyResponse = liveCurrencyCall.execute()
    logger.info("Live currency request finished.")
Enter fullscreen mode Exit fullscreen mode

Handling the Response

Once the API call completes, the response is processed as follows:

1. isSuccessful – Verifies whether the request was completed successfully.

2. Quote – If the response is valid, the first Quote object from the returned list is retrieved.

3. resultText – The details of the quote, including ask, bid, and mid prices, are displayed.

4. Error Handling – If no quote is available or the request fails, informative messages are printed to indicate the issue.

if (liveCurrencyResponse.isSuccessful) {
        val quote = liveCurrencyResponse.body()?.quotes?.firstOrNull()
        if (quote != null) {
            val resultText = "Ask: ${quote.ask}\nBid: ${quote.bid}\nMid: ${quote.mid}"
            println(resultText)
        } else {
            println("No quotes found.")
        }
    } else {
        println("Live currency request failed with code: ${liveCurrencyResponse.code()}")
    }
Enter fullscreen mode Exit fullscreen mode

Cleaning Up

To ensure efficient resource management and avoid memory leaks, the OkHttpClient is properly closed:

1. shutdown – Terminates the executor service responsible for handling network operations.

2. Evict All – Clears all unused or idle connections from the connection pool.

3. Logger – Logs the end of the program, indicating that execution has completed.

client.dispatcher.executorService.shutdown()
    client.connectionPool.evictAll()
    logger.info("Program finished.")
}
Enter fullscreen mode Exit fullscreen mode

Note
In this Kotlin tutorial, we demonstrated how to work with the live currency data endpoint using the base URL https://marketdata.tradermade.com/api/v1/. TraderMade, however, provides various other endpoints that can be accessed by adjusting the URL. For instance, you can retrieve historical exchange rates or perform currency conversions by modifying the endpoint path accordingly. Check TraderMade's Data Documentation to explore API endpoints and other details.

Compiling the Kotlin Code

To convert your Kotlin source file (Realtime.kt) into bytecode executable by the Java Virtual Machine (JVM), use the following command:

1. kotlinc – This is the Kotlin compiler that transforms your Kotlin code into Java-compatible bytecode.

2. -cp – Short for "classpath," this option tells the compiler where to locate any external libraries your project depends on. Here, it includes multiple JAR files stored in the libs/ directory.

3. -d out – Specifies the output directory for the compiled bytecode. The compiled files will be saved to the out folder.

4. src/Realtime.kt – This indicates the file path to your Kotlin source code, which in this case is located in the src directory.

kotlinc -cp "libs/okio-jvm-3.9.0.jar;libs/retrofit-2.11.0.jar;libs/converter-gson-2.11.0.jar;libs/okhttp-4.12.0.jar;libs/okhttp-urlconnection-4.12.0.jar;libs/gson-2.11.0.jar;libs/annotations-24.1.0.jar;libs/kotlin-stdlib-2.0.0.jar" -d out src/Realtime.kt
Enter fullscreen mode Exit fullscreen mode

Running the Compiled Kotlin Code

To execute the compiled Kotlin application, use the following command, which runs the program through the Java Virtual Machine (JVM):

1. Java – This command launches the Java Virtual Machine (JVM) and runs the specified class.

2. -cp "out; libs/..." – The -cp option sets the classpath, pointing to both the out directory (where compiled classes are stored) and the libs/ directory (containing required external libraries), so the JVM knows where to locate all dependencies.

3. com.api.RealtimeKt – This refers to the fully qualified name of the class containing the main function. Kotlin appends Kt to the class name when compiling, so Realtime.kt becomes RealtimeKt.

java -cp "out;libs/okio-jvm-3.9.0.jar;libs/retrofit-2.11.0.jar;libs/converter-gson-2.11.0.jar;libs/okhttp-4.12.0.jar;libs/okhttp-urlconnection-4.12.0.jar;libs/gson-2.11.0.jar;libs/annotations-24.1.0.jar;libs/kotlin-stdlib-2.0.0.jar" com.api.RealtimeKt
Enter fullscreen mode Exit fullscreen mode

Putting It All Together

These commands work in sequence: the first compiles your Kotlin source code into JVM-compatible bytecode while linking the necessary JAR files, and the second runs the compiled program, utilizing those same dependencies at runtime.

Output

Below is the resulting output from running the program.

Aug 09, 2024 4:04:10 PM com.api.RealtimeKt main
INFO: Starting live currency request...
Aug 09, 2024 4:04:12 PM com.api.RealtimeKt main
INFO: Live currency request finished.
Ask: 0.9155665
Bid: 0.9155581
Mid: 0.9155581
Aug 09, 2024 4:04:12 PM com.api.RealtimeKt main
INFO: Program finished.
Enter fullscreen mode Exit fullscreen mode

Conclusion

You’ve now completed the journey of using Kotlin to connect with the TraderMade API. This tutorial has provided you with the essential skills to access and utilize live forex data—a vital capability for developing modern financial software.

The same approach can be extended to support currency conversion and historical exchange rate features, giving you a versatile and scalable setup. As you continue building on this foundation, you’ll be well-equipped to develop more interactive and finance-focused applications.
If you need help or have any questions, please don't hesitate to reach out to us via our live chat or email support.

Please refer to the original tutorial published on our website: A Kotlin Tutorial to Fetch Market Data

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.