Available Currencies For Websockets and SocketIO
A list of the available currencies for streaming data can be seen at Full Currencies list.
We also have CFDs for live endpoint, See full CFD list page, also can see below the list to all the CFDs we provide through our live endpoint (USD at the end of the CFD code does not imply that data is in dollar ):
Commodities: COPPERUSD (Copper), OILUSD (US OIL), UKOILUSD (UK OIL), NATGASUSD (Natural Gas)
Indices: UK100USD (FTSE), SPX500USD, FRA40USD (CAC), GER30USD (DAX), JPN225USD (Nikkei), NAS100USD (Nasdaq), USA30USD (Dow), HKG33USD (Hang Seng), AUS200USD
Websocket
Websockets are 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 seprated symbol string to login and subcribe (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"} |
On message |
Connection Event / Recieve |
Will receive a JSON for the currencies subscribed with symbol, bid, ask, mid, and timestamp" |
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
}
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.
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 succesful 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
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();
}
}
}