Documentation

Getting Started

We provide acurate and reliable forex data via easy-to-use delivery methods. We use WSS and WebSockets which make it easier to receive data. Authentication is over a secure WSS protocol and responses are in JSON Format.

Following are a few simple steps to start receiving the market data.

  1. 1. Sign up for API : Sign Up
  2. 2. Start your Socket trial : Start Trial .
  3. 3. Get your Streaming API key : Get your Streaming Data key .
  4. 4. Start getting data : Connect to API

Quick Start Guide

We have created several of tutorials to help you get started with our Forex Websocket API. Our tutorials cover various topics, such as Golang, Python, NodeJS, C#.

  1. See our quick start tutorials on getting started : How to start a WebSocket Trial

Authentication

You need to include your Forex API key with the initial request when you start your connection. You can find your API key under your account once you log in.

Our streaming data API documentation is extensive, and you can see below all the available routes and currencies to help you integrate our data within your applications. If you are new to WebSockets and SocketIO, visit our tutorial page that explains sockets in greater detail.

Available Currencies For WebSockets and SocketIO

We support over 60+ currency pairs on our Websockets. To access a list of currencies available, visit our websocket currencies list page.

See the complete list of global Market CFDs we provide via WebSockets. You need to add USD at the end of each CFD code for Websockets. For example. TSLA should be TSLAUSD.

Websocket

WebSocket is a bidirectional protocol to get real-time data to help you build applications that require low-latency data. The TraderMade WebSocket API provides a simple implementation with easy setup in minutes.

URL
Protocol
Description
marketdata.trader
made.com/feedadv
wss
Connect using the above url and once open send JSON including streaming API key(userKey) and comma-separated symbol string to login and subscribe (as shown below).
Events
Type
Description
On open
Connection Event / Send
Send user key and comma seperated symbol string in JSON format - example: {"userKey":"streaming_api_key", "symbol":"EURUSD,GBPUSD"}
If you want to receive SSV or CSV format just add fmt in above json to get that format - example: {"userKey":"streaming_api_key", "symbol":"EURUSD,GBPUSD", "fmt":"CSV"} .
On message
Connection Event / Receive
Will receive a JSON for the currencies subscribed with symbol, bid, ask, mid, and timestamp" (Optional). If you provide fmt parameters on open, then CSV or SSV will be returned. .
On disconnect
Connection Event
On disconnect, you will receive a response if there is a reason for the disconnection.
Send JSON On open (To Recv JSON)
                        {"userKey":"streaming_api_key", "symbol":"EURUSD,GBPUSD"}
                    
Recv JSON On message
{
    "symbol": "EURUSD",
    "ts": "1614076641",
    "bid": 1.21469,
    "ask": 1.2147,
    "mid": 1.214695
}
                    
Send JSON On open (To Recv SSV)
{"userKey":"streaming_api_key", "symbol":"EURUSD,GBPUSD", "fmt":"SSV"}
                    
Recv SSV On message
EURUSD 1614692703994 1.20232 1.20232
GBPUSD 1614692849259 1.38971 1.38974
                    

SocketIO

SocketIO is a wrapper for websocket protocol implementation to get real-time data to help you build applications that require low-latency data. The TraderMade SocketIO API can be connected in minutes using our simple implementation documentation. Our SocketIO is currently compatible with version 2 only.

URL
Protocol
Description
marketdata.tradermade.com
https
Connect using the above url and emit streaming API key (userKey) on login and listen on handshake for successful login.
Events
Type
Description
login
Connection Event / Send
Login by sending JSON - example: {userKey: "streaming_api_key"}
handshake
Connection Event / Receive
Successful connection will receive a response, "Welcome to the TMS Data Feed."
symbolSub
Data Event / Send
Subscribe to a new currency pair by sending JSON - example: {symbol: "USDJPY"}. Send multiple requests to subscribe to more than one symbol.
subResponse
Data Event / Receive
On subscribing to a new currency pair will receive the "Subscribed to symbol" message.
price
Data event / Receive
If a symbol is subscribed will receive "symbol bid ask mid date time" string, which is space delimited
disconnect
Connection Event
On disconnect, you will receive a response if there is a reason for disconnection.
Emit JSON On login
{userKey: "streaming_api_key"}
                    
Recv string On handshake
Welcome to the TMS Data Feed
                    
Emit JSON On symbolSub
{symbol: "USDJPY"}
                    
Recv string On subResponse
Subscribed to symbol
                    
Recv CSV On price
USDJPY 105.265 105.265 105.264999 20201015-15:18:15.215
                    

Websocket Examples

Your Streaming API Key is included in all the sample codes when logged in. So you can use any example right away. Only you can see this key.

                                require_once("vendor/autoload.php");

$client = new WebSocket\Client("wss://marketdata.tradermade.com/feedadv");

$message =  $client->receive();
echo $message;

$client->text("{\"userKey\":\"streaming_api_key\", \"symbol\":\"GBPUSD,EURUSD\"}");

while(true){
        $message =  $client->receive();

        if(strcmp($message,"connected") !== 0){
                $decoded_json = json_decode($message);
                echo $decoded_json->symbol, " ", $decoded_json->ts, " ", $decoded_json->bid, " ", $decoded_json->ask, "\n";
        }
}
                            
                                import websocket
import time

try:
	import thread
except ImportError:
	import _thread as thread



f = open("webSocketTester.log", "a")

def on_message(ws, message):
	print(message)
	f.write(message  +  "\n" )
	f.flush()


def on_error(ws, error):
	print(error)

def on_close(ws):
	print("### closed ###")

def on_open(ws):
	def run(*args):
		ws.send("{\"userKey\":\"streaming_api_key\", \"symbol\":\"GBPUSD\"}")
	thread.start_new_thread(run, ())


if __name__ == "__main__":
	ws = websocket.WebSocketApp("wss://marketdata.tradermade.com/feedadv",
								on_message = on_message,
								on_error = on_error,
								on_close = on_close)
	ws.on_open = on_open
	ws.run_forever()


                            
                                library(websocket)
library(jsonlite)

{
    ws <- WebSocket$new("wss://marketdata.tradermade.com/feedadv")
    ws$onMessage(function(event) {
    d <- event$data
    if (d != "Connected"){
        json = fromJSON(d)
        cat(" Symbol ", json$symbol, json$ts, json$bid, json$ask, json$mid)
    }
    })
    ws$onOpen(function(event) {
            ws$send("{\"userKey\":\"streaming_api_key\", \"symbol\":\"GBPUSD,EURUSD\"}")
    })
    }
                            
                                // +build ignore

package main

import (
    "flag"
    "log"
    "net/url"
    "os"
    "os/signal"
    "time"
    "github.com/gorilla/websocket"

)


func main() {
    flag.Parse()
    log.SetFlags(0)

    messageOut := make(chan string)

    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt)
    u := url.URL{Scheme: "wss", Host: "marketdata.tradermade.com", Path: "/feedadv",}
    log.Printf("connecting to %s", u.String())

    c, resp, err := websocket.DefaultDialer.Dial(u.String(), nil);
    if err != nil {
    log.Printf("handshake failed with status %d", resp.StatusCode)
    log.Fatal("dial:", err)
    }
    defer c.Close()

    done := make(chan struct{})

    go func() {
    defer close(done)
    for {
        _, message, err := c.ReadMessage()
        if err != nil {
        log.Println("read:", err)
        return
        }
        log.Printf("recv: %s", message)
        if string(message) == "Connected"{
        log.Printf("Send Sub Details: %s", message)
        messageOut <- "{\"userKey\":\"streaming_api_key\", \"symbol\":\"EURUSD\"}"
        }
    }
    }()

    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()

    for {
    select {
    case <-done:
        return
    case m := <-messageOut:
        log.Printf("Send Message %s", m)
        err := c.WriteMessage(websocket.TextMessage, []byte(m))
        if err != nil {
        log.Println("write:", err)
        return
        }
    case t := <-ticker.C:
        err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
        if err != nil {
        log.Println("write:", err)
        return
        }
    case <-interrupt:
        log.Println("interrupt")

        // Cleanly close the connection by sending a close message and then
        // waiting (with timeout) for the server to close the connection.
        err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
        if err != nil {
        log.Println("write close:", err)
        return
        }
        select {
        case <-done:
        case <-time.After(time.Second):
        }
        return
    }
    }
}
                            
                                using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.WebSockets;

using Websocket.Client;

namespace TraderMadeWebSocketTest
{
    class Program
    {
        private string streaming_API_Key = "streaming_api_key";

        static void Main(string[] args)
        {
            Program prg = new Program();
            prg.Initialize();
        }

        private void Initialize()
        {
            Console.CursorVisible = false;

            try
            {
                var exitEvent = new ManualResetEvent(false);
                var url = new Uri("wss://marketdata.tradermade.com/feedadv");
                

                using (var client = new WebsocketClient(url))
                {
                    client.ReconnectTimeout = TimeSpan.FromSeconds(30);

                    client.ReconnectionHappened.Subscribe(info =>
                    {
                        Console.WriteLine("Reconnection happened, type: " + info.Type);
                    });

                    client.MessageReceived.Subscribe(msg =>
                    {
                        Console.WriteLine("Message received: " + msg);

                        if (msg.ToString().ToLower() == "connected")
                        {
                            string data = "{\"userKey\":\"" + streaming_api_key + "\", \"symbol\":\"EURUSD,GBPUSD,USDJPY\"}";
                            client.Send(data);
                        }
                    });

                    client.Start();

                    //Task.Run(() => client.Send("{ message }"));

                    exitEvent.WaitOne();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: " + ex.ToString());
            }

            Console.ReadKey();
        }

    }
}
                            
                                const WebSocket = require ('ws');

var reconnectInterval = 1000 * 10
var ws;

var connect = function(){

const ws = new WebSocket ('wss://marketdata.tradermade.com/feedadv');

ws.on('open', function open() {
    ws.send("{\"userKey\":\"streaming_api_key\", \"symbol\":\"GBPUSD\"}");
});

ws.on('close', function() {
    console.log('socket close : will reconnect in ' + reconnectInterval );
    setTimeout(connect, reconnectInterval)
});

ws.on('message', function incoming(data) {
    console.log(data);
});
};
connect();
                                
                            
                                package client;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;

public class ClientCaller {

    public static void main(String[] args) throws Exception {
        CountDownLatch latch = new CountDownLatch(100);

        WebSocket ws = HttpClient
                .newHttpClient()
                .newWebSocketBuilder()
                .buildAsync(URI.create("wss://marketdata.tradermade.com/feedadv"), new WebSocketClient(latch))
                .join();
//        ws.sendText("Hello!", true);
        latch.await();
    }

    private static class WebSocketClient implements WebSocket.Listener {
        private final CountDownLatch latch;

        public WebSocketClient(CountDownLatch latch) { this.latch = latch; }

        @Override
        public void onOpen(WebSocket webSocket) {
            System.out.println("onOpen using subprotocol " + webSocket.getSubprotocol());
            WebSocket.Listener.super.onOpen(webSocket);
            webSocket.sendText("{\"userKey\":\"streaming_api_key\", \"symbol\":\"GBPUSD\"}", true);

        }

        @Override
        public CompletionStage onText(WebSocket webSocket, CharSequence data, boolean last) {
            System.out.println("onText received " + data);
            latch.countDown();
            return WebSocket.Listener.super.onText(webSocket, data, last);
        }

        @Override
        public void onError(WebSocket webSocket, Throwable error) {
            System.out.println("Bad day! " + webSocket.toString());
            WebSocket.Listener.super.onError(webSocket, error);
        }
    }
}
                                
                            

SocketIO Examples

Your Streaming API Key is included in all the sample codes when logged in. So you can use any example right away. Only you can see this key.

                                var io = require('socket.io-client');

var socket = io.connect('https://marketdata.tradermade.com', {reconnect: true});

var connected = false;


socket.on('connect', function () {
    console.log('Connected! Please CTRL+C and restart if you see this messsage more than twice');
    console.log("disconnecting and reconnecting can take upto a minute and multiple attempts")
    console.log(".......")
    socket.emit('login', {userKey: "streaming_api_key"});
});

socket.on('disconnect', function (msg) {
    console.log(msg);
});

socket.on('handshake', function (msg) {
    console.log(msg);
    connected = true;
    socket.emit("symbolSub", {symbol: "GBPUSD"});
    socket.emit("symbolSub", {symbol: "EURUSD"});

});

socket.on('subResponse', function (msg) {
    console.log(msg)

});

socket.on('message', function (msg) {
    console.log(msg)
});

socket.on('price', function (message){
    var data = message.split(" ")
    console.log(data[0] + " " + data[1] + " " + data[2] + " " + data[3] + " " + parseDate(data[4]))

});

function parseDate(dateString){
    var reggie = /(\d{4})(\d{2})(\d{2})-(\d{2}):(\d{2}):(\d{2}).(\d{3})/;
    var dateArray = reggie.exec(dateString);
    var dateObject = new Date(
    (+dateArray[1]),
    (+dateArray[2])-1, // Careful, month starts at 0!
    (+dateArray[3]),
    (+dateArray[4]),
    (+dateArray[5]),
    (+dateArray[6])
    );
    return dateObject
}
                                    
                                
                            
                                import socketio


# standard Python
sio = socketio.Client()

@sio.event
def connect():
    print("I'm connected!")
    sio.emit('login', {'userKey': 'streaming_api_key'})

@sio.event
def connect_error():
    print("The connection failed!")

@sio.event
def message(data):
    print('I received a message!')

@sio.on('handshake')
def on_message(data):
    print('HandShake', data)
    sio.emit('symbolSub', {'symbol': 'USDJPY'})
    sio.emit('symbolSub', {'symbol': 'GBPUSD'})
    sio.emit('symbolSub', {'symbol': 'EURUSD'})

@sio.on('price')
def on_message(data):
    print('Price Data ', data)


sio.connect('https://marketdata.tradermade.com')