We have created a number of tutorials to help you get started with our Websocket API. Our tutorials cover topics such as Golang, Python, NodeJS, C#, etc.
You need to include your API key with the initial request when you start your connection. You can find your api key under your account once you login.
Our streaming data API documentation is extensive and you can see below all the available routes, currencies available 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. A list of currencies available can be accessed by visting our
websocket currencies list page.
See full list of CFDswe provide for websockets. You need to add USD at the end of the CFD code for websockets. You can also see below the full CFD codes we provide:
Commodities: CopperUSD, OILUSD (US), UKOILUSD, NATGASUSD
Indices: USDXUSD (USD Index), UK100USD (FTSE), SPX500USD, FRA40USD (CAC), GER30USD (DAX), JPN225USD (Nikkei), NAS100USD (Nasdaq), USA30USD (Dow), HKG33USD (Hang Seng), AUS200USD
Equities: AAPLUSD, FBUSD, AMZNUSD, NFLXUSD, TSLAUSD, GOOGLUSD, BABAUSD, TWTRUSD, BACUSD, BIDUUSD
Websocket
WebSocket is a bidirectional protocol to get real-time data to help you build applications that require low latency data. The TraderMade WebSockets API provides a simple implementation that can be set up in minutes.
Connection Details
URL |
Protocol |
Description |
marketdata.tradermade.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 / Recieve |
Will receive a JSON for the currencies subscribed with symbol, bid, ask, mid, and timestamp"
(Optional) fmt parameters is provided on open then either CSV or SSV will be returned. |
On disconnect |
Connection Event |
On disconnect will recieve response if there a reason for disconnection |
{"userKey":"streaming_api_key", "symbol":"EURUSD,GBPUSD"}
{
"symbol": "EURUSD",
"ts": "1614076641",
"bid": 1.21469,
"ask": 1.2147,
"mid": 1.214695
}
{"userKey":"streaming_api_key", "symbol":"EURUSD,GBPUSD", "fmt":"SSV"}
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.
Connection Details
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 / Recieve |
Successful connection will recieve 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 / Recieve |
On subscribing to a new currency pair will recieve "Subscribed to symbol" |
price |
Data event / Recieve |
If symbol is subscribed will recieve "symbol bid ask mid datetime" string which is space delimited |
disconnect |
Connection Event |
On disconnect will recieve response if there a reason for disconnection |
{userKey: "streaming_api_key"}
Welcome to the TMS Data Feed
{symbol: "USDJPY"}
Subscribed to symbol
USDJPY 105.265 105.265 105.264999 20201015-15:18:15.215
Nodejs Websocket Example
Streaming API Key |
Your Streaming API Key is included in all the sample codes if you are logged in, so you can use any example right away. Only you can see this key. |
Below is an example Nodejs Websocket Client
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();
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();
Nodejs SocketIO Example
Below is an example Nodejs SocketIO Client
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
}
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');
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: "USDJPY"});
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
}
Python Websocket Example
Below is an example Python Websocket Client
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()
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()
Python SocketIO Example
Below is an example Python SocketIO Client
python-engineio==3.14.2
python-socketio==4.3.1
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')
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')
Go Websocket Example
Below is an example Go Websocket Client
// +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
}
}
}
// +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
}
}
}
C# Websocket Example
Below is an example C# Websocket Client
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();
}
}
}
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();
}
}
}
R Websocket Example
Below is an example R websocket Client
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\"}")
})
}
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\"}")
})
}
PHP Websocket Example
Below is an example PHP websocket Client
<?php
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";
}
}
?>
<?php
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";
}
}
?>
Java Websocket Example
Below is an example Java Websocket Client
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);
}
}
}
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);
}
}
}