DEV Community

Cover image for Integrating Market Data into Your Go Applications with TraderMade's SDK
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on

Integrating Market Data into Your Go Applications with TraderMade's SDK

Learn how to fetch real-time and historical market data in Go using TraderMade's easy-to-use SDK.

If you're a Go developer aiming to integrate real-time or historical market data into your applications, TraderMade's Go SDK offers a streamlined solution. Whether you're building trading tools, analytics dashboards, or financial applications, this SDK simplifies access to Forex, cryptocurrency, precious metals, and CFD data.

Getting Started

First, use Go version 1.21 or higher to support modules. Then, retrieve the TraderMade Go SDK:

go get github.com/tradermade/Go-SDK
Enter fullscreen mode Exit fullscreen mode

After obtaining the SDK, initialize the REST client with your API key:

import (
    tradermade "github.com/tradermade/Go-SDK/rest"
)

client := tradermade.NewRESTClient("YOUR_API_KEY")
Enter fullscreen mode Exit fullscreen mode

You can acquire your API key by signing up on the TraderMade website.

Fetching Live Forex Rates

To retrieve live rates for specific currency pairs, such as EUR/USD and Gold (XAU/USD):

currencyPairs := []string{"EURUSD", "XAUUSD"}
liveRates, err := client.GetLiveRates(currencyPairs)
if err != nil {
    log.Fatalf("Error fetching live rates: %v", err)
}

for _, quote := range liveRates.Quotes {
    fmt.Printf("Base: %s, Quote: %s, Bid: %f, Ask: %f, Mid: %f\n",
        quote.BaseCurrency, quote.QuoteCurrency, quote.Bid, quote.Ask, quote.Mid)
}
Enter fullscreen mode Exit fullscreen mode

This code initializes the REST client, defines the desired currency pairs, fetches their live rates, and prints out the base currency, quote currency, bid, ask, and mid prices.

Performing Currency Conversion

To convert an amount from one currency to another in real-time:

convertResult, err := client.ConvertCurrency("EUR", "GBP", 1000.0)
if err != nil {
    log.Fatalf("Error fetching conversion data: %v", err)
}

fmt.Printf("Converted %s to %s:\n", convertResult.BaseCurrency, convertResult.QuoteCurrency)
fmt.Printf("Quote: %f\n", convertResult.Quote)
fmt.Printf("Total: %f\n", convertResult.Total)
fmt.Printf("Requested Time: %s\n", convertResult.RequestedTime)
fmt.Printf("Timestamp: %d\n", convertResult.Timestamp)
Enter fullscreen mode Exit fullscreen mode

This snippet converts 1,000 EUR to GBP, displaying the conversion rate, total amount, request time, and timestamp.

Retrieving Hourly Time Series Data

For historical analysis or charting, you might need time series data. Here's how to fetch hourly data for EUR/USD:

timeSeriesDataHourly, err := client.GetTimeSeriesData("EURUSD", "2024-10-01 10:00", "2024-10-02 11:00", "hourly", 4)
if err != nil {
    log.Fatalf("Error fetching hourly time series data: %v", err)
}

for _, data := range timeSeriesDataHourly.TimeSeries {
    fmt.Printf("Time: %s, Open: %f, High: %f, Low: %f, Close: %f\n",
        data.Date, data.Open, data.High, data.Low, data.Close)
}
Enter fullscreen mode Exit fullscreen mode

This code fetches hourly data between October 1, 2024, 10:00 AM and October 2, 2024, 11:00 AM, printing out the open, high, low, and close prices for each hour.

Example: Real-Time Forex Data with WebSocket

WebSocket feeds are ideal for ultra-low-latency applications like trading terminals or automated bots. TraderMade supports WebSocket streaming for live updates.
Here’s a quick example:

package main

import (
    "github.com/tradermade/Go-SDK/websocket"
)

func main() {
    ws := websocket.NewWebSocketClient("YOUR_API_KEY")
    ws.Connect()
    ws.Subscribe([]string{"EURUSD", "GBPUSD"})

    for msg := range ws.MessageChannel {
        fmt.Printf("Received tick: %v\n", msg)
    }
}
Enter fullscreen mode Exit fullscreen mode

This function opens a WebSocket connection and allows you to subscribe to live updates for EUR/USD and GBP/USD. Each incoming tick is pushed to a channel for real-time processing.

Using the WebSocket Client

  • Initialize the WebSocket client with your API key and the currency pairs you wish to subscribe to.
  • Configure connection settings, including automatic retries and reconnection behavior.
  • Set up event handlers:

Connection Handler: Triggered when the WebSocket successfully connects.

client.SetConnectedHandler(func(connectedMsg tradermadews.ConnectedMessage) {
    fmt.Printf("WebSocket connected: %s\n", connectedMsg.Message)
})
Enter fullscreen mode Exit fullscreen mode

Quote Message Handler: Processes incoming real-time market data such as bid/ask quotes.

client.SetMessageHandler(func(quote tradermadews.QuoteMessage, humanTimestamp string) {
    fmt.Printf("Received quote: Symbol=%s Bid=%.5f Ask=%.5f Timestamp=%s (Human-readable: %s)\n",
        quote.Symbol, quote.Bid, quote.Ask, quote.Ts, humanTimestamp)
})
Enter fullscreen mode Exit fullscreen mode

Reconnection Handler: Notifies you when the client is attempting to reconnect.

client.SetReconnectionHandler(func(attempt int) {
    fmt.Printf("Reconnecting... (Attempt %d)\n", attempt)
})

Enter fullscreen mode Exit fullscreen mode

Enable graceful shutdown on user interrupt (e.g., Ctrl+C).

c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
<-c
fmt.Println("Shutting down WebSocket client...")

Enter fullscreen mode Exit fullscreen mode

Summary

  • Connects to the WebSocket feed using secure credentials.
  • Receives real-time updates for Forex, stock indices, and precious metals.
  • Automatically handles disconnections and attempts to reconnect.
  • Provides handlers for key lifecycle events: connection, message, and reconnection.
  • Supports clean shutdowns for a robust and reliable client experience.

The WebSocket client is ideal for apps needing real-time FX market data with minimal latency.

Additional Resources

TraderMade's Go SDK also supports fetching historical data, performing currency conversions, and retrieving time series data. For comprehensive details and advanced usage, refer to the TraderMade REST API Documentation and explore their GitHub repository.

By integrating TraderMade's Go SDK into your projects, you can efficiently access a wide range of financial data, enhancing the functionality and reliability of your applications.

Wrapping Up

TraderMade’s Go SDK equips you with everything needed to tap into a world of financial data with minimal effort. From real-time streaming to historical insights and currency conversion, it's easily accessible through a clean, idiomatic Go interface.

Please refer to the originally published tutorial on our website: Accessing Market Data with TraderMade's Go Library

Also, go through the other Golang Tutorials:
Your First Golang REST API Client

Your First Golang WebSocket Client

Top comments (0)